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
|
---|---|---|---|---|---|
11686c8ee4800c3cf70a26670f42973ba1314d97
| 16,332 |
//
// StepChangeCheckViewController.swift
// Cosmostation
//
// Created by yongjoo on 23/05/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import UIKit
import Alamofire
import BitcoinKit
import SwiftKeychainWrapper
class StepChangeCheckViewController: BaseViewController, PasswordViewDelegate {
@IBOutlet weak var btnBack: UIButton!
@IBOutlet weak var btnConfirm: UIButton!
@IBOutlet weak var rewardAddressChangeFee: UILabel!
@IBOutlet weak var rewardAddressChangeDenom: UILabel!
@IBOutlet weak var currentRewardAddress: UILabel!
@IBOutlet weak var newRewardAddress: UILabel!
@IBOutlet weak var memoLabel: UILabel!
var pageHolderVC: StepGenTxViewController!
override func viewDidLoad() {
super.viewDidLoad()
pageHolderVC = self.parent as? StepGenTxViewController
WUtils.setDenomTitle(pageHolderVC.chainType!, rewardAddressChangeDenom)
}
func onUpdateView() {
let feeAmout = WUtils.localeStringToDecimal((pageHolderVC.mFee?.amount[0].amount)!)
if (pageHolderVC.chainType! == ChainType.COSMOS_MAIN || pageHolderVC.chainType! == ChainType.BAND_MAIN || pageHolderVC.chainType! == ChainType.SECRET_MAIN ||
pageHolderVC.chainType! == ChainType.IOV_MAIN || pageHolderVC.chainType! == ChainType.IOV_TEST || pageHolderVC.chainType! == ChainType.CERTIK_MAIN || pageHolderVC.chainType! == ChainType.CERTIK_TEST) {
rewardAddressChangeFee.attributedText = WUtils.displayAmount(feeAmout.stringValue, rewardAddressChangeFee.font, 6, pageHolderVC.chainType!)
} else if (pageHolderVC.chainType! == ChainType.DIPPER_MAIN || pageHolderVC.chainType! == ChainType.DIPPER_TEST) {
rewardAddressChangeFee.attributedText = WUtils.displayAmount(feeAmout.stringValue, rewardAddressChangeFee.font, 12, pageHolderVC.chainType!)
} else if (pageHolderVC.chainType! == ChainType.IRIS_MAIN) {
rewardAddressChangeFee.attributedText = WUtils.displayAmount(feeAmout.stringValue, rewardAddressChangeFee.font, 18, pageHolderVC.chainType!)
}
currentRewardAddress.text = pageHolderVC.mCurrentRewardAddress
newRewardAddress.text = pageHolderVC.mToChangeRewardAddress
currentRewardAddress.adjustsFontSizeToFitWidth = true
newRewardAddress.adjustsFontSizeToFitWidth = true
memoLabel.text = pageHolderVC.mMemo
}
override func enableUserInteraction() {
self.onUpdateView()
self.btnBack.isUserInteractionEnabled = true
self.btnConfirm.isUserInteractionEnabled = true
}
@IBAction func onClickBefore(_ sender: UIButton) {
self.btnBack.isUserInteractionEnabled = false
self.btnConfirm.isUserInteractionEnabled = false
pageHolderVC.onBeforePage()
}
@IBAction func onClickConfirm(_ sender: UIButton) {
let title = NSLocalizedString("reward_address_warnning_title", comment: "")
let msg1 = NSLocalizedString("reward_address_notice_msg", comment: "")
let msg2 = NSLocalizedString("reward_address_notice_msg2", comment: "")
let msg = msg1 + msg2
let range = (msg as NSString).range(of: msg2)
let noticeAlert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
let attributedMessage: NSMutableAttributedString = NSMutableAttributedString(
string: msg,
attributes: [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12.0)
]
)
attributedMessage.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 14.0), range: range)
attributedMessage.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
noticeAlert.setValue(attributedMessage, forKey: "attributedMessage")
noticeAlert.addAction(UIAlertAction(title: NSLocalizedString("continue", comment: ""), style: .destructive, handler: { _ in
self.onShowPasswordCheck()
}))
noticeAlert.addAction(UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .default, handler: { _ in
self.dismiss(animated: true, completion: nil)
}))
self.present(noticeAlert, animated: true) {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissAlertController))
noticeAlert.view.superview?.subviews[0].addGestureRecognizer(tapGesture)
}
}
func onShowPasswordCheck() {
let passwordVC = UIStoryboard(name: "Password", bundle: nil).instantiateViewController(withIdentifier: "PasswordViewController") as! PasswordViewController
self.navigationItem.title = ""
self.navigationController!.view.layer.add(WUtils.getPasswordAni(), forKey: kCATransition)
passwordVC.mTarget = PASSWORD_ACTION_CHECK_TX
passwordVC.resultDelegate = self
self.navigationController?.pushViewController(passwordVC, animated: false)
}
func passwordResponse(result: Int) {
if (result == PASSWORD_RESUKT_OK) {
self.onFetchAccountInfo(pageHolderVC.mAccount!)
}
}
func onFetchAccountInfo(_ account: Account) {
self.showWaittingAlert()
var url: String?
if (pageHolderVC.chainType! == ChainType.COSMOS_MAIN) {
url = COSMOS_URL_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.DIPPER_MAIN) {
url = DIPPER_URL_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.DIPPER_TEST) {
url = DIPPER_TEST_URL_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.IRIS_MAIN) {
url = IRIS_LCD_URL_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.BAND_MAIN) {
url = BAND_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.SECRET_MAIN) {
url = SECRET_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.IOV_MAIN) {
url = IOV_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.IOV_TEST) {
url = IOV_TEST_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.CERTIK_MAIN) {
url = CERTIK_ACCOUNT_INFO + account.account_address
} else if (pageHolderVC.chainType! == ChainType.CERTIK_TEST) {
url = CERTIK_TEST_ACCOUNT_INFO + account.account_address
}
let request = Alamofire.request(url!, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:]);
request.responseJSON { (response) in
switch response.result {
case .success(let res):
if (self.pageHolderVC.chainType! == ChainType.COSMOS_MAIN || self.pageHolderVC.chainType! == ChainType.DIPPER_MAIN || self.pageHolderVC.chainType! == ChainType.DIPPER_TEST) {
guard let responseData = res as? NSDictionary,
let info = responseData.object(forKey: "result") as? [String : Any] else {
_ = BaseData.instance.deleteBalance(account: account)
self.hideWaittingAlert()
self.onShowToast(NSLocalizedString("error_network", comment: ""))
return
}
let accountInfo = AccountInfo.init(info)
_ = BaseData.instance.updateAccount(WUtils.getAccountWithAccountInfo(account, accountInfo))
BaseData.instance.updateBalances(account.account_id, WUtils.getBalancesWithAccountInfo(account, accountInfo))
self.onGenModifyRewardAddressTx()
} else if (self.pageHolderVC.chainType! == ChainType.IRIS_MAIN) {
guard let info = res as? [String : Any] else {
_ = BaseData.instance.deleteBalance(account: account)
self.hideWaittingAlert()
self.onShowToast(NSLocalizedString("error_network", comment: ""))
return
}
let accountInfo = AccountInfo.init(info)
_ = BaseData.instance.updateAccount(WUtils.getAccountWithAccountInfo(account, accountInfo))
BaseData.instance.updateBalances(account.account_id, WUtils.getBalancesWithAccountInfo(account, accountInfo))
self.onGenModifyRewardAddressTx()
} else if (self.pageHolderVC.chainType! == ChainType.BAND_MAIN || self.pageHolderVC.chainType! == ChainType.SECRET_MAIN || self.pageHolderVC.chainType! == ChainType.IOV_MAIN ||
self.pageHolderVC.chainType! == ChainType.IOV_TEST || self.pageHolderVC.chainType! == ChainType.CERTIK_MAIN || self.pageHolderVC.chainType! == ChainType.CERTIK_TEST ) {
guard let responseData = res as? NSDictionary,
let info = responseData.object(forKey: "result") as? [String : Any] else {
_ = BaseData.instance.deleteBalance(account: account)
self.hideWaittingAlert()
self.onShowToast(NSLocalizedString("error_network", comment: ""))
return
}
let accountInfo = AccountInfo.init(info)
_ = BaseData.instance.updateAccount(WUtils.getAccountWithAccountInfo(account, accountInfo))
BaseData.instance.updateBalances(account.account_id, WUtils.getBalancesWithAccountInfo(account, accountInfo))
self.onGenModifyRewardAddressTx()
}
case .failure( _):
self.hideWaittingAlert()
self.onShowToast(NSLocalizedString("error_network", comment: ""))
}
}
}
func onGenModifyRewardAddressTx() {
DispatchQueue.global().async {
var stdTx:StdTx!
guard let words = KeychainWrapper.standard.string(forKey: self.pageHolderVC.mAccount!.account_uuid.sha1())?.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ") else {
return
}
do {
let pKey = WKey.getHDKeyFromWords(words, self.pageHolderVC.mAccount!)
let msg = MsgGenerator.genGetModifyRewardAddressMsg(self.pageHolderVC.mAccount!.account_address,
self.pageHolderVC.mToChangeRewardAddress!,
self.pageHolderVC.chainType!)
var msgList = Array<Msg>()
msgList.append(msg)
let stdMsg = MsgGenerator.getToSignMsg(WUtils.getChainId(self.pageHolderVC.mAccount!.account_base_chain),
String(self.pageHolderVC.mAccount!.account_account_numner),
String(self.pageHolderVC.mAccount!.account_sequence_number),
msgList,
self.pageHolderVC.mFee!,
self.pageHolderVC.mMemo!)
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try? encoder.encode(stdMsg)
let rawResult = String(data:data!, encoding:.utf8)?.replacingOccurrences(of: "\\/", with: "/")
let rawData: Data? = rawResult!.data(using: .utf8)
let hash = Crypto.sha256(rawData!)
let signedData: Data? = try Crypto.sign(hash, privateKey: pKey.privateKey())
var genedSignature = Signature.init()
var genPubkey = PublicKey.init()
genPubkey.type = COSMOS_KEY_TYPE_PUBLIC
genPubkey.value = pKey.privateKey().publicKey().data.base64EncodedString()
genedSignature.pub_key = genPubkey
genedSignature.signature = WKey.convertSignature(signedData!)
genedSignature.account_number = String(self.pageHolderVC.mAccount!.account_account_numner)
genedSignature.sequence = String(self.pageHolderVC.mAccount!.account_sequence_number)
var signatures: Array<Signature> = Array<Signature>()
signatures.append(genedSignature)
stdTx = MsgGenerator.genSignedTx(msgList, self.pageHolderVC.mFee!, self.pageHolderVC.mMemo!, signatures)
} catch {
if(SHOW_LOG) { print(error) }
}
DispatchQueue.main.async(execute: {
let postTx = PostTx.init("sync", stdTx.value)
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try? encoder.encode(postTx)
do {
let params = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
var url = "";
if (self.pageHolderVC.chainType! == ChainType.COSMOS_MAIN) {
url = COSMOS_URL_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.DIPPER_MAIN) {
url = DIPPER_URL_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.DIPPER_TEST) {
url = DIPPER_TEST_URL_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.IRIS_MAIN) {
url = IRIS_LCD_URL_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.BAND_MAIN) {
url = BAND_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.SECRET_MAIN) {
url = SECRET_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.IOV_MAIN) {
url = IOV_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.IOV_TEST) {
url = IOV_TEST_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.CERTIK_MAIN) {
url = CERTIK_BORAD_TX
} else if (self.pageHolderVC.chainType! == ChainType.CERTIK_TEST) {
url = CERTIK_TEST_BORAD_TX
}
let request = Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:])
request.responseJSON { response in
var txResult = [String:Any]()
switch response.result {
case .success(let res):
if(SHOW_LOG) { print("AddressChange ", res) }
if let result = res as? [String : Any] {
txResult = result
}
case .failure(let error):
if(SHOW_LOG) { print("AddressChange error ", error) }
if (response.response?.statusCode == 500) {
txResult["net_error"] = 500
}
}
if (self.waitAlert != nil) {
self.waitAlert?.dismiss(animated: true, completion: {
self.onStartTxDetail(txResult)
})
}
}
}catch {
print(error)
}
});
}
}
}
| 55.740614 | 217 | 0.588477 |
29774cf02125961ff77eeb5e75ebac2300d7f774
| 1,077 |
//
// BlurhashCache.swift
// Blurhash
//
// Created by Marc Rousavy on 04.09.20.
// Copyright © 2020 Facebook. All rights reserved.
//
import Foundation
final class BlurhashCache {
var blurhash: String?
var decodeWidth: Int
var decodeHeight: Int
var decodePunch: Float
init(blurhash: String?, decodeWidth: Int, decodeHeight: Int, decodePunch: Float) {
self.blurhash = blurhash
self.decodeWidth = decodeWidth
self.decodeHeight = decodeHeight
self.decodePunch = decodePunch
}
init(blurhash: NSString?, decodeWidth: NSNumber, decodeHeight: NSNumber, decodePunch: NSNumber) {
self.blurhash = blurhash as String?
self.decodeWidth = decodeWidth.intValue
self.decodeHeight = decodeHeight.intValue
self.decodePunch = decodePunch.floatValue
}
final func isDifferent(blurhash: NSString, decodeWidth: NSNumber, decodeHeight: NSNumber, decodePunch: NSNumber) -> Bool {
return self.blurhash != blurhash as String || self.decodeWidth != decodeWidth.intValue || self.decodeHeight != decodeHeight.intValue || self.decodePunch != decodePunch.floatValue
}
}
| 30.771429 | 180 | 0.756732 |
23e3b339c6eec675357b201adbf4c019de6d5ea2
| 166 |
import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(SourceKitHipsterTests.allTests),
]
}
#endif
| 16.6 | 49 | 0.686747 |
ef0580c8ad12b03a6b8a839fa626912617804a8b
| 2,725 |
//
// Database.swift
// AzureData
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
/// Represents a database in the Azure Cosmos DB account.
///
/// - Remark:
/// Each Azure Cosmos DB database account can have zero or more databases.
/// A database in Azure Cosmos DB is a logical container for document collections and users.
/// Refer to [databases](http://azure.microsoft.com/documentation/articles/documentdb-resources/#databases) for more details on databases.
public struct Database : CodableResource {
public static var type = "dbs"
public static var list = "Databases"
public private(set) var id: String
public private(set) var resourceId: String
public private(set) var selfLink: String?
public private(set) var etag: String?
public private(set) var timestamp: Date?
public private(set) var altLink: String? = nil
public mutating func setAltLink(to link: String) {
self.altLink = link
}
public mutating func setEtag(to tag: String) {
self.etag = tag
}
/// Gets the self-link for collections from the Azure Cosmos DB service.
public private(set) var collectionsLink: String?
/// Gets the self-link for users from the Azure Cosmos DB service.
public private(set) var usersLink: String?
public init (_ id: String) { self.id = id; resourceId = "" }
}
extension Database {
enum CodingKeys: String, CodingKey {
case id
case resourceId = "_rid"
case selfLink = "_self"
case etag = "_etag"
case timestamp = "_ts"
case collectionsLink = "_colls"
case usersLink = "_users"
}
init(id: String, resourceId: String, selfLink: String?, etag: String?, timestamp: Date?, altLink: String?, collectionsLink: String?, usersLink: String?) {
self.id = id
self.resourceId = resourceId
self.selfLink = selfLink
self.etag = etag
self.timestamp = timestamp
self.altLink = altLink
self.collectionsLink = collectionsLink
self.usersLink = usersLink
}
}
extension Database : CustomDebugStringConvertible {
public var debugDescription: String {
return "Database :\n\tid : \(self.id)\n\tresourceId : \(self.resourceId)\n\tselfLink : \(self.selfLink.valueOrNilString)\n\tetag : \(self.etag.valueOrNilString)\n\ttimestamp : \(self.timestamp.valueOrNilString)\n\taltLink : \(self.altLink.valueOrNilString)\n\tcollectionsLink : \(self.collectionsLink.valueOrNilString)\n\tusersLink : \(self.usersLink.valueOrNilString)\n--"
}
}
| 35.855263 | 381 | 0.658716 |
1883462096211c4b750e8facac68a13aceddd9b4
| 6,972 |
//
// PasswordViewController.swift
// Pods
//
// Created by Daniel Lozano Valdés on 12/12/16.
//
//
import UIKit
import Validator
protocol PasswordViewControllerDelegate: class {
func didSelectRecover(_ viewController: UIViewController, email: String)
func passwordDidSelectBack(_ viewController: UIViewController)
}
class PasswordViewController: UIViewController, BackgroundMovable, KeyboardMovable {
// MARK: - Properties
weak var delegate: PasswordViewControllerDelegate?
weak var configurationSource: ConfigurationSource?
var recoverAttempted = false
// MARK: Keyboard movable
var selectedField: UITextField?
var offset: CGFloat = 0.0
// MARK: Background Movable
var movableBackground: UIView {
get {
return backgroundImageView
}
}
// MARK: Outlet's
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var recoverButton: Buttn!
@IBOutlet weak var backButton: Buttn!
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var backgroundImageView: GradientImageView!
@IBOutlet weak var textfieldCenterLayoutConstraint: NSLayoutConstraint!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
initBackgroundMover()
customizeAppearance()
setupValidation()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHideNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func loadView() {
self.view = viewFromNib()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - Setup
func customizeAppearance() {
configureFromSource()
setupFonts()
}
func configureFromSource() {
guard let config = configurationSource else {
return
}
backgroundImageView.image = config.backgroundImage
logoImageView.image = config.secondaryLogoImage
emailTextField.placeholder = config.emailPlaceholder
//emailTextField.errorColor = config.errorTintColor
recoverButton.setTitle(config.recoverPasswordButtonText, for: .normal)
}
func setupFonts() {
emailTextField.font = Font.montserratRegular.get(size: 13)
recoverButton.titleLabel?.font = Font.montserratRegular.get(size: 15)
}
// MARK: - Action's
@IBAction func didSelectBack(_ sender: AnyObject) {
delegate?.passwordDidSelectBack(self)
}
@IBAction func didSelectRecover(_ sender: AnyObject) {
recoverAttempted = true
guard let email = emailTextField.text else {
return
}
validateFields {
delegate?.didSelectRecover(self, email: email)
}
}
}
// MARK: - Validation
extension PasswordViewController {
func setupValidation() {
//setupValidationOn(field: emailTextField, rules: ValidationService.emailRules)
}
func setupValidationOn(field: SkyFloatingLabelTextField, rules: ValidationRuleSet<String>) {
field.validationRules = rules
field.validateOnInputChange(enabled: true)
field.validationHandler = validationHandlerFor(field: field)
}
func validationHandlerFor(field: SkyFloatingLabelTextField) -> ((ValidationResult) -> Void) {
return { result in
switch result {
case .valid:
guard self.recoverAttempted == true else {
break
}
field.errorMessage = nil
case .invalid(let errors):
guard self.recoverAttempted == true else {
break
}
if let errors = errors as? [ValidationError] {
field.errorMessage = errors.first?.message
}
}
}
}
func validateFields(success: () -> Void) {
let result = emailTextField.validate()
switch result {
case .valid:
//emailTextField.errorMessage = nil
success()
case .invalid(let errors):
if let errors = errors as? [ValidationError] {
//emailTextField.errorMessage = errors.first?.message
}
}
}
@objc func keyboardWillShowNotification(_ notification: Notification) {
let keyboardEndFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let convertedKeyboardEndFrame = view.convert(keyboardEndFrame, from: view.window)
textfieldCenterLayoutConstraint.constant -= 120
UIView.animate(withDuration: 1.0) {
self.logoImageView.alpha = 0.0
self.view.layoutIfNeeded()
}
}
@objc func keyboardWillHideNotification(_ notification: Notification) {
textfieldCenterLayoutConstraint.constant = 0
UIView.animate(withDuration: 1.0) {
self.logoImageView.alpha = 1.0
self.view.layoutIfNeeded()
}
}
}
// MARK: - UITextField Delegate
extension PasswordViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
selectedField = textField
addAccessoryView(selectedField!)
}
func textFieldDidEndEditing(_ textField: UITextField) {
selectedField = nil
}
func addAccessoryView(_ textField: UITextField) -> Void {
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: NSLocalizedString("Close", comment: ""), style: .done, target: self, action: #selector(PasswordViewController.doneButtonTapped(button:)))
let flexItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolBar.items = [flexItem, doneButton]
toolBar.tintColor = .black
textField.inputAccessoryView = toolBar
}
@objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
// do you stuff with done here
selectedField?.resignFirstResponder()
selectedField = nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
let nextResponder = view.viewWithTag(nextTag) as UIResponder!
if nextResponder != nil {
nextResponder?.becomeFirstResponder()
} else {
textField.resignFirstResponder()
//didSelectRecover(self)
}
return false
}
}
| 28.929461 | 185 | 0.64759 |
4b622b0d2c32bb6f8d915ddbee37555f8cba5390
| 1,388 |
//
// GopherTests.swift
// GopherTests
//
// Created by Dane Acena on 8/12/21.
//
import XCTest
@testable import Gopher
class GopherTests: XCTestCase {
var sut: URLSession!
override func setUpWithError() throws {
try super.setUpWithError()
sut = URLSession(configuration: .default)
}
override func tearDownWithError() throws {
sut = nil
try super.tearDownWithError()
}
func testValidApiCallGetsHTTPStatusCode200() throws {
//given
let urlString = "https://api.github.com/repos/apple/swift/commits?per_page=25"
let url = URL(string: urlString)!
// 1
let promise = expectation(description: "Status code: 200")
//when
let dataTask = sut.dataTask(with: url){ _, response, error in
// then
if let error = error {
XCTFail("Error: \(error.localizedDescription)")
return
} else if let statusCode = (response as? HTTPURLResponse)?.statusCode {
if statusCode == 200 {
// 2
promise.fulfill()
} else{
XCTFail("Status code: \(statusCode)")
}
}
}
dataTask.resume()
// 3
wait(for: [promise], timeout: 5)
}
}
| 26.188679 | 86 | 0.522334 |
621085d0d78d4ea5c74279444e7ad8ce6df35736
| 1,262 |
//
// HCMFHeaderTableViewCell.swift
// sfmobilefood
//
// Created by Isabel Yepes on 30/10/15.
// Copyright © 2015 Hacemos Contactos. All rights reserved.
//
import UIKit
class HCMFHeaderTableViewCell: UITableViewCell {
@IBOutlet weak var cartName: UILabel!
@IBOutlet weak var cartFood: UILabel!
@IBOutlet weak var expandButton: UIButton!
@IBOutlet weak var headerContentView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
var tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doNothing:"))
self.addGestureRecognizer(tapGesture)
}
func doNothing(sender: AnyObject) {
//Catch other taps over header cell different than expand button
}
@IBAction func toggleOpen(sender: AnyObject) {
self.toggleOpenWithUserAction(true)
}
func toggleOpenWithUserAction(userAction: Bool) {
// toggle the expand button state
self.expandButton.selected = !self.expandButton.selected
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 25.755102 | 117 | 0.676704 |
1a5cada7442008ef9d098b92b1c1ff1f2137ef75
| 45 |
var age = 22
print("I am \(age) years old.")
| 15 | 31 | 0.6 |
297ed858020690356960449d52fdb029a0f787a6
| 12,401 |
//
// ReceiveInLightningView.swift
// falcon
//
// Created by Manu Herrera on 05/10/2020.
// Copyright © 2020 muun. All rights reserved.
//
import UIKit
import core
protocol ReceiveDelegate: AnyObject {
func didTapOnShare(_ shareText: String)
func didTapOnCopy(_ copyText: String)
func didTapOnAddAmount()
func didToggleOptions(visible: Bool)
}
protocol ReceiveInLightningViewDelegate: ReceiveDelegate {
func didTapOnCompatibilityAddressInfo()
func didTapOnInvoice(_ invoice: String)
func didTapOnRequestNewInvoice()
}
struct IncomingInvoiceInfo {
// The raw string representation of the invoice
let rawInvoice: String
// This is the expiration date of the invoice represented in unix time
// Optional for future compatibility with invoices without expiration date
let expiresAt: Double?
var expirationTimeInSeconds: Int? {
guard let expiresAt = expiresAt else {
return nil
}
return Int(expiresAt - Date().timeIntervalSince1970)
}
var formattedExpirationTime: String? {
guard let seconds = expirationTimeInSeconds else {
return nil
}
let formatter = DateFormatter()
formatter.dateFormat = "mm:ss"
let timeInterval = Double(seconds)
let timeRemaining = Date(timeIntervalSince1970: timeInterval)
return formatter.string(from: timeRemaining)
}
}
final class ReceiveInLightningView: UIView {
private let stackView = UIStackView()
private let expirationNoticeView = NoticeView()
private let qrCodeView = QRCodeWithActionsView()
private let advancedOptionsView = LightningAdvancedOptionsView()
private let overlayView = UIView()
private let createAnotherInvoiceButton = SmallButtonView()
private var invoiceInfo: IncomingInvoiceInfo?
private var timer = Timer()
private lazy var constraintsWhenNoticeIsHidden = [
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 48)
]
private lazy var constraintsWhenNoticeIsVisible = [
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 16)
]
// We display a expiration warning message when the invoice has only 3 minutes remaining of expiration time
private let expirationMessageThresholdInSecs = 180
private weak var delegate: ReceiveInLightningViewDelegate?
init(delegate: ReceiveInLightningViewDelegate?) {
self.delegate = delegate
super.init(frame: .zero)
setUpView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func willMove(toWindow newWindow: UIWindow?) {
if newWindow == nil {
timer.invalidate()
}
}
private func setUpView() {
setUpStackView()
setUpExpiryNotice()
setUpQRCodeView()
setUpAdvancedOptionsView()
setUpOverlayView()
makeViewTestable()
}
// MARK: - Views Layout and configuration -
fileprivate func setUpStackView() {
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = .sideMargin
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.bottomAnchor.constraint(equalTo: bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
NSLayoutConstraint.activate(constraintsWhenNoticeIsHidden)
}
fileprivate func setUpQRCodeView() {
qrCodeView.translatesAutoresizingMaskIntoConstraints = false
qrCodeView.delegate = self
stackView.addArrangedSubview(qrCodeView)
stackView.setCustomSpacing(24, after: qrCodeView)
NSLayoutConstraint.activate([
qrCodeView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: .sideMargin),
qrCodeView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: -.sideMargin),
qrCodeView.topAnchor.constraint(equalTo: expirationNoticeView.bottomAnchor, constant: .sideMargin)
])
}
fileprivate func setUpExpiryNotice() {
expirationNoticeView.style = .notice
expirationNoticeView.text = L10n.ReceiveInLightningView.s1("")
.attributedForDescription()
expirationNoticeView.delegate = self
expirationNoticeView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(expirationNoticeView)
NSLayoutConstraint.activate([
expirationNoticeView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: .sideMargin),
expirationNoticeView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: -.sideMargin)
])
}
private func setExpirationNoticeHidden(_ isHidden: Bool) {
expirationNoticeView.isHidden = isHidden
if isHidden {
NSLayoutConstraint.deactivate(constraintsWhenNoticeIsVisible)
NSLayoutConstraint.activate(constraintsWhenNoticeIsHidden)
} else {
NSLayoutConstraint.deactivate(constraintsWhenNoticeIsHidden)
NSLayoutConstraint.activate(constraintsWhenNoticeIsVisible)
}
}
fileprivate func setUpAdvancedOptionsView() {
advancedOptionsView.translatesAutoresizingMaskIntoConstraints = false
advancedOptionsView.delegate = self
stackView.addArrangedSubview(advancedOptionsView)
NSLayoutConstraint.activate([
advancedOptionsView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor),
advancedOptionsView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor)
])
}
private func setUpOverlayView() {
overlayView.backgroundColor = Asset.Colors.background.color
overlayView.translatesAutoresizingMaskIntoConstraints = false
overlayView.isHidden = true
addSubview(overlayView)
NSLayoutConstraint.activate([
overlayView.leadingAnchor.constraint(equalTo: leadingAnchor),
overlayView.trailingAnchor.constraint(equalTo: trailingAnchor),
overlayView.topAnchor.constraint(equalTo: topAnchor),
overlayView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
let overlayStackView = UIStackView()
overlayStackView.translatesAutoresizingMaskIntoConstraints = false
overlayStackView.spacing = 16
overlayStackView.alignment = .center
overlayStackView.axis = .vertical
overlayView.addSubview(overlayStackView)
NSLayoutConstraint.activate([
overlayStackView.leadingAnchor.constraint(equalTo: overlayView.leadingAnchor, constant: .sideMargin),
overlayStackView.trailingAnchor.constraint(equalTo: overlayView.trailingAnchor, constant: -.sideMargin),
overlayStackView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
let expiredLabel = UILabel()
expiredLabel.style = .description
expiredLabel.attributedText = L10n.ReceiveInLightningView.s5
.attributedForDescription(alignment: .center)
expiredLabel.translatesAutoresizingMaskIntoConstraints = false
expiredLabel.numberOfLines = 0
overlayStackView.addArrangedSubview(expiredLabel)
NSLayoutConstraint.activate([
expiredLabel.leadingAnchor.constraint(equalTo: overlayStackView.leadingAnchor),
expiredLabel.trailingAnchor.constraint(equalTo: overlayStackView.trailingAnchor)
])
createAnotherInvoiceButton.isEnabled = true
createAnotherInvoiceButton.buttonText = L10n.ReceiveInLightningView.s6
createAnotherInvoiceButton.delegate = self
createAnotherInvoiceButton.backgroundColor = .clear
overlayStackView.addArrangedSubview(createAnotherInvoiceButton)
NSLayoutConstraint.activate([
createAnotherInvoiceButton.heightAnchor.constraint(equalToConstant: 40)
])
}
private func displayInvoiceExpiredView() {
overlayView.isHidden = false
}
private func startTimer() {
updateTimer()
timer = Timer.scheduledTimer(
timeInterval: 1,
target: self,
selector: .updateTimer,
userInfo: nil,
repeats: true
)
}
// MARK: - View actions -
@objc fileprivate func updateTimer() {
guard let expirationTimeRemainingInSecs = invoiceInfo?.expirationTimeInSeconds,
let formattedTime = invoiceInfo?.formattedExpirationTime else {
return
}
if expirationTimeRemainingInSecs <= 0 {
displayInvoiceExpiredView()
timer.invalidate()
return
}
advancedOptionsView.setExpirationTime(formattedTime)
if expirationTimeRemainingInSecs < expirationMessageThresholdInSecs {
setExpirationNoticeHidden(false)
updateExpireLabel(formattedTime: formattedTime)
} else {
setExpirationNoticeHidden(true)
}
}
private func updateExpireLabel(formattedTime: String) {
expirationNoticeView.text = L10n.ReceiveInLightningView.s1(formattedTime)
.set(font: Constant.Fonts.system(size: .opHelper))
.set(bold: formattedTime, color: Asset.Colors.muunGrayDark.color)
.set(underline: L10n.ReceiveInLightningView.s2, color: Asset.Colors.muunBlue.color)
}
// MARK: - View Controller actions -
func setAmount(_ bitcoinAmount: BitcoinAmount?) {
advancedOptionsView.setAmount(bitcoinAmount)
}
func displayInvoice(_ invoiceInfo: IncomingInvoiceInfo?) {
guard let invoiceInfo = invoiceInfo else {
setExpirationNoticeHidden(true)
qrCodeView.loadingText = L10n.ReceiveInLightningView.loading
qrCodeView.isLoading = true
advancedOptionsView.setExpirationTime(nil)
timer.invalidate()
return
}
qrCodeView.data = invoiceInfo.rawInvoice.uppercased().data(using: .utf8)
qrCodeView.label = invoiceInfo.rawInvoice
qrCodeView.isLoading = false
// Reset the view to initial state when displaying a new invoice
overlayView.isHidden = true
setExpirationNoticeHidden(true)
timer.invalidate()
self.invoiceInfo = invoiceInfo
// Restart the timer, it will take care of handling the expiration time of the invoice
startTimer()
}
}
extension ReceiveInLightningView: SmallButtonViewDelegate {
internal func button(didPress button: SmallButtonView) {
if button == createAnotherInvoiceButton {
delegate?.didTapOnRequestNewInvoice()
}
}
}
extension ReceiveInLightningView: QRCodeWithActionsViewDelegate {
internal func didTapQRCode() {
guard let invoiceInfo = invoiceInfo else { return }
delegate?.didTapOnCopy(invoiceInfo.rawInvoice)
}
internal func didTapLabel() {
guard let invoiceInfo = invoiceInfo else { return }
delegate?.didTapOnInvoice(invoiceInfo.rawInvoice)
}
internal func didTapOnCopy() {
guard let invoiceInfo = invoiceInfo else { return }
delegate?.didTapOnCopy(invoiceInfo.rawInvoice)
}
internal func didTapOnShare() {
guard let invoiceInfo = invoiceInfo else { return }
delegate?.didTapOnShare(invoiceInfo.rawInvoice)
}
}
extension ReceiveInLightningView: NoticeViewDelegate {
func didTapOnMessage() {
delegate?.didTapOnRequestNewInvoice()
}
}
extension ReceiveInLightningView: LightningAdvancedOptionsViewDelegate {
func didTapAddAmount() {
delegate?.didTapOnAddAmount()
}
func didToggleOptions(visible: Bool) {
delegate?.didToggleOptions(visible: visible)
}
}
extension ReceiveInLightningView: UITestablePage {
typealias UIElementType = UIElements.Pages.ReceivePage
private func makeViewTestable() {
makeViewTestable(qrCodeView, using: .qrCodeWithActions)
}
}
fileprivate extension Selector {
static let updateTimer = #selector(ReceiveInLightningView.updateTimer)
}
| 33.516216 | 117 | 0.698008 |
1452f536905c9e4391a809d44fd633af6ab93a3b
| 2,316 |
// Copyright 2018-2020 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment
// -- Generated Code; do not edit --
//
// SecurityTokenOperationsClientInput.swift
// SecurityTokenClient
//
import Foundation
import SmokeHTTPClient
import SecurityTokenModel
/**
Type to handle the input to the AssumeRole operation in a HTTP client.
*/
public typealias AssumeRoleOperationHTTPRequestInput = QueryHTTPRequestInput
/**
Type to handle the input to the AssumeRoleWithSAML operation in a HTTP client.
*/
public typealias AssumeRoleWithSAMLOperationHTTPRequestInput = QueryHTTPRequestInput
/**
Type to handle the input to the AssumeRoleWithWebIdentity operation in a HTTP client.
*/
public typealias AssumeRoleWithWebIdentityOperationHTTPRequestInput = QueryHTTPRequestInput
/**
Type to handle the input to the DecodeAuthorizationMessage operation in a HTTP client.
*/
public typealias DecodeAuthorizationMessageOperationHTTPRequestInput = QueryHTTPRequestInput
/**
Type to handle the input to the GetAccessKeyInfo operation in a HTTP client.
*/
public typealias GetAccessKeyInfoOperationHTTPRequestInput = QueryHTTPRequestInput
/**
Type to handle the input to the GetCallerIdentity operation in a HTTP client.
*/
public typealias GetCallerIdentityOperationHTTPRequestInput = QueryHTTPRequestInput
/**
Type to handle the input to the GetFederationToken operation in a HTTP client.
*/
public typealias GetFederationTokenOperationHTTPRequestInput = QueryHTTPRequestInput
/**
Type to handle the input to the GetSessionToken operation in a HTTP client.
*/
public typealias GetSessionTokenOperationHTTPRequestInput = QueryHTTPRequestInput
| 35.630769 | 99 | 0.805699 |
1147748167b11d31d9362d412117b099ae7dac0f
| 761 |
//
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]>
//
// SPDX-License-Identifier: MIT
//
/// A `ConnectionEffect` describes the affect of a `Response` on a connection.
/// This impacts stream connection types such as client, service or bidirectional streams
///
///
/// These values should not be directly set by an Apodini developer.
/// Use the possible `Response` static computed properties or functions to create a `Response`
public enum ConnectionEffect {
/// The connection should stay open
case open
/// The connection should be closed
case close
}
| 34.590909 | 135 | 0.708279 |
d5027d49d0dd133444f5b9d26c43894671d0c0df
| 6,500 |
//
// Copyright © 2021 DHSC. All rights reserved.
//
import Combine
import Domain
import Integration
import Interface
import Localization
import UIKit
internal protocol HomeScreenScenario: Scenario {
static var riskyPostcodeEnabled: Bool { get }
static var checkInEnabled: Bool { get }
static var shouldShowSelfDiagnosis: Bool { get }
static var localInformationEnabled: Bool { get }
}
extension HomeScreenScenario {
static func postcodeViewModel(parent: UIViewController) -> RiskLevelBanner.ViewModel? {
if Self.riskyPostcodeEnabled {
return RiskLevelBanner.ViewModel(
postcode: "SW12",
colorScheme: .green,
title: "SW12 is in Local Alert Level 1".apply(direction: currentLanguageDirection()),
infoTitle: "SW12 is in Local Alert Level 1",
heading: [],
body: [],
linkTitle: "Restrictions in your area",
linkURL: nil,
footer: [],
policies: [],
shouldShowMassTestingLink: .constant(true)
)
} else {
return nil
}
}
static var localInfoBannerViewModel: LocalInformationBanner.ViewModel? {
if Self.localInformationEnabled {
return .init(text: "A new variant of concern is in your area.", localInfoScreenViewModel: .init(header: "", body: []))
}
return nil
}
static var appController: AppController {
NavigationAppController { (parent: UINavigationController) in
let exposureNotificationsEnabled = CurrentValueSubject<Bool, Never>(true)
return HomeViewController(
interactor: Interactor(
viewController: parent,
checkInEnabled: checkInEnabled
),
riskLevelBannerViewModel: .constant(postcodeViewModel(parent: parent)),
localInfoBannerViewModel: .constant(localInfoBannerViewModel),
isolationViewModel: RiskLevelIndicator.ViewModel(isolationState: .constant(.notIsolating), paused: .constant(false), animationDisabled: .constant(false)),
exposureNotificationsEnabled: exposureNotificationsEnabled.property(initialValue: false),
exposureNotificationsToggleAction: { [weak parent] toggle in
parent?.showAlert(title: "Toggle state changed to \(toggle)")
},
shouldShowSelfDiagnosis: .constant(shouldShowSelfDiagnosis),
userNotificationsEnabled: .constant(false),
showFinancialSupportButton: .constant(true),
country: .constant(.england),
showLanguageSelectionScreen: nil
)
}
}
}
public class SuccessHomeScreenScenario: HomeScreenScenario {
public static var name = "Home Screen"
public static var kind = ScenarioKind.screen
public static var riskyPostcodeEnabled = true
public static var selfDiagnosisEnabled: Bool = true
public static var checkInEnabled: Bool = true
public static var shouldShowSelfDiagnosis = true
public static var localInformationEnabled = true
}
public class DisabledFeaturesHomeScreenScenario: HomeScreenScenario {
public static var name = "Home Screen – All Features disabled"
public static var kind = ScenarioKind.screen
public static var riskyPostcodeEnabled = false
public static var selfDiagnosisEnabled = false
public static var checkInEnabled: Bool = false
public static var shouldShowSelfDiagnosis = false
public static var localInformationEnabled = false
}
public class HomeScreenAlerts {
public static let diagnosisAlertTitle = "I don't feel well button tapped."
public static let isolationAdviceAlertTitle = "Read isolation advice button tapped."
public static let checkInAlertTitle = "Check-in into a venue."
public static let financeAlertTitle = "Financial Support button tapped"
public static let settingsAlertTitle = "Settings button tapped"
public static let aboutAlertTitle = "About tapped"
public static let linkTestResultTitle = "Link test result tapped"
public static let postcodeBannerAlertTitle = "Postcode banner tapped"
public static let localInfoBannerAlertTitle = "Local Information banner tapped"
public static let contactTracingHubAlertTitle = "Contact Tracing Hub tapped"
public static let testingHubAlertTitle = "Testing Hub tapped"
}
private class Interactor: HomeViewController.Interacting {
var checkInEnabled: Bool
private weak var viewController: UIViewController?
init(
viewController: UIViewController,
checkInEnabled: Bool
) {
self.viewController = viewController
self.checkInEnabled = checkInEnabled
}
func didTapRiskLevelBanner(viewModel: RiskLevelInfoViewController.ViewModel) {
viewController?.showAlert(title: HomeScreenAlerts.postcodeBannerAlertTitle)
}
func didTapLocalInfoBanner(viewModel: LocalInformationViewController.ViewModel) {
viewController?.showAlert(title: HomeScreenAlerts.localInfoBannerAlertTitle)
}
func didTapDiagnosisButton() {
viewController?.showAlert(title: HomeScreenAlerts.diagnosisAlertTitle)
}
func didTapIsolationAdviceButton() {
viewController?.showAlert(title: HomeScreenAlerts.isolationAdviceAlertTitle)
}
func didTapCheckInButton() {
viewController?.showAlert(title: HomeScreenAlerts.checkInAlertTitle)
}
func didTapFinancialSupportButton() {
viewController?.showAlert(title: HomeScreenAlerts.financeAlertTitle)
}
func didTapAboutButton() {
viewController?.showAlert(title: HomeScreenAlerts.aboutAlertTitle)
}
func didTapSettingsButton() {
viewController?.showAlert(title: HomeScreenAlerts.settingsAlertTitle)
}
func didTapLinkTestResultButton() {
viewController?.showAlert(title: HomeScreenAlerts.linkTestResultTitle)
}
func didTapContactTracingHubButton() {
viewController?.showAlert(title: HomeScreenAlerts.contactTracingHubAlertTitle)
}
func didTapTestingHubButton() {
viewController?.showAlert(title: HomeScreenAlerts.testingHubAlertTitle)
}
var shouldShowCheckIn: Bool {
checkInEnabled
}
}
| 37.142857 | 170 | 0.682923 |
38c24a0e4ed9db853d8074705876a928ae8c2acc
| 436 |
import XCTest
@testable import BreadCrumbHeaders
final class BreadCrumbHeadersTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(BreadCrumbHeaders().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 27.25 | 87 | 0.669725 |
015452507647a2460cb4bd3f2b7edeb6650208ad
| 1,374 |
//
// CGColorPropertyType.swift
// ReactantUIGenerator
//
// Created by Matouš Hýbl on 09/03/2018.
//
import Foundation
#if canImport(UIKit)
import UIKit
#endif
public struct CGColorPropertyType: AttributeSupportedPropertyType {
public let color: UIColorPropertyType
public var requiresTheme: Bool {
return color.requiresTheme
}
public func generate(context: SupportedPropertyTypeContext) -> String {
return "\(color.generate(context: context.child(for: color))).cgColor"
}
#if SanAndreas
public func dematerialize(context: SupportedPropertyTypeContext) -> String {
return color.dematerialize(context: context.child(for: color))
}
#endif
#if canImport(UIKit)
public func runtimeValue(context: SupportedPropertyTypeContext) -> Any? {
return (color.runtimeValue(context: context.child(for: color)) as? UIColor)?.cgColor
}
#endif
public init(color: UIColorPropertyType) {
self.color = color
}
public static func materialize(from value: String) throws -> CGColorPropertyType {
let materializedValue = try UIColorPropertyType.materialize(from: value)
return CGColorPropertyType(color: materializedValue)
}
public static var runtimeType: String = "CGColor"
public static var xsdType: XSDType {
return Color.xsdType
}
}
| 26.941176 | 92 | 0.702329 |
488b86294d91391c30559144f53546a82d4a50db
| 12,779 |
//
// TopicCommentModel.swift
// V2ex-Swift
//
// Created by huangfeng on 3/24/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
import Alamofire
import Ji
import YYText
import Kingfisher
protocol V2CommentAttachmentImageTapDelegate : class {
func V2CommentAttachmentImageSingleTap(_ imageView:V2CommentAttachmentImage)
}
/// 评论中的图片
class V2CommentAttachmentImage:AnimatedImageView {
/// 父容器中第几张图片
var index:Int = 0
/// 图片地址
var imageURL:String?
weak var attachmentDelegate : V2CommentAttachmentImageTapDelegate?
init(){
super.init(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
self.autoPlayAnimatedImage = false;
self.contentMode = .scaleAspectFill
self.clipsToBounds = true
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if self.image != nil {
return
}
if let imageURL = self.imageURL , let URL = URL(string: imageURL) {
self.kf.setImage(with: URL, placeholder: nil, options: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in
if let image = image {
if image.size.width < 80 && image.size.height < 80 {
self.contentMode = .bottomLeft
}
}
})
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let tapCount = touch?.tapCount
if let tapCount = tapCount {
if tapCount == 1 {
self.handleSingleTap(touch!)
}
}
//取消后续的事件响应
self.next?.touchesCancelled(touches, with: event)
}
func handleSingleTap(_ touch:UITouch){
self.attachmentDelegate?.V2CommentAttachmentImageSingleTap(self)
}
}
class TopicCommentModel: NSObject,BaseHtmlModelProtocol {
var replyId:String?
var avata: String?
var userName: String?
var date: String?
var comment: String?
var favorites: Int = 0
var textLayout:YYTextLayout?
var images:NSMutableArray = NSMutableArray()
//楼层
var number:Int = 0
var textAttributedString:NSMutableAttributedString?
required init(rootNode: JiNode) {
super.init()
let id = rootNode.xPath("table/tr/td[3]/div[1]/div[attribute::id]").first?["id"]
if let id = id {
if id.hasPrefix("thank_area_") {
self.replyId = id.replacingOccurrences(of: "thank_area_", with: "")
}
}
self.avata = rootNode.xPath("table/tr/td[1]/img").first?["src"]
self.userName = rootNode.xPath("table/tr/td[3]/strong/a").first?.content
self.date = rootNode.xPath("table/tr/td[3]/span").first?.content
if let str = rootNode.xPath("table/tr/td[3]/div[@class='fr']/span").first?.content , let no = Int(str){
self.number = no;
}
if let favorite = rootNode.xPath("table/tr/td[3]/span[2]").first?.content {
let array = favorite.components(separatedBy: " ")
if array.count == 2 {
if let i = Int(array[1]){
self.favorites = i
}
}
}
//构造评论内容
let commentAttributedString:NSMutableAttributedString = NSMutableAttributedString(string: "")
let nodes = rootNode.xPath("table/tr/td[3]/div[@class='reply_content']/node()")
self.preformAttributedString(commentAttributedString, nodes: nodes)
let textContainer = YYTextContainer(size: CGSize(width: SCREEN_WIDTH - 24, height: 9999))
self.textLayout = YYTextLayout(container: textContainer, text: commentAttributedString)
self.textAttributedString = commentAttributedString
}
func preformAttributedString(_ commentAttributedString:NSMutableAttributedString,nodes:[JiNode]) {
for element in nodes {
let urlHandler: (_ attributedString:NSMutableAttributedString, _ url:String, _ url:String)->() = {attributedString,title,url in
let attr = NSMutableAttributedString(string: title ,attributes: [NSAttributedStringKey.font:v2ScaleFont(14)])
attr.yy_setTextHighlight(NSMakeRange(0, title.Lenght),
color: V2EXColor.colors.v2_LinkColor,
backgroundColor: UIColor(white: 0.95, alpha: 1),
userInfo: ["url":url],
tapAction: { (view, text, range, rect) -> Void in
if let highlight = text.yy_attribute(YYTextHighlightAttributeName, at: UInt(range.location)) ,let url = (highlight as AnyObject).userInfo["url"] as? String {
AnalyzeURLHelper.Analyze(url)
}
}, longPressAction: nil)
commentAttributedString.append(attr)
}
if element.name == "text" , let content = element.content{//普通文本
commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSAttributedStringKey.font:v2ScaleFont(14) , NSAttributedStringKey.foregroundColor:V2EXColor.colors.v2_TopicListTitleColor]))
commentAttributedString.yy_lineSpacing = 5
}
else if element.name == "img" ,let imageURL = element["src"] {//图片
let image = V2CommentAttachmentImage()
image.imageURL = imageURL
let imageAttributedString = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit , attachmentSize: CGSize(width: 80,height: 80), alignTo: v2ScaleFont(14), alignment: .bottom)
commentAttributedString.append(imageAttributedString)
image.index = self.images.count
self.images.add(imageURL)
}
else if element.name == "a" ,let content = element.content,let url = element["href"]{//超链接
//递归处理所有子节点,主要是处理下 a标签下包含的img标签
let subNodes = element.xPath("./node()")
if subNodes.first?.name != "text" && subNodes.count > 0 {
self.preformAttributedString(commentAttributedString, nodes: subNodes)
}
if content.Lenght > 0 {
urlHandler(commentAttributedString,content,url)
}
}
else if element.name == "br" {
commentAttributedString.yy_appendString("\n")
}
else if element.children.first?.name == "iframe", let src = element.children.first?["src"] , src.Lenght > 0 {
// youtube 视频
urlHandler(commentAttributedString,src,src)
}
else if let content = element.content{//其他
commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSAttributedStringKey.foregroundColor:V2EXColor.colors.v2_TopicListTitleColor]))
}
}
}
}
//MARK: - Request
extension TopicCommentModel {
class func replyWithTopicId(_ topic:TopicDetailModel, content:String,
completionHandler: @escaping (V2Response) -> Void){
let url = V2EXURL + "t/" + topic.topicId!
V2User.sharedInstance.getOnce(url) { (response) -> Void in
if response.success {
let prames = [
"content":content,
"once":V2User.sharedInstance.once!
] as [String:Any]
Alamofire.request(url, method: .post, parameters: prames, headers: MOBILE_CLIENT_HEADERS).responseJiHtml { (response) -> Void in
if let location = response.response?.allHeaderFields["Etag"] as? String{
if location.Lenght > 0 {
completionHandler(V2Response(success: true))
}
else {
completionHandler(V2Response(success: false, message: "回帖失败"))
}
//不管成功还是失败,更新一下once
if let jiHtml = response .result.value{
V2User.sharedInstance.once = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"]
}
return
}
completionHandler(V2Response(success: false,message: "请求失败"))
}
}
else{
completionHandler(V2Response(success: false,message: "获取once失败,请重试"))
}
}
}
class func replyThankWithReplyId(_ replyId:String , token:String ,completionHandler: @escaping (V2Response) -> Void) {
let url = V2EXURL + "thank/reply/" + replyId + "?t=" + token
Alamofire.request(url, method: .post, headers: MOBILE_CLIENT_HEADERS).responseString { (response: DataResponse<String>) -> Void in
if response.result.isSuccess {
if let result = response.result.value {
if result.Lenght == 0 {
completionHandler(V2Response(success: true))
return;
}
}
}
completionHandler(V2Response(success: false))
}
}
}
//MARK: - Method
extension TopicCommentModel {
/**
用某一条评论,获取和这条评论有关的所有评论
- parameter array: 所有的评论数组
- parameter firstComment: 这条评论
- returns: 某一条评论相关的评论,里面包含它自己
*/
class func getRelevantCommentsInArray(_ allCommentsArray:[TopicCommentModel], firstComment:TopicCommentModel) -> [TopicCommentModel] {
var relevantComments:[TopicCommentModel] = []
var users = getUsersOfComment(firstComment)
//当前会话所有相关的用户( B 回复 A, C 回复 B, D 回复 C, 查看D的对话时, D C B 为相关联用户)
var relateUsers:Set<String> = users
for comment in allCommentsArray {
//被回复人所@的人也加进对话,但是不递归获取所有关系链(可能获取到无意义的数据)
if let username = comment.userName, users.contains(username) {
let commentUsers = getUsersOfComment(comment)
relateUsers = relateUsers.union(commentUsers)
}
//只找到点击的位置,之后就不找了
if comment == firstComment {
break;
}
}
users.insert(firstComment.userName!)
for comment in allCommentsArray {
//判断评论中是否@的所有用户和会话相关联的用户无关,是的话则证明这条评论是和别人讲的,不属于当前对话
let commentUsers = getUsersOfComment(comment)
let intersectUsers = commentUsers.intersection(relateUsers)
if commentUsers.count > 0 && intersectUsers.count <= 0 {
continue;
}
if let username = comment.userName {
if users.contains(username) {
relevantComments.append(comment)
}
}
//只找到点击的位置,之后就不找了
if comment == firstComment {
break;
}
}
return relevantComments
}
//获取评论中 @ 了多少用户
class func getUsersOfComment(_ comment:TopicCommentModel) -> Set<String> {
//获取到所有YYTextHighlight ,用以之后获取 这条评论@了多少用户
var textHighlights:[YYTextHighlight] = []
comment.textAttributedString!.enumerateAttribute(NSAttributedStringKey(rawValue: YYTextHighlightAttributeName), in: NSMakeRange(0, comment.textAttributedString!.length), options: []) { (attribute, range, stop) -> Void in
if let highlight = attribute as? YYTextHighlight {
textHighlights.append(highlight)
}
}
//获取这条评论 @ 了多少用户
var users:Set<String> = []
for highlight in textHighlights {
if let url = highlight.userInfo?["url"] as? String{
let result = AnalyzURLResultType(url: url)
if case .member(let member) = result {
users.insert(member.username)
}
}
}
return users
}
}
| 39.934375 | 232 | 0.557242 |
f7e77484d99f92e5cbddb50f97b5c77d2b2f996d
| 260 |
//
// Bundle+Extensions.swift
// Alamofire
//
// Created by Daniel Clelland on 15/07/20.
//
import Foundation
extension Bundle {
internal func urlForSymbols() -> URL {
return url(forResource: "index", withExtension: "json")!
}
}
| 15.294118 | 64 | 0.623077 |
752d7ceae5eaa49ba734e45c67726a09138d2d80
| 380 |
//
// Gem+CoreDataProperties.swift
//
//
// Created by Jeff Eom on 2018-04-21.
//
//
import Foundation
import CoreData
extension Gem {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Gem> {
return NSFetchRequest<Gem>(entityName: "Gem")
}
@NSManaged public var name: String?
@NSManaged public var gemHighlightList: GemHighlightList?
}
| 16.521739 | 70 | 0.681579 |
4aebf658554e1ea08277e271af5d10e7e8064e4b
| 3,935 |
//
// FulfillmentLineItem.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Represents a single line item in a fulfillment. There is at most one
/// fulfillment line item for each order line item.
open class FulfillmentLineItemQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = FulfillmentLineItem
/// The associated order's line item.
@discardableResult
open func lineItem(alias: String? = nil, _ subfields: (OrderLineItemQuery) -> Void) -> FulfillmentLineItemQuery {
let subquery = OrderLineItemQuery()
subfields(subquery)
addField(field: "lineItem", aliasSuffix: alias, subfields: subquery)
return self
}
/// The amount fulfilled in this fulfillment.
@discardableResult
open func quantity(alias: String? = nil) -> FulfillmentLineItemQuery {
addField(field: "quantity", aliasSuffix: alias)
return self
}
}
/// Represents a single line item in a fulfillment. There is at most one
/// fulfillment line item for each order line item.
open class FulfillmentLineItem: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = FulfillmentLineItemQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "lineItem":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: FulfillmentLineItem.self, field: fieldName, value: fieldValue)
}
return try OrderLineItem(fields: value)
case "quantity":
guard let value = value as? Int else {
throw SchemaViolationError(type: FulfillmentLineItem.self, field: fieldName, value: fieldValue)
}
return Int32(value)
default:
throw SchemaViolationError(type: FulfillmentLineItem.self, field: fieldName, value: fieldValue)
}
}
/// The associated order's line item.
open var lineItem: Storefront.OrderLineItem {
return internalGetLineItem()
}
func internalGetLineItem(alias: String? = nil) -> Storefront.OrderLineItem {
return field(field: "lineItem", aliasSuffix: alias) as! Storefront.OrderLineItem
}
/// The amount fulfilled in this fulfillment.
open var quantity: Int32 {
return internalGetQuantity()
}
func internalGetQuantity(alias: String? = nil) -> Int32 {
return field(field: "quantity", aliasSuffix: alias) as! Int32
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "lineItem":
response.append(internalGetLineItem())
response.append(contentsOf: internalGetLineItem().childResponseObjectMap())
default:
break
}
}
return response
}
}
}
| 35.133929 | 115 | 0.729606 |
33525c8ce6ddce5224703c69a2711ba070b3ac63
| 1,866 |
//
// RetryIO.swift
//
//
// Created by Mikael Konradsson on 2021-04-27.
//
import Foundation
import Funswift
// MARK: - IO<Result>
public func retry<A, B>(
_ f: @escaping (A) -> IO<Result<B, Error>>,
retries: Int,
debounce: Debounce
) -> (A) -> IO<Result<B, Error>> {
retry(f)(debounce)(retries)
}
public func retry<A, B>(
_ f: @escaping (A) -> IO<Result<B, Error>>
) -> (Debounce) -> (Int) -> (A) -> IO<Result<B, Error>> {
func retry(
value: A,
result: IO<Result<B, Error>>,
currentRun: Int,
debounce: Debounce
) -> IO<Result<B, Error>> {
switch result.unsafeRun() {
case .success:
return result
case .failure:
if currentRun > 0 {
Thread.sleep(forTimeInterval: debounce.value)
return retry(value: value, result: f(value), currentRun: currentRun - 1, debounce: debounce.run())
}
return result
}
}
return {
debounce in {
retries in { value in
retry(value: value, result: f(value), currentRun: retries, debounce: debounce)
}
}
}
}
// MARK: - IO<Result>
public func retry<A, B, E>(
_ f: @escaping (A) -> IO<Either<E, B>>,
retries: Int,
debounce: Debounce
) -> (A) -> IO<Either<E, B>> {
retry(f)(debounce)(retries)
}
public func retry<A, B, E>(
_ f: @escaping (A) -> IO<Either<E, B>>
) -> (Debounce) -> (Int) -> (A) -> IO<Either<E, B>> {
func retry(
value: A,
result: IO<Either<E, B>>,
currentRun: Int,
debounce: Debounce
) -> IO<Either<E, B>> {
switch result.unsafeRun() {
case .right:
return result
case .left:
if currentRun > 0 {
Thread.sleep(forTimeInterval: debounce.value)
return retry(value: value, result: f(value), currentRun: currentRun - 1, debounce: debounce)
}
return result
}
}
return {
debounce in {
retries in { value in
retry(value: value, result: f(value), currentRun: retries, debounce: debounce)
}
}
}
}
| 20.733333 | 114 | 0.610397 |
69eac85b565258c91cbd86d69782600e84e59f2d
| 132 |
import XCTest
import ImportSanitizerTests
var tests = [XCTestCaseEntry]()
tests += ImportSanitizerTests.allTests()
XCTMain(tests)
| 16.5 | 40 | 0.80303 |
67b30cb172820f56dfd1b2a3d5621f1effcac4c3
| 1,195 |
//
// AVPlayerItem+PublishersTests.swift
// AVFoundation-CombineTests
//
// Created by József Vesza on 2020. 08. 09..
//
import XCTest
import Combine
import AVFoundation
@testable import AVFoundationCombine
class AVPlayerItem_PublishersTests: XCTestCase {
var subscriptions = Set<AnyCancellable>()
override func tearDown() {
subscriptions = []
}
func testWhenAVPlayerItemDidPlayToEndTimeNotificationIsSent_ItEmitsAnEvent() {
// given
let playerItem = AVPlayerItem(url: URL(string: "https://test.url")!)
let notificationCenter = NotificationCenter()
var notificationReceived = false
playerItem.didPlayToEndTimePublisher(notificationCenter).sink {_ in
notificationReceived = true
}.store(in: &subscriptions)
// when
notificationCenter.post(name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
// then
XCTAssertTrue(notificationReceived)
}
static var allTests = [
("testWhenAVPlayerItemDidPlayToEndTimeNotificationIsSent_ItEmitsAnEvent", testWhenAVPlayerItemDidPlayToEndTimeNotificationIsSent_ItEmitsAnEvent)
]
}
| 28.452381 | 152 | 0.698745 |
118b9e2b3537864cc5dccfb7c03a39d4cef44b49
| 3,259 |
//
// DappPOSCodeHelper.swift
// DappMX
//
// Created by Rodrigo Rivas on 3/31/20.
// Copyright © 2020 Dapp. All rights reserved.
//
import Foundation
internal protocol DappPOSCodeHelperDelegate: AnyObject {
func dappPOSCodeHelper(_ helper: DappPOSCodeHelper, codePayed payment: DappPayment)
func dappPOSCodeHelper(_ helper: DappPOSCodeHelper, didFailWithError error: DappError)
}
internal protocol DappPOSCodeActionsDelegate: AnyObject {
func listenToCode(id: String, delegate: DappPOSCodeHelperDelegate)
func stopListening()
}
internal class DappPOSCodeHelper: DappPOSCodeActionsDelegate {
public var delegate: DappPOSCodeHelperDelegate?
private var id: String!
private var timer: Timer!
private var retries = 0
private var isListening = false
private var wsClient: DappWSClient?
public func listenToCode(id: String, delegate: DappPOSCodeHelperDelegate) {
if isListening {
return
}
isListening = true
self.delegate = delegate
self.id = id
if DappWSClient.isAvailable() {
wsClient = DappApiVendor.dappCodeSocket(id)
wsClient?.delegate = self
wsClient?.connect()
}
else {
setTimer()
}
}
public func stopListening() {
isListening = false
if let t = timer {
t.invalidate()
}
wsClient?.disconnect()
delegate = nil
}
private func setTimer() {
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(httpRequestCodeStatus), userInfo: nil, repeats: false)
}
@objc private func httpRequestCodeStatus() {
DappApiVendor.dappCodePayment(id) { (data, error) in
if let e = error {
switch e {
case .error:
self.retries += 1
if self.retries >= 3 {
self.delegate?.dappPOSCodeHelper(self, didFailWithError: e)
self.stopListening()
}
else {
self.setTimer()
}
default:
self.delegate?.dappPOSCodeHelper(self, didFailWithError: e)
self.stopListening()
}
return
}
if let d = data {
self.delegate?.dappPOSCodeHelper(self, codePayed: DappPayment(with: d))
self.stopListening()
return
}
self.setTimer()
}
}
}
extension DappPOSCodeHelper: DappSocketDelegate {
func didChangeStatus(_ status: DappSocketStatus) {
switch status {
case .connected:
break
case .disconnected:
if isListening {
httpRequestCodeStatus()
}
case .data(let txt):
if let data = txt.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
isListening = false
delegate?.dappPOSCodeHelper(self, codePayed: DappPayment(with: json))
}
}
}
}
| 28.840708 | 142 | 0.55784 |
de96473009f7c964d1cdbc315909f69f5204fc2d
| 3,395 |
//
// CDMarkdownTextView.swift
// CDMarkdownKit
//
// Created by Christopher de Haan on 12/8/16.
//
// Copyright © 2016-2020 Christopher de Haan <[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)
import UIKit
open class CDMarkdownTextView: UITextView {
open var customLayoutManager: CDMarkdownLayoutManager!
open var customTextStorage: NSTextStorage!
open var roundAllCorners: Bool = false {
didSet {
if let layoutManager = self.customLayoutManager {
layoutManager.roundAllCorners = roundAllCorners
}
}
}
open var roundCodeCorners: Bool = false {
didSet {
if let layoutManager = self.customLayoutManager {
layoutManager.roundCodeCorners = roundCodeCorners
}
}
}
open var roundSyntaxCorners: Bool = false {
didSet {
if let layoutManager = self.customLayoutManager {
layoutManager.roundSyntaxCorners = roundSyntaxCorners
}
}
}
open override var attributedText: NSAttributedString! {
get {
return super.attributedText
}
set {
self.customTextStorage = NSTextStorage(attributedString: newValue)
if let layoutManager = self.customLayoutManager {
self.customTextStorage.addLayoutManager(layoutManager)
}
}
}
public init(frame: CGRect,
textContainer: NSTextContainer,
layoutManager: CDMarkdownLayoutManager) {
super.init(frame: frame,
textContainer: textContainer)
self.customLayoutManager = layoutManager
}
public override init(frame: CGRect,
textContainer: NSTextContainer?) {
super.init(frame: frame,
textContainer: textContainer)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configure()
}
open func configure() {
self.customLayoutManager = CDMarkdownLayoutManager()
self.customLayoutManager.addTextContainer(self.textContainer)
self.isScrollEnabled = true
self.isSelectable = false
#if os(iOS)
self.isEditable = false
#endif
}
}
#endif
| 32.961165 | 81 | 0.660972 |
e073f4a73773d2ac367383eff4c708345cb2bcbb
| 7,449 |
//
// SwiftyPhotoClipper.swift
// SwiftyPhotoClipper
//
// Created by lip on 17/4/4.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
//
// UIClipController.swift
// Temple
//
// Created by lip on 17/4/4.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
protocol SwiftyPhotoClipperDelegate {
func didFinishClippingPhoto(image:UIImage)
}
class SwiftyPhotoClipper: UIViewController {
// 代理
var delegate:SwiftyPhotoClipperDelegate?
var imgView:UIImageView?
var img:UIImage?
let scrollview = UIScrollView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
var maxScale:CGFloat = 3.0
var minScale:CGFloat = 1.0
// 屏幕
let HEIGHT = UIScreen.main.bounds.height
let WIDTH = UIScreen.main.bounds.width
// 截图大小
var selectWidth:CGFloat = UIScreen.main.bounds.width
var selectHeight:CGFloat = 200.0
// 框框线的宽度
let lineWidth:CGFloat = 1.0
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
setupUI()
drawTheRect()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 设置图片
func setImageView(image:UIImage){
imgView = UIImageView(image: image)
}
/// 设置裁切区域
func setClipSize(width:CGFloat,height:CGFloat){
self.selectHeight = height
self.selectWidth = width
}
}
// MARK: - UI
extension SwiftyPhotoClipper{
fileprivate func setupUI(){
scrollview.backgroundColor = UIColor.black
imgView = UIImageView(image: img)
guard let imgView = imgView else {
return
}
view.backgroundColor = UIColor.white
imgView.contentMode = .scaleToFill
scrollview.delegate = self
imgView.center = scrollview.center
if imgView.bounds.width > WIDTH {
imgView.frame.size = CGSize(width: WIDTH, height: imgView.bounds.height / imgView.bounds.width * WIDTH)
imgView.center = scrollview.center
}
if imgView.bounds.height > HEIGHT{
imgView.frame.size = CGSize(width: HEIGHT, height: imgView.bounds.width / imgView.bounds.height * HEIGHT)
imgView.center = scrollview.center
}
view.addSubview(scrollview)
scrollview.addSubview(imgView)
let topInsert = (imgView.frame.size.height - selectHeight)/2
let bottomInsert = (HEIGHT - imgView.frame.size.height)/2
scrollview.contentSize = CGSize(width: WIDTH, height: HEIGHT + imgView.frame.height / 2)
scrollview.contentInset = UIEdgeInsets(top: topInsert, left: 0, bottom: -bottomInsert, right: 0)
// 隐藏导航条
scrollview.showsHorizontalScrollIndicator = false
scrollview.showsVerticalScrollIndicator = false
// 设置缩放属性
scrollview.maximumZoomScale = maxScale
scrollview.minimumZoomScale = minScale
// 设置按钮
let cancelBtn = UIButton(frame: CGRect(x: 10, y: HEIGHT - 50, width: 100, height: 40))
cancelBtn.setTitle("取消", for: .normal)
cancelBtn.addTarget(nil, action: #selector(cancelBtnIsClicked), for: .touchUpInside)
view.addSubview(cancelBtn)
let okBtn = UIButton(frame: CGRect(x: WIDTH - 110, y: HEIGHT - 50, width: 100, height: 40))
okBtn.contentMode = .right
okBtn.setTitle("选取", for: .normal)
okBtn.addTarget(nil, action: #selector(okBtnIsClicked), for: .touchUpInside)
view.addSubview(okBtn)
}
fileprivate func clipImage()->UIImage?{
let rect = UIScreen.main.bounds
// 记录屏幕缩放比
let scal = UIScreen.main.scale
// 上下文
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
let context = UIGraphicsGetCurrentContext()
UIApplication.shared.keyWindow?.layer.render(in: context!)
// 截全屏
guard let img = UIGraphicsGetImageFromCurrentImageContext()?.cgImage,
let result = img.cropping(to: CGRect(x: scal * lineWidth, y: (HEIGHT - selectHeight)/2 * scal, width: (self.WIDTH - 2*lineWidth) * scal, height: selectHeight * scal)) else{
return nil
}
// 关闭上下文
UIGraphicsEndImageContext()
return UIImage(cgImage: result, scale: scal, orientation: .up)
}
/// 绘制选择框
fileprivate func drawTheRect(){
// 获取上下文 size表示图片大小 false表示透明 0表示自动适配屏幕大小
UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, 0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor)
context?.fill(UIScreen.main.bounds)
context?.addRect(CGRect(x: 0, y: (HEIGHT - selectHeight)/2, width: WIDTH , height: selectHeight))
context?.setBlendMode(.clear)
context?.fillPath()
// 绘制框框
context?.setBlendMode(.color)
context?.setStrokeColor(UIColor.white.cgColor)
context?.setLineWidth(1.0)
context?.stroke(CGRect(x: 0, y: (HEIGHT - selectHeight)/2 - lineWidth , width: WIDTH , height: selectHeight + 2*lineWidth))
context?.strokePath()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let selectarea = UIImageView(image: img)
selectarea.frame.origin = CGPoint(x: 0, y: 0)
view.addSubview(selectarea)
}
}
// MARK: - 代理方法
extension SwiftyPhotoClipper:UIScrollViewDelegate{
func scrollViewDidZoom(_ scrollView: UIScrollView) {
//当捏或移动时,需要对center重新定义以达到正确显示位置
var centerX = scrollView.center.x
var centerY = scrollView.center.y
centerX = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width / 2 : centerX
centerY = scrollView.contentSize.height > scrollView.frame.size.height ?scrollView.contentSize.height / 2 : centerY
self.imgView?.center = CGPoint(x: centerX, y: centerY)
guard let imgView = imgView else {
return
}
let topInsert = (imgView.frame.size.height - selectHeight)/2
let bottomInsert = (HEIGHT - imgView.frame.size.height)/2
scrollview.contentSize = CGSize(width: imgView.frame.width, height: HEIGHT + imgView.frame.height / 2)
scrollview.contentInset = UIEdgeInsets(top: topInsert, left: 0, bottom: -bottomInsert, right: 0)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imgView
}
}
// MARK: - 监听
extension SwiftyPhotoClipper{
@objc fileprivate func cancelBtnIsClicked(){
dismiss(animated: true, completion: nil)
}
@objc fileprivate func okBtnIsClicked(){
let result = clipImage() ?? UIImage()
delegate?.didFinishClippingPhoto(image: result)
dismiss(animated: true, completion: nil)
}
}
| 29.915663 | 186 | 0.614848 |
61b304f8625dc7eb5129db4b901d978df9e4a95b
| 14,297 |
// Copyright 2020 Penguin 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.
// MARK: - Queue
// TODO: how should queue relate to collection?
// TODO: how should this be refined w.r.t. priority queues?
/// A first-in-first-out data structure.
public protocol Queue {
/// The type of data stored in the queue.
associatedtype Element
/// Removes and returns the next element.
mutating func pop() -> Element?
/// Adds `element` to `self`.
mutating func push(_ element: Element)
}
// MARK: - Deques
/// A dynamically-sized double-ended queue that allows pushing and popping at both the front and the
/// back.
public struct Deque<Element> {
/// A block of data
private typealias Block = DoubleEndedBuffer<Element>
/// The elements contained within the data structure.
///
/// Invariant: buff is never empty (it always contains at least one (nested) Block).
private var buff: DoubleEndedBuffer<Block>
/// The number of elements contained within `self`.
public private(set) var count: Int
/// Creates an empty Deque.
///
/// - Parameter bufferSize: The capacity (in terms of elements) of the initial Deque. If
/// unspecified, `Deque` uses a heuristic to pick a value, tuned for performance.
public init(initialCapacity: Int? = nil) {
let blockSize: Int
if let capacity = initialCapacity {
blockSize = capacity
} else {
if MemoryLayout<Element>.stride < 256 {
// ~4k pages; minus the overheads.
blockSize = (4096 - MemoryLayout<DoubleEndedHeader>.size - 8) / MemoryLayout<Element>.stride
} else {
// Store at least 16 elements per block.
blockSize = 16
}
}
buff = DoubleEndedBuffer<Block>(capacity: 16, with: .middle)
buff.pushBack(Block(capacity: blockSize, with: .middle))
count = 0
}
/// True iff no values are contained in `self.
public var isEmpty: Bool { count == 0 }
private mutating func reallocateBuff() {
if buff.count * 2 < buff.capacity {
// Reallocate to the same size to avoid taking too much memory.
buff.reallocate(newCapacity: buff.capacity, with: .middle)
} else {
buff.reallocate(newCapacity: buff.capacity * 2, with: .middle)
}
}
/// Add `elem` to the back of `self`.
public mutating func pushBack(_ elem: Element) {
count += 1
if buff[buff.endIndex - 1].canPushBack {
buff[buff.endIndex - 1].pushBack(elem)
} else {
if buff[buff.endIndex - 1].isEmpty {
// Re-use the previous buffer.
buff[buff.endIndex - 1].pushFront(elem)
} else {
// Allocate a new buffer.
var newBlock = Block(capacity: buff[buff.endIndex - 1].capacity, with: .beginning)
newBlock.pushBack(elem)
if !buff.canPushBack {
reallocateBuff()
}
buff.pushBack(newBlock)
}
}
}
/// Removes and returns the element at the back, reducing `self`'s count by one.
///
/// - Precondition: !isEmpty
public mutating func popBack() -> Element {
assert(!isEmpty, "Cannot popBack from an empty Deque.")
count -= 1
let tmp = buff[buff.endIndex - 1].popBack()
if buff[buff.endIndex - 1].isEmpty && buff.count > 1 {
_ = buff.popBack()
}
return tmp
}
/// Adds `elem` to the front of `self`.
public mutating func pushFront(_ elem: Element) {
count += 1
if buff[buff.startIndex].canPushFront {
buff[buff.startIndex].pushFront(elem)
} else {
// Allocate a new buffer.
var newBlock = Block(capacity: buff[buff.startIndex].capacity, with: .end)
newBlock.pushFront(elem)
if !buff.canPushFront {
reallocateBuff()
}
buff.pushFront(newBlock)
}
}
/// Removes and returns the element at the front, reducing `self`'s count by one.
///
/// - Precondition: !isEmpty
public mutating func popFront() -> Element {
precondition(!isEmpty)
count -= 1
let tmp = buff[buff.startIndex].popFront()
if buff[buff.startIndex].isEmpty && buff.count > 1 {
_ = buff.popFront()
}
return tmp
}
}
extension Deque: Queue {
public mutating func pop() -> Element? {
if isEmpty {
return nil
}
return popFront()
}
public mutating func push(_ element: Element) {
pushBack(element)
}
}
extension Deque: HierarchicalCollection {
public struct Cursor: Equatable, Comparable {
let outerIndex: Int
let innerIndex: Int
public static func < (lhs: Self, rhs: Self) -> Bool {
if lhs.outerIndex < rhs.outerIndex { return true }
if lhs.outerIndex > rhs.outerIndex { return false }
return lhs.innerIndex < rhs.innerIndex
}
}
/// Call `fn` for each element in the collection until `fn` returns false.
///
/// - Parameter start: Start iterating at elements corresponding to this index. If nil, starts at
/// the beginning of the collection.
/// - Returns: a cursor into the data structure corresponding to the first element that returns
/// false.
@discardableResult
public func forEachWhile(
startingAt start: Cursor?,
_ fn: (Element) throws -> Bool
) rethrows -> Cursor? {
let startPoint =
start
?? Cursor(
outerIndex: buff.startIndex,
innerIndex: buff[buff.startIndex].startIndex)
/// Start with potential partial first buffer.
for i in startPoint.innerIndex..<buff[startPoint.outerIndex].endIndex {
let shouldContinue = try fn(buff[startPoint.outerIndex][i])
if !shouldContinue {
return Cursor(outerIndex: startPoint.outerIndex, innerIndex: i)
}
}
// Nested loops for remainder of data structure.
for outer in (startPoint.outerIndex + 1)..<buff.endIndex {
for inner in buff[outer].startIndex..<buff[outer].endIndex {
let shouldContinue = try fn(buff[outer][inner])
if !shouldContinue {
return Cursor(outerIndex: outer, innerIndex: inner)
}
}
}
return nil
}
}
/// A fixed-size, contiguous collection allowing additions and removals at either end (space
/// permitting).
///
/// Beware: unbalanced pushes/pops to either the front or the back will result in the effective
/// working size to be diminished. If you would like this to be managed for you automatically,
/// please use a `Deque`.
///
/// - SeeAlso: `Deque`
public struct DoubleEndedBuffer<T> {
private var buff: ManagedBuffer<DoubleEndedHeader, T>
/// Allocate with a given capacity and insertion `initialPolicy`.
///
/// - Parameter capacity: The capacity of the buffer.
/// - Parameter initialPolicy: The policy for where initial values should be inserted into the
/// buffer. Note: asymmetric pushes/pops to front/back will cause the portion of the consumed
/// buffer to drift. If you need management to occur automatically, please use a Deque.
public init(capacity: Int, with initialPolicy: DoubleEndedAllocationPolicy) {
assert(capacity > 3)
buff = DoubleEndedBufferImpl<T>.create(minimumCapacity: capacity) { buff in
switch initialPolicy {
case .beginning:
return DoubleEndedHeader(start: 0, end: 0)
case .middle:
let approxMiddle = buff.capacity / 2
return DoubleEndedHeader(start: approxMiddle, end: approxMiddle)
case .end:
return DoubleEndedHeader(start: buff.capacity, end: buff.capacity)
}
}
}
/// True if no elements are contained within the data structure, false otherwise.
public var isEmpty: Bool {
buff.header.start == buff.header.end
}
/// Returns the number of elements contained within `self`.
public var count: Int {
buff.header.end - buff.header.start
}
/// Returns the capacity of `self`.
public var capacity: Int {
buff.capacity
}
/// True iff there is available space at the beginning of the buffer.
public var canPushFront: Bool {
buff.header.start != 0
}
/// True iff there is available space at the end of the buffer.
public var canPushBack: Bool {
buff.header.end < buff.capacity
}
/// Add elem to the back of the buffer.
///
/// - Precondition: `canPushBack`.
public mutating func pushBack(_ elem: T) {
precondition(canPushBack, "Cannot pushBack!")
ensureBuffIsUniquelyReferenced()
buff.withUnsafeMutablePointerToElements { buffP in
let offset = buffP.advanced(by: buff.header.end)
offset.initialize(to: elem)
}
buff.header.end += 1
}
/// Removes and returns the element at the back, reducing `self`'s count by one.
///
/// - Precondition: !isEmpty
public mutating func popBack() -> T {
precondition(!isEmpty, "Cannot popBack from empty buffer!")
ensureBuffIsUniquelyReferenced()
buff.header.end -= 1
return buff.withUnsafeMutablePointerToElements { buffP in
buffP.advanced(by: buff.header.end).move()
}
}
/// Adds elem to the front of the buffer.
///
/// - Precondition: `canPushFront`.
public mutating func pushFront(_ elem: T) {
precondition(canPushFront, "Cannot pushFront!")
ensureBuffIsUniquelyReferenced()
buff.header.start -= 1
buff.withUnsafeMutablePointerToElements { buffP in
let offset = buffP.advanced(by: buff.header.start)
offset.initialize(to: elem)
}
}
/// Removes and returns the element at the front, reducing `self`'s count by one.
public mutating func popFront() -> T {
precondition(!isEmpty, "Cannot popFront from empty buffer!")
ensureBuffIsUniquelyReferenced()
buff.header.start += 1
return buff.withUnsafeMutablePointerToElements { buffP in
buffP.advanced(by: buff.header.start - 1).move()
}
}
/// Makes a copy of the backing buffer if it's not uniquely referenced; does nothing otherwise.
private mutating func ensureBuffIsUniquelyReferenced() {
if !isKnownUniquelyReferenced(&buff) {
// make a copy of the backing store.
let copy = DoubleEndedBufferImpl<T>.create(minimumCapacity: buff.capacity) { copy in
return buff.header
}
copy.withUnsafeMutablePointerToElements { copyP in
buff.withUnsafeMutablePointerToElements { buffP in
let copyOffset = copyP.advanced(by: buff.header.start)
let buffOffset = UnsafePointer(buffP).advanced(by: buff.header.start)
copyOffset.initialize(from: buffOffset, count: buff.header.end - buff.header.start)
}
}
self.buff = copy
}
}
/// Explicitly reallocate the backing buffer.
public mutating func reallocate(
newCapacity: Int,
with initialPolicy: DoubleEndedAllocationPolicy
) {
assert(newCapacity >= count)
let newHeader: DoubleEndedHeader
switch initialPolicy {
case .beginning:
newHeader = DoubleEndedHeader(start: 0, end: count)
case .middle:
let newStart = (newCapacity - count) / 2
newHeader = DoubleEndedHeader(start: newStart, end: newStart + count)
case .end:
newHeader = DoubleEndedHeader(start: newCapacity - count, end: newCapacity)
}
let copy = DoubleEndedBufferImpl<T>.create(minimumCapacity: newCapacity) { copy in
newHeader
}
if !isKnownUniquelyReferenced(&buff) {
// Don't touch existing one; must make a copy of buffer contents.
copy.withUnsafeMutablePointerToElements { copyP in
buff.withUnsafeMutablePointerToElements { buffP in
let copyOffset = copyP.advanced(by: copy.header.start)
let buffOffset = UnsafePointer(buffP).advanced(by: buff.header.start)
copyOffset.initialize(from: buffOffset, count: count)
}
}
} else {
// Move values out of existing buffer into new buffer.
copy.withUnsafeMutablePointerToElements { copyP in
buff.withUnsafeMutablePointerToElements { buffP in
let copyOffset = copyP.advanced(by: copy.header.start)
let buffOffset = buffP.advanced(by: buff.header.start)
copyOffset.moveInitialize(from: buffOffset, count: count)
}
}
buff.header.end = buff.header.start // don't deinitialize uninitialized memory.
}
self.buff = copy
}
}
extension DoubleEndedBuffer: Collection {
public var startIndex: Int { buff.header.start }
public var endIndex: Int { buff.header.end }
public func index(after: Int) -> Int { after + 1 }
public subscript(index: Int) -> T {
get {
assert(index >= buff.header.start)
assert(index < buff.header.end)
return buff.withUnsafeMutablePointerToElements { $0[index] }
}
_modify {
assert(index >= buff.header.start)
assert(index < buff.header.end)
ensureBuffIsUniquelyReferenced()
var tmp = buff.withUnsafeMutablePointerToElements { $0.advanced(by: index).move() }
// Ensure we re-initialize the memory!
defer {
buff.withUnsafeMutablePointerToElements {
$0.advanced(by: index).initialize(to: tmp)
}
}
yield &tmp
}
}
}
/// Describes where the initial insertions into a buffer should go.
///
/// - SeeAlso: `DoubleEndedBuffer`
public enum DoubleEndedAllocationPolicy {
/// Begin allocating elements at the beginning of the buffer.
case beginning
/// Begin allocating in the middle of the buffer.
case middle
/// Begin allocating at the end of the buffer.
case end
}
private struct DoubleEndedHeader {
// TODO: use smaller `Int`s to save memory.
/// The first index with valid data.
var start: Int
/// The index one after the last index with valid data.
var end: Int
}
private class DoubleEndedBufferImpl<T>: ManagedBuffer<DoubleEndedHeader, T> {
deinit {
if header.end != header.start {
withUnsafeMutablePointerToElements { elems in
let base = elems.advanced(by: header.start)
base.deinitialize(count: header.end - header.start)
}
}
}
}
| 33.171694 | 100 | 0.67084 |
deb7a7516d234a98128b6393291a00dee68a3bfb
| 332 |
//
// IRouter.swift
// Services
//
// Created by Alexander Ivlev on 22/09/2019.
// Copyright © 2019 ApostleLife. All rights reserved.
//
import UIKit
public protocol IRouter
{
func start(parameters: RoutingParamaters)
}
public extension IRouter
{
func start() {
start(parameters: RoutingParamaters())
}
}
| 15.090909 | 54 | 0.677711 |
bbb65109ea5b687c42247f43f9183cfe8b966cc2
| 6,900 |
import Basic
import Foundation
import TuistCore
struct WorkspaceStructure {
enum Element: Equatable {
case file(path: AbsolutePath)
case folderReference(path: AbsolutePath)
indirect case group(name: String, path: AbsolutePath, contents: [Element])
case project(path: AbsolutePath)
}
let name: String
let contents: [Element]
}
protocol WorkspaceStructureGenerating {
func generateStructure(path: AbsolutePath, workspace: Workspace) -> WorkspaceStructure
}
final class WorkspaceStructureGenerator: WorkspaceStructureGenerating {
private let fileHandler: FileHandling
init(fileHandler: FileHandling) {
self.fileHandler = fileHandler
}
func generateStructure(path: AbsolutePath, workspace: Workspace) -> WorkspaceStructure {
let graph = DirectoryStructure(path: path,
fileHandler: fileHandler,
projects: workspace.projects,
files: workspace.additionalFiles).buildGraph()
return WorkspaceStructure(name: workspace.name,
contents: graph.nodes.compactMap(directoryGraphToWorkspaceStructureElement))
}
private func directoryGraphToWorkspaceStructureElement(content: DirectoryStructure.Node) -> WorkspaceStructure.Element? {
switch content {
case let .file(file):
return .file(path: file)
case let .project(path):
return .project(path: path)
case let .directory(path, contents):
return .group(name: path.basename,
path: path,
contents: contents.nodes.compactMap(directoryGraphToWorkspaceStructureElement))
case let .folderReference(path):
return .folderReference(path: path)
}
}
}
private class DirectoryStructure {
let path: AbsolutePath
let fileHandler: FileHandling
let projects: [AbsolutePath]
let files: [Workspace.Element]
private let containers: [String] = [
".playground",
".xcodeproj",
]
init(path: AbsolutePath,
fileHandler: FileHandling,
projects: [AbsolutePath],
files: [Workspace.Element]) {
self.path = path
self.fileHandler = fileHandler
self.projects = projects
self.files = files
}
func buildGraph() -> Graph {
return buildGraph(path: path)
}
private func buildGraph(path: AbsolutePath) -> Graph {
let root = Graph()
let filesIncludingContainers = files.filter(isFileOrFolderReference)
let fileNodes = filesIncludingContainers.map(fileNode)
let projectNodes = projects.map(projectNode)
let allNodes = (projectNodes + fileNodes).sorted(by: { $0.path < $1.path })
let commonAncestor = allNodes.reduce(path) { $0.commonAncestor(with: $1.path) }
for node in allNodes {
let relativePath = node.path.relative(to: commonAncestor)
var currentNode = root
var absolutePath = commonAncestor
for component in relativePath.components.dropLast() {
absolutePath = absolutePath.appending(component: component)
currentNode = currentNode.add(.directory(absolutePath))
}
currentNode.add(node)
}
return root
}
private func fileNode(from element: Workspace.Element) -> Node {
switch element {
case let .file(path: path):
return .file(path)
case let .folderReference(path: path):
return .folderReference(path)
}
}
private func projectNode(from path: AbsolutePath) -> Node {
return .project(path)
}
private func isFileOrFolderReference(element: Workspace.Element) -> Bool {
switch element {
case .folderReference:
return true
case let .file(path):
if fileHandler.isFolder(path) {
return path.suffix.map(containers.contains) ?? false
}
return true
}
}
}
extension DirectoryStructure {
class Graph: Equatable, ExpressibleByArrayLiteral, CustomDebugStringConvertible {
var nodes: [Node] = []
private var directoryCache: [AbsolutePath: Graph] = [:]
required init(arrayLiteral elements: DirectoryStructure.Node...) {
nodes = elements
directoryCache = Dictionary(uniqueKeysWithValues: nodes.compactMap {
switch $0 {
case let .directory(path, graph):
return (path, graph)
default:
return nil
}
})
}
@discardableResult
func add(_ node: Node) -> Graph {
switch node {
case .file, .project, .folderReference:
nodes.append(node)
return self
case let .directory(path, _):
if let existingNode = directoryCache[path] {
return existingNode
} else {
let directoryGraph = Graph()
nodes.append(.directory(path, directoryGraph))
directoryCache[path] = directoryGraph
return directoryGraph
}
}
}
var debugDescription: String {
return nodes.debugDescription
}
static func == (lhs: DirectoryStructure.Graph,
rhs: DirectoryStructure.Graph) -> Bool {
return lhs.nodes == rhs.nodes
}
}
}
extension DirectoryStructure {
indirect enum Node: Equatable {
case file(AbsolutePath)
case project(AbsolutePath)
case directory(AbsolutePath, DirectoryStructure.Graph)
case folderReference(AbsolutePath)
static func directory(_ path: AbsolutePath) -> Node {
return .directory(path, Graph())
}
var path: AbsolutePath {
switch self {
case let .file(path):
return path
case let .project(path):
return path
case let .directory(path, _):
return path
case let .folderReference(path):
return path
}
}
}
}
extension DirectoryStructure.Node: CustomDebugStringConvertible {
var debugDescription: String {
switch self {
case let .file(path):
return "file: \(path.asString)"
case let .project(path):
return "project: \(path.asString)"
case let .directory(path, graph):
return "directory: \(path.asString) > \(graph.nodes)"
case let .folderReference(path):
return "folderReference: \(path.asString)"
}
}
}
| 32.093023 | 125 | 0.583188 |
72238118e2e5d546d954c8f52e2eb16a65da6ad7
| 553 |
//
// ViewController.swift
// Demo
//
// Created by Simon Bromberg on 2015-08-08.
// Copyright (c) 2015 Bupkis. All rights reserved.
//
import UIKit
class ViewController: SBAccordionViewController {
override func viewDidLoad() {
super.viewDidLoad()
let subItem = ["SubItem1","SubItem2","SubItem3","SubItem4"]
self.headers = [SBAccordionHeader(header: "Header1",subItems: subItem),SBAccordionHeader(header: "Header2",subItems: subItem),SBAccordionHeader(header: "Header3",subItems: subItem)]
}
}
| 25.136364 | 189 | 0.676311 |
7293a3f6891d6e1456b3b46e9f371012a1e5a1ee
| 3,173 |
//
// UIButton+extension.swift
// firefly20200330
//
// Created by Hold on 2020/5/25.
// Copyright © 2020 mumu. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(text: String, textColorHex: String, font: UIFont) {
self.init(type: .custom)
setTitle(text, for: .normal)
setTitleColor(UIColor(hexString: textColorHex), for: .normal)
titleLabel?.font = font
}
convenience init(text: String, textColor: UIColor, font: UIFont) {
self.init(type: .custom)
setTitle(text, for: .normal)
setTitleColor(textColor, for: .normal)
titleLabel?.font = font
}
convenience init(imageName: String) {
self.init(type: .custom)
setImage(UIImage(named: imageName), for: .normal)
}
}
// MARK: - Image Position
enum ButtonImagePositionType {
case top
case left
case bottom
case right
}
extension UIButton {
func layoutImage(type: ButtonImagePositionType, space: CGFloat) {
/**
* 前置知识点:titleEdgeInsets是title相对于其上下左右的inset,跟tableView的contentInset是类似的,
* 如果只有title,那它上下左右都是相对于button的,image也是一样;
* 如果同时有image和label,那这时候image的上左下是相对于button,右边是相对于label的;title的上右下是相对于button,左边是相对于image的。
*/
// 1. 得到imageView和titleLabel的宽、高
sizeToFit()
clipsToBounds = false
let imageWith = imageView?.frame.size.width ?? 0
let imageHeight = imageView?.frame.size.height ?? 0
var labelWidth: CGFloat = 0
var labelHeight: CGFloat = 0
// 由于iOS8中titleLabel的size为0,用下面的这种设置
labelWidth = titleLabel?.intrinsicContentSize.width ?? 0
labelHeight = titleLabel?.intrinsicContentSize.height ?? 0
// 2. 声明全局的imageEdgeInsets和labelEdgeInsets
var imageEdgeInsets = UIEdgeInsets.zero;
var labelEdgeInsets = UIEdgeInsets.zero;
// 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值
switch (type) {
case .top:
imageEdgeInsets = UIEdgeInsets(top: -labelHeight - space * 0.5, left: 0, bottom: 0, right: -labelWidth)
labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith, bottom: -imageHeight - space * 0.5, right: 0)
case .left:
imageEdgeInsets = UIEdgeInsets(top: 0, left: -space * 0.5, bottom: 0, right: space * 0.5)
labelEdgeInsets = UIEdgeInsets(top: 0, left: space * 0.5, bottom: 0, right: -space * 0.5)
case .bottom:
imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -labelHeight - space * 0.5, right: -labelWidth)
labelEdgeInsets = UIEdgeInsets(top: -imageHeight - space * 0.5, left: -imageWith, bottom: 0, right: 0)
case .right:
imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth + space * 0.5, bottom: 0, right: -labelWidth - space * 0.5)
labelEdgeInsets = UIEdgeInsets(top: 0, left: -imageWith - space * 0.5, bottom: 0, right: imageWith + space * 0.5)
}
self.titleEdgeInsets = labelEdgeInsets
self.imageEdgeInsets = imageEdgeInsets
}
}
| 35.255556 | 127 | 0.624961 |
2f94bae008d639231067de73a8fae33a6a593a0f
| 4,444 |
// Copyright (c) 2020 Bugsnag, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall remain in place
// in this source code.
//
// 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
import WebKit
import Bugsnag
class ViewController: UITableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// we're not showing a new UIView so deselect this row
self.tableView.deselectRow(at: indexPath, animated: true)
// switch through the UITableView sections
switch indexPath.section {
case 0:
// switch through the rows in 'Crashes'
switch indexPath.row {
case 0:
// Uncaught exception
generateUncaughtException();
case 1:
// POSIX Signal
generatePOSIXSignal();
case 2:
// Memory corruption
generateMemoryCorruption();
case 3:
// Stack overflow
generateStackOverflow();
case 4:
// Assertion failure
generateAssertionFailure();
case 5:
// Out of Memory
generateOutOfMemoryError();
case 6:
// Fatal App Hang
fatalAppHang()
default:
break;
}
case 1:
// switch through the rows in 'Handled Errors'
switch indexPath.row {
case 0:
// Send error with notifyError()
sendAnError()
default:
break;
}
default:
break;
}
}
func generateUncaughtException() {
let someJson : Dictionary = ["foo":self]
do {
let data = try JSONSerialization.data(withJSONObject: someJson, options: .prettyPrinted)
print("Received data: %@", data)
} catch {
// Why does this crash the app? A very good question.
}
}
func generatePOSIXSignal() {
raise(SIGTRAP)
}
func generateStackOverflow() {
let items = ["Something!"]
// Use if statement to remove warning about calling self through any path
if (items[0] == "Something!") {
generateStackOverflow()
}
print("items: %@", items)
}
func generateMemoryCorruption() {
let ptr = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
ptr.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)
let badPtr = ptr + 5
_ = badPtr.load(as: UInt32.self)
}
func generateAssertionFailure() {
preconditionFailure("This should NEVER happen")
}
func generateOutOfMemoryError() {
Bugsnag.leaveBreadcrumb(
withMessage: "Loading a lot of JavaScript to generate an OOM"
)
let controller = OutOfMemoryController()
navigationController?.pushViewController(controller, animated: true)
}
func sendAnError() {
do {
try FileManager.default.removeItem(atPath:"//invalid/file")
} catch {
Bugsnag.notifyError(error) { event in
// modify report properties in the (optional) block
event.severity = .info
return true
}
}
}
func fatalAppHang() {
Thread.sleep(forTimeInterval: 3)
_exit(1)
}
}
| 32.918519 | 100 | 0.590459 |
33a44a142a1fa7be7fa4067210bd988e4660671f
| 3,275 |
//
// DDDGeometry.swift
// DDDKit
//
// Created by Guillaume Sabran on 9/28/16.
// Copyright © 2016 Guillaume Sabran. All rights reserved.
//
import Foundation
import GLKit
/**
Represents the 3D shape of an object
*/
public class DDDGeometry {
var vertexArrayObject = GLuint()
private var vertexIndicesBufferID = GLuint()
private var vertexBufferID = GLuint()
private var vertexTexCoordID = GLuint()
private var vertexTexCoordAttributeIndex: GLuint!
/// Positions in the 3d space
public let vertices: [GLKVector3]
/// (optional) positions in a 2d space that describe the mapping between the vertices and their positions in the texture
public let texCoords: [GLKVector2]?
/// The order in which triangles (described by 3 vertices) should be drawn.
public let indices: [UInt16]
var numVertices: Int {
return vertices.count
}
/**
Creates a new geometry
- Parameter vertices: positions in the 3d space
- Parameter texCoords: (optional) positions in a 2d space that describe the mapping between the vertices and their positions in the texture
- Parameter indices: the order in which triangles (described by 3 vertices) should be drawn.
*/
public init(
indices: [UInt16],
vertices: [GLKVector3],
texCoords: [GLKVector2]? = nil
) {
self.indices = indices
self.vertices = vertices
self.texCoords = texCoords
}
private var hasSetUp = false
/// create the vertex buffers
func setUpIfNotAlready(for program: DDDShaderProgram) {
if hasSetUp { return }
//
glGenVertexArrays(1, &vertexArrayObject)
glBindVertexArray(vertexArrayObject)
//Indices
glGenBuffers(1, &vertexIndicesBufferID);
glBindBuffer(GLenum(GL_ELEMENT_ARRAY_BUFFER), vertexIndicesBufferID);
glBufferData(GLenum(GL_ELEMENT_ARRAY_BUFFER), indices.count * MemoryLayout<UInt16>.size, indices, GLenum(GL_STATIC_DRAW));
// Vertex
let flatVert = vertices
.map({ return [$0.x, $0.y, $0.z] })
.flatMap({ return $0 })
.map({ return GLfloat($0) })
glGenBuffers(1, &vertexBufferID);
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBufferID);
glBufferData(GLenum(GL_ARRAY_BUFFER), flatVert.count*MemoryLayout<GLfloat>.size, flatVert, GLenum(GL_STATIC_DRAW));
glEnableVertexAttribArray(GLuint(GLKVertexAttrib.position.rawValue));
glVertexAttribPointer(GLuint(GLKVertexAttrib.position.rawValue), 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<GLfloat>.size*3), nil);
// Texture Coordinates
if let texCoords = texCoords {
let flatCoords = texCoords
.map({ return [$0.y, $0.x] })
.flatMap({ return $0 })
.map({ return GLfloat($0) })
vertexTexCoordAttributeIndex = program.indexFor(attributeNamed: "texCoord")
glGenBuffers(1, &vertexTexCoordID);
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexTexCoordID);
glBufferData(GLenum(GL_ARRAY_BUFFER), flatCoords.count*MemoryLayout<GLfloat>.size, flatCoords, GLenum(GL_DYNAMIC_DRAW));
glEnableVertexAttribArray(vertexTexCoordAttributeIndex);
glVertexAttribPointer(vertexTexCoordAttributeIndex, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<GLfloat>.size*2), nil);
}
hasSetUp = true
}
/// set the geometry to be used as this one
func prepareToUse() {
glBindVertexArray(vertexArrayObject)
}
func reset() {
hasSetUp = false
}
}
| 32.425743 | 153 | 0.746565 |
798d5ddbb1a137ef53d4914ee8bdaaecf58e8353
| 15,574 |
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
/// A result code limited to the least significant 8 bits of the receiver.
/// See https://www.sqlite.org/rescode.html for more information.
///
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
public var primaryResultCode: ResultCode {
return ResultCode(rawValue: rawValue & 0xFF)
}
var isPrimary: Bool {
return self == primaryResultCode
}
/// Returns true if the code on the left matches the code on the right.
///
/// Primary result codes match themselves and their extended result codes,
/// while extended result codes match only themselves:
///
/// switch error.extendedResultCode {
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
/// case .SQLITE_CONSTRAINT: // any other constraint error
/// default: // any other database error
/// }
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
if pattern.isPrimary {
return pattern == code.primaryResultCode
} else {
return pattern == code
}
}
// Primary Result codes
// https://www.sqlite.org/rescode.html#primary_result_code_list
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
public static let SQLITE_PERM = ResultCode(rawValue: 3) // Access permission denied
public static let SQLITE_ABORT = ResultCode(rawValue: 4) // Callback routine requested an abort
public static let SQLITE_BUSY = ResultCode(rawValue: 5) // The database file is locked
public static let SQLITE_LOCKED = ResultCode(rawValue: 6) // A table in the database is locked
public static let SQLITE_NOMEM = ResultCode(rawValue: 7) // A malloc() failed
public static let SQLITE_READONLY = ResultCode(rawValue: 8) // Attempt to write a readonly database
public static let SQLITE_INTERRUPT = ResultCode(rawValue: 9) // Operation terminated by sqlite3_interrupt()
public static let SQLITE_IOERR = ResultCode(rawValue: 10) // Some kind of disk I/O error occurred
public static let SQLITE_CORRUPT = ResultCode(rawValue: 11) // The database disk image is malformed
public static let SQLITE_NOTFOUND = ResultCode(rawValue: 12) // Unknown opcode in sqlite3_file_control()
public static let SQLITE_FULL = ResultCode(rawValue: 13) // Insertion failed because database is full
public static let SQLITE_CANTOPEN = ResultCode(rawValue: 14) // Unable to open the database file
public static let SQLITE_PROTOCOL = ResultCode(rawValue: 15) // Database lock protocol error
public static let SQLITE_EMPTY = ResultCode(rawValue: 16) // Database is empty
public static let SQLITE_SCHEMA = ResultCode(rawValue: 17) // The database schema changed
public static let SQLITE_TOOBIG = ResultCode(rawValue: 18) // String or BLOB exceeds size limit
public static let SQLITE_CONSTRAINT = ResultCode(rawValue: 19) // Abort due to constraint violation
public static let SQLITE_MISMATCH = ResultCode(rawValue: 20) // Data type mismatch
public static let SQLITE_MISUSE = ResultCode(rawValue: 21) // Library used incorrectly
public static let SQLITE_NOLFS = ResultCode(rawValue: 22) // Uses OS features not supported on host
public static let SQLITE_AUTH = ResultCode(rawValue: 23) // Authorization denied
public static let SQLITE_FORMAT = ResultCode(rawValue: 24) // Auxiliary database format error
public static let SQLITE_RANGE = ResultCode(rawValue: 25) // 2nd parameter to sqlite3_bind out of range
public static let SQLITE_NOTADB = ResultCode(rawValue: 26) // File opened that is not a database file
public static let SQLITE_NOTICE = ResultCode(rawValue: 27) // Notifications from sqlite3_log()
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
// Extended Result Code
// https://www.sqlite.org/rescode.html#extended_result_code_list
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
public static let SQLITE_IOERR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (4<<8)))
public static let SQLITE_IOERR_DIR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (5<<8)))
public static let SQLITE_IOERR_TRUNCATE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (6<<8)))
public static let SQLITE_IOERR_FSTAT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (7<<8)))
public static let SQLITE_IOERR_UNLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (8<<8)))
public static let SQLITE_IOERR_RDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (9<<8)))
public static let SQLITE_IOERR_DELETE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (10<<8)))
public static let SQLITE_IOERR_BLOCKED = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (11<<8)))
public static let SQLITE_IOERR_NOMEM = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (12<<8)))
public static let SQLITE_IOERR_ACCESS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (13<<8)))
public static let SQLITE_IOERR_CHECKRESERVEDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (14<<8)))
public static let SQLITE_IOERR_LOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (15<<8)))
public static let SQLITE_IOERR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (16<<8)))
public static let SQLITE_IOERR_DIR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (17<<8)))
public static let SQLITE_IOERR_SHMOPEN = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (18<<8)))
public static let SQLITE_IOERR_SHMSIZE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (19<<8)))
public static let SQLITE_IOERR_SHMLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (20<<8)))
public static let SQLITE_IOERR_SHMMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (21<<8)))
public static let SQLITE_IOERR_SEEK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (22<<8)))
public static let SQLITE_IOERR_DELETE_NOENT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (23<<8)))
public static let SQLITE_IOERR_MMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (24<<8)))
public static let SQLITE_IOERR_GETTEMPPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (25<<8)))
public static let SQLITE_IOERR_CONVPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (26<<8)))
public static let SQLITE_IOERR_VNODE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (27<<8)))
public static let SQLITE_IOERR_AUTH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (28<<8)))
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8)))
public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8)))
public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8)))
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8)))
public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8)))
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8)))
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8)))
public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8)))
public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8)))
public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8)))
public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8)))
public static let SQLITE_READONLY_DBMOVED = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (4<<8)))
public static let SQLITE_ABORT_ROLLBACK = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (2<<8)))
public static let SQLITE_CONSTRAINT_CHECK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (1<<8)))
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (2<<8)))
public static let SQLITE_CONSTRAINT_FOREIGNKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (3<<8)))
public static let SQLITE_CONSTRAINT_FUNCTION = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (4<<8)))
public static let SQLITE_CONSTRAINT_NOTNULL = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (5<<8)))
public static let SQLITE_CONSTRAINT_PRIMARYKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (6<<8)))
public static let SQLITE_CONSTRAINT_TRIGGER = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (7<<8)))
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (8<<8)))
public static let SQLITE_CONSTRAINT_VTAB = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (9<<8)))
public static let SQLITE_CONSTRAINT_ROWID = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (10<<8)))
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (1<<8)))
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (2<<8)))
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
}
// CustomStringConvertible
extension ResultCode {
var errorString: String? {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return String(cString: sqlite3_errstr(rawValue))
#else
if #available(OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
}
#endif
}
/// :nodoc:
public var description: String {
if let errorString = errorString {
return "\(rawValue) (\(errorString))"
} else {
return "\(rawValue)"
}
}
}
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
///
/// do {
/// ...
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
/// // A constraint error
/// }
///
/// This property returns a "primary result code", that is to say the least
/// significant 8 bits of any SQLite result code. See
/// https://www.sqlite.org/rescode.html for more information.
///
/// See also `extendedResultCode`.
public var resultCode: ResultCode {
return extendedResultCode.primaryResultCode
}
/// The SQLite extended error code (see
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
///
/// do {
/// ...
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
/// // A foreign key constraint error
/// }
///
/// See also `resultCode`.
public let extendedResultCode: ResultCode
/// The SQLite error message.
public let message: String?
/// The SQL query that yielded the error (if relevant).
public let sql: String?
/// Creates a Database Error
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.extendedResultCode = resultCode
self.message = message ?? resultCode.errorString
self.sql = sql
self.arguments = arguments
}
/// Creates a Database Error with a raw Int32 result code.
///
/// This initializer is not public because library user is not supposed to
/// be exposed to raw result codes.
init(resultCode: Int32, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
}
// MARK: Not public
/// The query arguments that yielded the error (if relevant).
/// Not public because the StatementArguments class has no public method.
let arguments: StatementArguments?
}
// CustomStringConvertible
extension DatabaseError {
/// :nodoc:
public var description: String {
var description = "SQLite error \(resultCode.rawValue)"
if let sql = sql {
description += " with statement `\(sql)`"
}
if let arguments = arguments, !arguments.isEmpty {
description += " arguments \(arguments)"
}
if let message = message {
description += ": \(message)"
}
return description
}
}
// CustomNSError
extension DatabaseError {
/// NSError bridging: the domain of the error.
/// :nodoc:
public static var errorDomain: String {
return "GRDB.DatabaseError"
}
/// NSError bridging: the error code within the given domain.
/// :nodoc:
public var errorCode: Int {
return Int(extendedResultCode.rawValue)
}
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: description]
}
}
| 57.895911 | 139 | 0.671696 |
0a2798acf507f4b3b55103ea7b6ca043595b865c
| 940 |
import Foundation
final class Token: Codable {
var id: UUID?
var token: String
var userID: User.ID
init(token: String, userID: User.ID) {
self.token = token
self.userID = userID
}
}
import Vapor
import FluentMySQL
extension Token: MySQLUUIDModel {}
extension Token: Content {}
extension Token: Migration {}
extension Token {
var user: Parent<Token, User> {
return parent(\.userID)
}
}
import Crypto
extension Token {
static func generate(for user: User) throws -> Token {
let random = try CryptoRandom().generateData(count: 16)
return try Token(token: random.base64EncodedString(), userID: user.requireID())
}
}
import Authentication
extension Token: Authentication.Token {
static let userIDKey: UserIDKey = \Token.userID
typealias UserType = User
}
extension Token: BearerAuthenticatable {
static let tokenKey: TokenKey = \Token.token
}
| 20.434783 | 87 | 0.681915 |
87aedec95808bd5a35af93827a942c3818adb20b
| 3,076 |
//
// ViewController.swift
// Chapter48
//
// Created by Yunyan Shi on 11/11/19.
// Copyright © 2019 Yunyan Shi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var address: UITextField!
@IBOutlet weak var phone: UITextField!
@IBOutlet weak var status: UILabel!
var databasePath = String()
override func viewDidLoad() {
super.viewDidLoad()
initDB()
}
func initDB() {
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
databasePath = dirPaths[0].appendingPathComponent("contacts.db").path
if !filemgr.fileExists(atPath: databasePath) {
let contactDB = FMDatabase(path: databasePath)
if (contactDB.open()) {
let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"
if !(contactDB.executeStatements(sql_stmt)) {
print("Error: \(contactDB.lastErrorMessage())")
}
contactDB.close()
} else {
print("Error: \(contactDB.lastErrorMessage())")
}
}
}
@IBAction func saveContact(_ sender: Any) {
let contactDB = FMDatabase(path: databasePath)
if (contactDB.open()) {
let insertSQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ('\(name.text ?? "")', '\(address.text ?? "")', '\(phone.text ?? "")')"
do {
try contactDB.executeUpdate(insertSQL, values: nil)
} catch {
status.text = "Failed to add contact"
print("Error: \(error.localizedDescription)")
}
status.text = "Contact Added"
name.text = ""
address.text = ""
phone.text = ""
} else {
print("Error: \(contactDB.lastErrorMessage())")
}
}
@IBAction func findContact(_ sender: Any) {
let contactDB = FMDatabase(path: databasePath)
if (contactDB.open()) {
let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(name.text!)'"
do {
let results: FMResultSet? = try contactDB.executeQuery(querySQL, values: nil)
if results?.next() == true {
address.text = results?.string(forColumn: "address")
phone.text = results?.string(forColumn: "phone")
status.text = "Record Found"
} else {
status.text = "Record not found"
address.text = ""
phone.text = ""
}
} catch {
print("Error: \(error.localizedDescription)")
}
contactDB.close()
} else {
print("Error: \(contactDB.lastErrorMessage())")
}
}
}
| 32.041667 | 151 | 0.528609 |
7674674baf3a61f7d6b227540522f73dc99db79d
| 1,329 |
/*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
// deprecated 9/2021
@available(*, deprecated, message: "use Foundation APIs instead")
public struct URL {
/// Parses the URL type of a git repository
/// e.g. https://github.com/apple/swift returns "https"
/// e.g. [email protected]:apple/swift returns "git"
///
/// This is *not* a generic URI scheme parser!
public static func scheme(_ url: String) -> String? {
func prefixOfSplitBy(_ delimiter: String) -> String? {
let (head, tail) = url.spm_split(around: delimiter)
if tail == nil {
//not found
return nil
} else {
//found, return head
//lowercase the "scheme", as specified by the URI RFC (just in case)
return head.lowercased()
}
}
for delim in ["://", "@"] {
if let found = prefixOfSplitBy(delim), !found.contains("/") {
return found
}
}
return nil
}
}
| 30.906977 | 84 | 0.583898 |
233696713e773d9c8a61095a6c77501131fbea59
| 809 |
import Foundation
protocol InstanaTimerProxiedTarget: AnyObject {
func onTimer(timer: Timer)
}
/// The proxy is used to avoid the retain cycle caused by Timer retaining its target.
class InstanaTimerProxy {
private weak var target: InstanaTimerProxiedTarget?
@objc func onTimer(timer: Timer) {
if let target = target {
target.onTimer(timer: timer)
} else {
timer.invalidate()
}
}
static func timer(proxied: InstanaTimerProxiedTarget, timeInterval: TimeInterval, userInfo: Any? = nil, repeats: Bool = false) -> Timer {
let proxy = InstanaTimerProxy()
proxy.target = proxied
return Timer(timeInterval: timeInterval, target: proxy, selector: #selector(onTimer(timer:)), userInfo: userInfo, repeats: repeats)
}
}
| 32.36 | 141 | 0.678616 |
e6784d969f5bf721f7346d73fb86e020d26cc167
| 1,959 |
// Copyright (c) 2019 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
public extension BuildStep {
/// Flattens a group of swift compilations steps.
///
/// When a Swift module is compiled with `whole module` option
/// The paresed log looks like:
/// - CompileSwiftTarget
/// - CompileSwift
/// - CompileSwift file1.swift
/// - CompileSwift file2.swift
/// This tasks removes the intermediate CompileSwift step and moves the substeps
/// to the root:
/// - CompileSwiftTarget
/// - CompileSwift file1.swift
/// - CompileSwift file2.swift
/// - Returns: The build step with its swift substeps at the root level, and intermediate CompileSwift step removed.
func moveSwiftStepsToRoot() -> BuildStep {
var updatedSubSteps = subSteps
for (index, subStep) in subSteps.enumerated() {
if subStep.detailStepType == .swiftCompilation && subStep.subSteps.count > 0 {
updatedSubSteps.remove(at: index)
updatedSubSteps.append(contentsOf: subStep.subSteps)
}
}
return with(subSteps: updatedSubSteps)
}
}
| 39.18 | 120 | 0.684022 |
d74faa270fc4d09cf6ab9f1fdae0eac89a900a28
| 4,783 |
//
// TxListCell.swift
// bitcorewallet
//
// Created by Ehsan Rezaie on 2018-02-19.
// Copyright © 2018 breadwallet LLC. All rights reserved.
//
import UIKit
class TxListCell: UITableViewCell {
// MARK: - Views
private let timestamp = UILabel(font: .customBody(size: 16.0), color: .darkGray)
private let descriptionLabel = UILabel(font: .customBody(size: 14.0), color: .lightGray)
private let amount = UILabel(font: .customBold(size: 18.0))
private let separator = UIView(color: .separatorGray)
private let statusIndicator = TxStatusIndicator(width: 44.0)
private var pendingConstraints = [NSLayoutConstraint]()
private var completeConstraints = [NSLayoutConstraint]()
// MARK: Vars
private var viewModel: TxListViewModel!
// MARK: - Init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
func setTransaction(_ viewModel: TxListViewModel, isBtcSwapped: Bool, rate: Rate, maxDigits: Int, isSyncing: Bool) {
self.viewModel = viewModel
timestamp.text = viewModel.shortTimestamp
descriptionLabel.text = viewModel.shortDescription
amount.attributedText = viewModel.amount(rate: rate)
statusIndicator.status = viewModel.status
if viewModel.status == .complete {
statusIndicator.isHidden = true
timestamp.isHidden = false
NSLayoutConstraint.deactivate(pendingConstraints)
NSLayoutConstraint.activate(completeConstraints)
} else {
statusIndicator.isHidden = false
timestamp.isHidden = true
NSLayoutConstraint.deactivate(completeConstraints)
NSLayoutConstraint.activate(pendingConstraints)
}
}
// MARK: - Private
private func setupViews() {
addSubviews()
addConstraints()
setupStyle()
}
private func addSubviews() {
contentView.addSubview(timestamp)
contentView.addSubview(descriptionLabel)
contentView.addSubview(statusIndicator)
contentView.addSubview(amount)
contentView.addSubview(separator)
}
private func addConstraints() {
timestamp.constrain([
timestamp.topAnchor.constraint(equalTo: contentView.topAnchor, constant: C.padding[2]),
timestamp.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: C.padding[2])
])
descriptionLabel.constrain([
descriptionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -C.padding[2]),
descriptionLabel.trailingAnchor.constraint(equalTo: timestamp.trailingAnchor)
])
pendingConstraints = [
descriptionLabel.centerYAnchor.constraint(equalTo: statusIndicator.centerYAnchor),
descriptionLabel.leadingAnchor.constraint(equalTo: statusIndicator.trailingAnchor, constant: C.padding[1]),
descriptionLabel.heightAnchor.constraint(equalToConstant: 48.0)
]
completeConstraints = [
descriptionLabel.topAnchor.constraint(equalTo: timestamp.bottomAnchor),
descriptionLabel.leadingAnchor.constraint(equalTo: timestamp.leadingAnchor),
]
statusIndicator.constrain([
statusIndicator.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
statusIndicator.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: C.padding[2]),
statusIndicator.widthAnchor.constraint(equalToConstant: statusIndicator.width),
statusIndicator.heightAnchor.constraint(equalToConstant: statusIndicator.height)
])
amount.constrain([
amount.topAnchor.constraint(equalTo: contentView.topAnchor),
amount.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
amount.leadingAnchor.constraint(equalTo: descriptionLabel.trailingAnchor, constant: C.padding[6]),
amount.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -C.padding[2]),
])
separator.constrainBottomCorners(height: 0.5)
}
private func setupStyle() {
selectionStyle = .none
amount.textAlignment = .right
amount.setContentHuggingPriority(.required, for: .horizontal)
timestamp.setContentHuggingPriority(.required, for: .vertical)
descriptionLabel.lineBreakMode = .byTruncatingTail
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 38.886179 | 120 | 0.671545 |
ab757b600c1befe920c249fda335755081bcb7cb
| 1,419 |
//
// KarmaBoardParser.swift
// App
//
// Created by Allan Vialatte on 28/09/2018.
//
import Foundation
struct KarmaBoardParser {
let text: String
let teamId: String
let authedBot: String
var textToken: [String] = []
init(with event:SlackEvent) {
self.text = event.event.text
self.teamId = event.teamId
self.textToken = event.event.text.split(separator: " ").map { String($0) }
self.authedBot = event.authedUsers.first ?? ""
}
func parse() -> [Action] {
guard self.textToken.count > 1, self.textToken.count < 4 else { return [] }
guard self.textToken[0] == "<@\(self.authedBot)>" else { return [] }
let actionVerb = self.textToken[1]
var actionLength = 5
if self.textToken.count > 2{ actionLength = (Int(self.textToken[2]) ?? 5)}
if actionVerb.lowercased() == "leaderboard" { return [Action(teamId: self.teamId, type: .leaderboard, length: actionLength)] }
if actionVerb.lowercased() == "lastboard" { return [Action(teamId: self.teamId, type: .lastboard, length: actionLength)] }
return []
}
}
extension KarmaBoardParser {
struct Action {
let teamId: String
let type: ActionType
let length: Int
}
}
enum ActionType {
case leaderboard
case lastboard
var title: String {
switch self {
case .leaderboard: return "Top :sports_medal: :"
case .lastboard: return "Last :thumbsdown: :"
}
}
}
| 25.339286 | 130 | 0.647639 |
1d377a759bc1bc5464720f2498b293bdb407e4aa
| 269 |
//
// PValidatorDelegate.swift
// ParakhValidator
//
// Created by J3Patel on 08/08/18.
//
import UIKit
public protocol PValidatorDelegate: class {
func failed(with element: PValidationElement, condition: PValidationCondition)
func validationSucceded()
}
| 17.933333 | 82 | 0.743494 |
abe9639511c99ee3a2588a671823b9e576b8f1b7
| 2,536 |
//
// Movie.swift
// flicks
//
// Created by dawei_wang on 9/16/17.
// Copyright © 2017 dawei_wang. All rights reserved.
//
import UIKit
import SwiftyJSON
class Movie: NSObject {
let POSTER_BASE_URL = "https://image.tmdb.org/t/p/w342"
let HIGH_RESOLUTION_POSTER_BASE_URL = "https://image.tmdb.org/t/p/original"
let LOW_RESOLUTION_POSTER_BASE_URL = "https://image.tmdb.org/t/p/w45"
fileprivate(set) var title : String
fileprivate(set) var overview : String
fileprivate(set) var posterPath : String?
fileprivate(set) var voteAverage : Float
fileprivate(set) var isAdult : Bool
fileprivate(set) var releaseDateString : String
var posterUrl : URL? {
get {
return posterPath.map({ (path: String) -> URL in
URL(string: POSTER_BASE_URL + path)!
})
}
}
var lowResolutionPosterUrl : URL? {
get {
return posterPath.map({ (path: String) -> URL in
URL(string: LOW_RESOLUTION_POSTER_BASE_URL + path)!
})
}
}
var hiResolutionPosterUrl : URL? {
get {
return posterPath.map({ (path: String) -> URL in
URL(string: HIGH_RESOLUTION_POSTER_BASE_URL + path)!
})
}
}
var voteString : String {
get {
return "\(voteAverage)"
}
}
init(overview: String, title: String, posterPath: String?, voteAverage: Float, releaseDateString: String, isAdult: Bool) {
self.overview = overview
self.title = title
self.posterPath = posterPath
self.voteAverage = voteAverage
self.releaseDateString = releaseDateString
self.isAdult = isAdult
}
class func getMovies(_ json: JSON) -> [Movie] {
var movies = [Movie]()
if let movieArray = json["results"].array {
for movie in movieArray {
let title = movie["title"].string!
let overview = movie["overview"].string!
let posterPath = movie["poster_path"].string
let voteAverage = movie["vote_average"].float!
let releaseDateString = movie["release_date"].string!
let isAdult = movie["adult"].bool!
movies.append(Movie(overview: overview, title: title, posterPath: posterPath, voteAverage: voteAverage, releaseDateString: releaseDateString, isAdult: isAdult));
}
}
return movies
}
}
| 31.7 | 177 | 0.583991 |
263c57fda90759fd515afc884b10d49a1932acd4
| 4,819 |
//
// SocialMediaViewController.swift
// StanwoodSocial
//
// Copyright (c) 2018 stanwood GmbH
// Distributed under MIT licence.
//
// The MIT License (MIT)
//
// Copyright (c) 2018 Stanwood GmbH (www.stanwood.io)
//
// 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
import StanwoodSocial
class SocialMediaViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
fileprivate var dataSource:SocialMediaDataSource!
fileprivate var delegate:SocialMediaDelegate!
fileprivate var items:SMPosts?
fileprivate var activityIndictor:UIActivityIndicatorView!
var socialUrl:URL!
override func viewDidLoad() {
super.viewDidLoad()
/// Setting OAuth handler
STSocialManager.shared.set(target: self)
STSocialManager.shared.delegate = self
collectionView.allowsSelection = false
loadData(withUrl: socialUrl.absoluteString)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(SocialMediaViewController.logout))
}
func logout(){
STSocialManager.shared.logout()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
STSocialManager.shared.cancelAllOperations()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
activityIndictor = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndictor.hidesWhenStopped = true
activityIndictor.tintColor = UIColor.black
activityIndictor.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height * 0.95)
view.addSubview(activityIndictor)
}
fileprivate func loadData(withUrl url: String) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
NetworkManager.sharedManager.getPosts(withUrl: url) {
[unowned self] (posts, response) in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if posts != nil {
if self.items == nil {
self.items = SMPosts(items: posts!)
} else {
self.items = self.items!.appendItems(posts!)
}
DispatchQueue.main.async(execute: {
self.configureDataSource()
})
} else {
print(response ?? "")
}
}
}
fileprivate func configureDataSource(){
let nib = UINib(nibName: "SMPostCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: "SMPostCell")
self.dataSource = SocialMediaDataSource(dataObject: self.items, currentViewController: self)
self.delegate = SocialMediaDelegate(currentViewController: self, dataObject: self.items)
self.collectionView.dataSource = self.dataSource
self.collectionView.delegate = self.delegate
}
}
extension SocialMediaViewController: SMPostCellDelegate {
func auth(type: PostType) {
guard let serviceType = STSocialType(rawValue: type.rawValue) else { return }
STSocialManager.shared.auth(forType: serviceType)
}
}
extension SocialMediaViewController: STSocialManagerDelegate {
func didLogout(type: STSocialType?) {
collectionView.reloadData()
}
func didLogin(type: STSocialType, withError error: Error?) {
collectionView.reloadData()
}
}
| 35.175182 | 158 | 0.667981 |
fc23bdba7283ed93779a2cdcc7c7d316e7f958ee
| 2,541 |
//
// MovieClient.swift
// MVVMwithRXSwiftDemo
//
// Created by Keith Gapusan on 17/07/2018.
// Copyright © 2018 Keith Gapusan. All rights reserved.
//
import UIKit
class MoviesClient: NSObject {
// func fetchMoviesV2(completion:@escaping ([Dictionary<AnyHashable,Any>]?) -> ()){
// let urlString = "https://itunes.apple.com/us/rss/topmovies/limit=25/json"
// let url = URL(string: urlString)
// let session = URLSession(configuration: URLSessionConfiguration.default)
// let task = session.dataTask(with: url!, completionHandler: {
// (data, response, error) in
// if error != nil{
// completion(nil)
// return
// }
// // var error : NSError
// if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [Dictionary<AnyHashable,Any>] {
//
// if let movies = json![keyPath(path: "feed.entry")]{
// //value(forKey: "feed.entry"){
// completion(movies as? [Dictionary<AnyHashable,Any>])
// print(movies)
// return
//
// }
// }
// })
//
// task.resume()
//
// }
func fetchMovies(completion: @escaping ([NSDictionary]?) -> ()){
// fetch the data
// call the completion
let urlString = "https://itunes.apple.com/us/rss/topmovies/limit=25/json"
let url = URL(string: urlString)
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: url!, completionHandler: {
(data, response, error) in
if error != nil{
completion(nil)
return
}
// var error : NSError
if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
if let movies = json?.value(forKeyPath: "feed.entry"){
//value(forKey: "feed.entry"){
completion(movies as? [NSDictionary])
print(movies)
return
}
}
})
task.resume()
}
func keyPath<T>(path: String) -> (_ box: [String: AnyObject]) -> T? {
return { box in
return (box as NSDictionary).value(forKeyPath: path) as? T
}
}
}
| 34.337838 | 123 | 0.498623 |
140963d229477530a4bd03cf266baba94ff9212c
| 486 |
//
// SBDefaultUserService.swift
// BaseMVVM
//
// Created by ALEXEY ABDULIN on 02.02.2021.
// Copyright © 2021 ALEXEY ABDULIN. All rights reserved.
//
import Foundation
import RxRelay
class SBDefaultUserService: SBAuthUserServiceProtocol
{
var isLogin = false
{
didSet
{
rxIsLogin.accept( isLogin )
}
}
var rxIsLogin = BehaviorRelay<Bool>( value: false )
init( login: Bool )
{
isLogin = login
}
}
| 16.758621 | 57 | 0.604938 |
dd45a99854cdb451d84bcec9152bfe56a2bf1192
| 1,983 |
//
// FileHelper.swift
// SlimTools
//
// Created by Peter Jin on 2018/8/9.
// Copyright © 2018 Jxb. All rights reserved.
//
import Cocoa
class FileHelper {
static let shared = FileHelper()
private let filterDirNames = ["carthage","pods","qiyu","filter_file"]
private init() {
}
func fetchAllPNGs(with path: String, list: inout [String], count: inout Int) {
let fileManager = FileManager.default
var isDir: ObjCBool = false
guard fileManager.fileExists(atPath: path, isDirectory: &isDir), isDir.boolValue else {
return
}
if let dirArray = try? fileManager.contentsOfDirectory(atPath: path) {
dirArray.forEach { (name) in
guard !filterDirNames.contains(name.lowercased()) else {
return
}
let subpath = "\(path)/\(name)"
var issubDir: ObjCBool = false
if fileManager.fileExists(atPath: subpath, isDirectory: &issubDir), issubDir.boolValue {
fetchAllPNGs(with: subpath, list: &list, count: &count)
} else {
count += 1
let log = "已扫描\(count)个文件\r"
print("\(log) \r", terminator: "")
let ext = URL(fileURLWithPath: path).appendingPathComponent(name).pathExtension.lowercased()
if ext == "png" || ext == "jpg" {
list.append(subpath)
}
}
}
}
// var subPath: String? = nil
// for str: String? in dirArray ?? [String?]() {
// subPath = URL(fileURLWithPath: path ?? "").appendingPathComponent(str).absoluteString
// var issubDir: ObjCBool = false
// fileManager.fileExists(atPath: subPath ?? "", isDirectory: &issubDir)
// showAllFile(withPath: subPath)
// }
}
}
| 34.189655 | 112 | 0.523449 |
e9c02d913faad37b7b0b577b501333a99956a1b2
| 957 |
//
// UserNameNotExists.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
open class UserNameNotExists: Codable {
public var userName: String
public var exists: Bool
public init(userName: String, exists: Bool) {
self.userName = userName
self.exists = exists
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: String.self)
try container.encode(userName, forKey: "userName")
try container.encode(exists, forKey: "exists")
}
// Decodable protocol methods
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: String.self)
userName = try container.decode(String.self, forKey: "userName")
exists = try container.decode(Bool.self, forKey: "exists")
}
}
| 21.266667 | 72 | 0.665622 |
3849d909d0fdc8416f7eac2bf69080e4f28b7f6f
| 1,796 |
//
// StartScreenViewModel.swift
// Application
//
// Created by Dino Catalinac on 13/04/2020.
// Copyright © 2020 github.com/dinocata. All rights reserved.
//
import RxCocoa
import Domain
// sourcery: injectable
class StartScreenViewModel {
private let isUserLoggedInUseCase: IsUserLoggedInUseCase
private let loginUserUseCase: LoginUserUseCase
private let logoutUserUseCase: LogoutUserUseCase
init(
isUserLoggedInUseCase: IsUserLoggedInUseCase,
loginUserUseCase: LoginUserUseCase,
logoutUserUseCase: LogoutUserUseCase) {
self.isUserLoggedInUseCase = isUserLoggedInUseCase
self.loginUserUseCase = loginUserUseCase
self.logoutUserUseCase = logoutUserUseCase
}
}
// Binding
extension StartScreenViewModel: ViewModelType {
struct Input {
let dashboardButtonPressed: Driver<Void>
let loginButtonPressed: Driver<Void>
let logoutButtonPressed: Driver<Void>
}
struct Output {
let isLoggedIn: Driver<Bool>
let logout: Driver<Void>
let transition: Driver<Scene>
}
func transform(input: Input) -> Output {
let isLoggedIn = isUserLoggedInUseCase.execute()
.asDriver(onErrorJustReturn: false)
let transition: Driver<Scene> = .merge(
input.loginButtonPressed.map { .login },
input.dashboardButtonPressed.map { .postList }
)
let logout = input.logoutButtonPressed
.asObservable()
.flatMapLatest(logoutUserUseCase.execute)
.mapToVoid()
.asDriver(onErrorJustReturn: ())
return Output(
isLoggedIn: isLoggedIn,
logout: logout,
transition: transition
)
}
}
| 28.0625 | 62 | 0.649777 |
39e9eb60db96467fa892a7e0c345ba1bb7850c21
| 47,604 |
//===------------------ RawSyntax.swift - Raw Syntax nodes ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Represents the tail-allocated elements of `RawSyntax`'s `ManagedBuffer`.
typealias RawSyntaxDataElement = UInt64
fileprivate typealias DataElementPtr = UnsafePointer<RawSyntaxDataElement>
fileprivate typealias MutableDataElementPtr = UnsafeMutablePointer<RawSyntaxDataElement>
/// Convenience function to write a value into a `RawSyntaxDataElement`.
fileprivate func initializeElement<T>(_ ptr: MutableDataElementPtr, with value: T) {
castElementAs(ptr).initialize(to: value)
}
/// Convenience function to read a value from a `RawSyntaxDataElement`.
fileprivate func readElement<T>(_ ptr: DataElementPtr) -> T {
return castElementAs(ptr).pointee
}
fileprivate func castElementAs<T>(_ ptr: DataElementPtr) -> UnsafePointer<T> {
assert(MemoryLayout<T>.alignment <= MemoryLayout<RawSyntaxDataElement>.alignment)
return UnsafePointer<T>(OpaquePointer(ptr))
}
fileprivate func castElementAs<T>(_ ptr: MutableDataElementPtr) -> UnsafeMutablePointer<T> {
assert(MemoryLayout<T>.alignment <= MemoryLayout<RawSyntaxDataElement>.alignment)
return UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: T.self)
}
/// Calculates the number of `RawSyntaxDataElement`s needed to fit the given
/// number of bytes.
fileprivate func numberOfElements(forBytes size: Int) -> Int {
let (words, remainder) = size.quotientAndRemainder(
dividingBy: MemoryLayout<RawSyntaxDataElement>.stride)
let numOfElems = remainder == 0 ? words : words+1
return numOfElems
}
/// Calculates the number of `RawSyntaxDataElement`s needed to fit the given
/// value.
fileprivate func numberOfElements<T>(for value: T) -> Int {
return numberOfElements(forBytes: MemoryLayout<T>.size)
}
/// Convenience property to refer to an empty string buffer.
fileprivate var emptyStringBuffer: UnsafeBufferPointer<UInt8> {
return .init(start: nil, count: 0)
}
/// Low-level data specific to token nodes.
///
/// There's additional data that are tail-allocated. The data are as follows:
///
/// * For a parsed token (`TokenData.isConstructed` is false):
/// * List of leading `CTriviaPiece`s
/// * List of trailing `CTriviaPiece`s
/// * A string buffer. If `TokenData.hasCustomText` is false then the buffer is empty
/// otherwise it contains the full text for the token, including the trivia.
/// `TokenData.hasCustomText` is true if there's any custom text in any of the trivia
/// or the token kind.
/// * For a constructed token (`TokenData.isConstructed` is true):
/// * A `ConstructedTokenData` value
///
/// Testing showed that, during parsing, copying the full token length, when
/// there is any custom text, is more efficient than trying to copy only the
/// individual strings from trivia or token kind containing custom text.
fileprivate struct TokenData {
let leadingTriviaCount: UInt16
let trailingTriviaCount: UInt16
let tokenKind: CTokenKind
/// Returns true if there's any custom text in any of the trivia or the token kind.
///
/// If true then there is a string buffer in the tail-allocated storage for
/// the full token range (including trivia).
/// It is ignored for a constructed token node (`isConstructed` == true).
let hasCustomText: Bool
private let isConstructed: Bool
private init(
kind: CTokenKind,
leadingTriviaCount: UInt16,
trailingTriviaCount: UInt16,
hasCustomText: Bool,
isConstructed: Bool
) {
self.tokenKind = kind
self.leadingTriviaCount = leadingTriviaCount
self.trailingTriviaCount = trailingTriviaCount
self.hasCustomText = hasCustomText
self.isConstructed = isConstructed
}
/// Returns header `RawSyntaxData` value and number of elements to tail-allocate.
static func dataAndExtraCapacity(
for cnode: CSyntaxNode
) -> (RawSyntaxData, Int) {
assert(cnode.kind == 0)
let data = cnode.token_data
let leadingTriviaCount = Int(data.leading_trivia_count)
let trailingTriviaCount = Int(data.trailing_trivia_count)
let totalTrivia = leadingTriviaCount + trailingTriviaCount
let hasTriviaText = { (count: Int, p: CTriviaPiecePtr?) -> Bool in
for i in 0..<count {
if TriviaPiece.hasText(kind: p![i].kind) { return true }
}
return false
}
let hasCustomText = TokenKind.hasText(kind: data.kind) ||
hasTriviaText(leadingTriviaCount, data.leading_trivia) ||
hasTriviaText(trailingTriviaCount, data.trailing_trivia)
let textSize = hasCustomText ? Int(cnode.range.length) : 0
let rawData: RawSyntaxData = .token(.init(kind: data.kind,
leadingTriviaCount: data.leading_trivia_count,
trailingTriviaCount: data.trailing_trivia_count,
hasCustomText: hasCustomText, isConstructed: false))
let capacity = totalTrivia + numberOfElements(forBytes: textSize)
return (rawData, capacity)
}
/// Initializes the tail-allocated elements.
static func initializeExtra(
_ cnode: CSyntaxNode,
source: String,
hasCustomText: Bool,
extraPtr: MutableDataElementPtr
) {
let data = cnode.token_data
let leadingTriviaCount = Int(data.leading_trivia_count)
let trailingTriviaCount = Int(data.trailing_trivia_count)
var curPtr = extraPtr
for i in 0..<leadingTriviaCount {
assert(MemoryLayout.size(ofValue: data.leading_trivia![i])
<= MemoryLayout<RawSyntaxDataElement>.size)
initializeElement(curPtr, with: data.leading_trivia![i])
curPtr = curPtr.successor()
}
for i in 0..<trailingTriviaCount {
assert(MemoryLayout.size(ofValue: data.trailing_trivia![i])
<= MemoryLayout<RawSyntaxDataElement>.size)
initializeElement(curPtr, with: data.trailing_trivia![i])
curPtr = curPtr.successor()
}
if hasCustomText {
// Copy the full token text, including trivia.
let startOffset = Int(cnode.range.offset)
var charPtr = UnsafeMutableRawPointer(curPtr).assumingMemoryBound(to: UInt8.self)
let utf8 = source.utf8
let begin = utf8.index(utf8.startIndex, offsetBy: startOffset)
let end = utf8.index(begin, offsetBy: Int(cnode.range.length))
for ch in utf8[begin..<end] {
charPtr.pointee = ch
charPtr = charPtr.successor()
}
}
}
/// Returns header `RawSyntaxData` value and number of elements to tail-allocate.
static func dataAndExtraCapacity(
for data: ConstructedTokenData
) -> (RawSyntaxData, Int) {
let rawData: RawSyntaxData = .token(.init(kind: /*irrelevant*/0,
leadingTriviaCount: UInt16(truncatingIfNeeded: data.leadingTrivia.count),
trailingTriviaCount: UInt16(truncatingIfNeeded: data.trailingTrivia.count),
hasCustomText: /*irrelevant*/false, isConstructed: true))
let capacity = numberOfElements(for: data)
return (rawData, capacity)
}
/// Initializes the tail-allocated elements.
static func initializeExtra(
_ data: ConstructedTokenData,
extraPtr: MutableDataElementPtr
) {
initializeElement(extraPtr, with: data)
}
/// De-initializes memory from tail-allocated data.
fileprivate func deinitialize(extraPtr: MutableDataElementPtr) {
if isConstructed {
let ptr: UnsafeMutablePointer<ConstructedTokenData> = castElementAs(extraPtr)
ptr.deinitialize(count: 1)
}
}
private var isParsed: Bool { return !isConstructed }
private func parsedData(
length: UInt32, extraPtr: DataElementPtr
) -> UnsafeParsedTokenData {
assert(isParsed)
let leadingTriviaCount = Int(self.leadingTriviaCount)
let trailingTriviaCount = Int(self.trailingTriviaCount)
var curPtr = extraPtr
let leadingTriviaBuffer: UnsafeBufferPointer<CTriviaPiece> =
.init(start: castElementAs(curPtr), count: leadingTriviaCount)
curPtr = curPtr.advanced(by: leadingTriviaCount)
let trailingTriviaBuffer: UnsafeBufferPointer<CTriviaPiece> =
.init(start: castElementAs(curPtr), count: trailingTriviaCount)
curPtr = curPtr.advanced(by: trailingTriviaCount)
let textSize = hasCustomText ? Int(length) : 0
let textBuffer: UnsafeBufferPointer<UInt8> =
.init(start: castElementAs(curPtr), count: textSize)
return .init(length: length, tokenKind: tokenKind,
leadingTriviaBuffer: leadingTriviaBuffer,
trailingTriviaBuffer: trailingTriviaBuffer,
fullTextBuffer: textBuffer, hasCustomText: hasCustomText)
}
fileprivate func formTokenKind(
length: UInt32, extraPtr: DataElementPtr
) -> TokenKind {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return data.formTokenKind()
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
return tok.kind
}
}
/// Returns the leading `Trivia` length for a token node.
/// - Returns: .zero if called on a layout node.
fileprivate func getLeadingTriviaLength(
length: UInt32, extraPtr: DataElementPtr
) -> SourceLength {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return SourceLength(utf8Length: data.getLeadingTriviaLength())
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
return tok.leadingTrivia.sourceLength
}
}
/// Returns the trailing `Trivia` length for a token node.
/// - Returns: .zero if called on a layout node.
fileprivate func getTrailingTriviaLength(
length: UInt32, extraPtr: DataElementPtr
) -> SourceLength {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return SourceLength(utf8Length: data.getTrailingTriviaLength())
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
return tok.trailingTrivia.sourceLength
}
}
/// Returns the leading `Trivia` for a token node.
/// - Returns: nil if called on a layout node.
fileprivate func formLeadingTrivia(
length: UInt32, extraPtr: DataElementPtr
) -> Trivia {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return data.formLeadingTrivia()
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
return tok.leadingTrivia
}
}
/// Returns the trailing `Trivia` for a token node.
/// - Returns: nil if called on a layout node.
fileprivate func formTrailingTrivia(
length: UInt32, extraPtr: DataElementPtr
) -> Trivia {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return data.formTrailingTrivia()
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
return tok.trailingTrivia
}
}
fileprivate func withUnsafeTokenText<Result>(
relativeOffset: Int,
length: UInt32,
extraPtr: DataElementPtr,
_ body: (UnsafeTokenText) -> Result
) -> Result {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return body(data.getTokenText(relativeOffset: relativeOffset))
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
return tok.kind.withUnsafeTokenText(body)
}
}
fileprivate func withUnsafeLeadingTriviaPiece<Result>(
at index: Int,
relativeOffset: Int,
length: UInt32,
extraPtr: DataElementPtr,
_ body: (UnsafeTriviaPiece?) -> Result
) -> Result {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return body(data.getLeadingTriviaPiece(at: index, relativeOffset: relativeOffset))
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
guard index < tok.leadingTrivia.count else { return body(nil) }
return tok.leadingTrivia[index].withUnsafeTriviaPiece(body)
}
}
fileprivate func withUnsafeTrailingTriviaPiece<Result>(
at index: Int,
relativeOffset: Int,
length: UInt32,
extraPtr: DataElementPtr,
_ body: (UnsafeTriviaPiece?) -> Result
) -> Result {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return body(data.getTrailingTriviaPiece(at: index, relativeOffset: relativeOffset))
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
guard index < tok.trailingTrivia.count else { return body(nil) }
return tok.trailingTrivia[index].withUnsafeTriviaPiece(body)
}
}
/// Prints the RawSyntax token.
fileprivate func write<Target>(
to target: inout Target, length: UInt32, extraPtr: DataElementPtr
) where Target: TextOutputStream {
if isParsed {
let data = parsedData(length: length, extraPtr: extraPtr)
return data.write(to: &target)
} else {
let tok: ConstructedTokenData = castElementAs(extraPtr).pointee
tok.write(to: &target)
}
}
}
/// Convenience wrapper over the tail-allocated data for a token node.
/// This is used only for tokens created during parsing.
fileprivate struct UnsafeParsedTokenData {
let length: UInt32
let tokenKind: CTokenKind
let leadingTriviaBuffer: UnsafeBufferPointer<CTriviaPiece>
let trailingTriviaBuffer: UnsafeBufferPointer<CTriviaPiece>
let fullTextBuffer: UnsafeBufferPointer<UInt8>
let hasCustomText: Bool
func formTokenKind() -> TokenKind {
if fullTextBuffer.isEmpty {
// Fast path, there's no text in the buffer so no need to determine the
// token length.
return TokenKind.fromRawValue(kind: tokenKind, textBuffer: emptyStringBuffer)
}
let leadingTriviaLength = self.getLeadingTriviaLength()
let trailingTriviaLength = self.getTrailingTriviaLength()
let tokenLength = Int(length) - (leadingTriviaLength + trailingTriviaLength)
let tokenText = getTextSlice(start: leadingTriviaLength, length: tokenLength)
return TokenKind.fromRawValue(kind: tokenKind, textBuffer: tokenText)
}
func formLeadingTrivia() -> Trivia {
var newPieces: [TriviaPiece] = []
newPieces.reserveCapacity(leadingTriviaBuffer.count)
if fullTextBuffer.isEmpty {
// Fast path, there's no text in the buffer so no need to determine the
// trivia piece length.
for cpiece in leadingTriviaBuffer {
let newPiece = TriviaPiece.fromRawValue(cpiece, textBuffer: emptyStringBuffer)
newPieces.append(newPiece)
}
} else {
var textOffset = 0
for cpiece in leadingTriviaBuffer {
let len = Int(cpiece.length)
let textBuffer = getTextSlice(start: textOffset, length: len)
let newPiece = TriviaPiece.fromRawValue(cpiece, textBuffer: textBuffer)
newPieces.append(newPiece)
textOffset += len
}
}
return .init(pieces: newPieces)
}
func formTrailingTrivia() -> Trivia {
var newPieces: [TriviaPiece] = []
newPieces.reserveCapacity(trailingTriviaBuffer.count)
if fullTextBuffer.isEmpty {
// Fast path, there's no text in the buffer so no need to determine the
// trivia piece length.
for cpiece in trailingTriviaBuffer {
let newPiece = TriviaPiece.fromRawValue(cpiece, textBuffer: emptyStringBuffer)
newPieces.append(newPiece)
}
} else {
let leadingTriviaLength = self.getLeadingTriviaLength()
let trailingTriviaLength = self.getTrailingTriviaLength()
let tokenLength = Int(length) - (leadingTriviaLength + trailingTriviaLength)
var textOffset = leadingTriviaLength + tokenLength
for cpiece in trailingTriviaBuffer {
let len = Int(cpiece.length)
let textBuffer = getTextSlice(start: textOffset, length: len)
let newPiece = TriviaPiece.fromRawValue(cpiece, textBuffer: textBuffer)
newPieces.append(newPiece)
textOffset += len
}
}
return .init(pieces: newPieces)
}
func getTokenText(relativeOffset: Int) -> UnsafeTokenText {
let leadingTriviaLength = relativeOffset
let trailingTriviaLength = self.getTrailingTriviaLength()
let tokenLength = Int(length) - (leadingTriviaLength + trailingTriviaLength)
let customText = fullTextBuffer.isEmpty ? emptyStringBuffer :
getTextSlice(start: relativeOffset, length: tokenLength)
return .init(kind: .fromRawValue(tokenKind), length: tokenLength, customText: customText)
}
func getLeadingTriviaPiece(
at index: Int, relativeOffset: Int
) -> UnsafeTriviaPiece? {
return getTriviaPiece(at: index, relativeOffset: relativeOffset,
trivia: leadingTriviaBuffer)
}
func getTrailingTriviaPiece(
at index: Int, relativeOffset: Int
) -> UnsafeTriviaPiece? {
return getTriviaPiece(at: index, relativeOffset: relativeOffset,
trivia: trailingTriviaBuffer)
}
private func getTriviaPiece(
at index: Int,
relativeOffset: Int,
trivia: UnsafeBufferPointer<CTriviaPiece>
) -> UnsafeTriviaPiece? {
guard index < trivia.count else { return nil }
let cpiece = trivia[index]
let length = Int(cpiece.length)
let customText = fullTextBuffer.isEmpty ? emptyStringBuffer :
getTextSlice(start: relativeOffset, length: length)
return .init(kind: .fromRawValue(cpiece.kind), length: length, customText: customText)
}
func write<Target>(
to target: inout Target
) where Target: TextOutputStream {
if hasCustomText {
// Fast path, we recorded the full token text, including trivia.
// FIXME: A way to print the buffer directly and avoid the copy ?
target.write(String.fromBuffer(fullTextBuffer))
} else {
func printTrivia(_ buf: UnsafeBufferPointer<CTriviaPiece>) {
for cpiece in buf {
let newPiece = TriviaPiece.fromRawValue(cpiece, textBuffer: emptyStringBuffer)
newPiece.write(to: &target)
}
}
printTrivia(leadingTriviaBuffer)
let tokKind = TokenKind.fromRawValue(kind: tokenKind,
textBuffer: emptyStringBuffer)
target.write(tokKind.text)
printTrivia(trailingTriviaBuffer)
}
}
func getLeadingTriviaLength() -> Int {
var len = 0
for piece in leadingTriviaBuffer { len += Int(piece.length) }
return len
}
func getTrailingTriviaLength() -> Int {
var len = 0
for piece in trailingTriviaBuffer { len += Int(piece.length) }
return len
}
func getTextSlice(start: Int, length: Int) -> UnsafeBufferPointer<UInt8> {
return .init(rebasing: fullTextBuffer[start..<start+length])
}
}
/// Low-level data specific to layout nodes.
///
/// There's additional data that are tail-allocated. The data are as follows:
///
/// * For a parsed token (`LayoutData.isConstructed` is false):
/// * List of `CClientNode?` values
/// * For a constructed token (`LayoutData.isConstructed` is true):
/// * A `ConstructedLayoutData` value
fileprivate struct LayoutData {
let nodeCount: UInt32
let totalSubNodeCount: UInt32
let syntaxKind: SyntaxKind
private let isConstructed: Bool
private init(
kind: SyntaxKind,
nodeCount: UInt32,
totalSubNodeCount: UInt32,
isConstructed: Bool
) {
assert(kind != .token)
self.syntaxKind = kind
self.nodeCount = nodeCount
self.totalSubNodeCount = totalSubNodeCount
self.isConstructed = isConstructed
}
/// Returns header `RawSyntaxData` value and number of elements to tail-allocate.
static func dataAndExtraCapacity(
for kind: SyntaxKind,
data: CLayoutData
) -> (RawSyntaxData, Int) {
var totalCount = 0
for i in 0..<Int(data.nodes_count) {
if let raw = RawSyntax.getFromOpaque(data.nodes![i]) {
totalCount += raw.totalNodes
}
}
let totalSubNodeCount = UInt32(truncatingIfNeeded: totalCount)
let rawData: RawSyntaxData = .layout(.init(kind: kind,
nodeCount: data.nodes_count, totalSubNodeCount: totalSubNodeCount,
isConstructed: false))
return (rawData, Int(data.nodes_count))
}
/// Initializes the tail-allocated elements.
static func initializeExtra(
_ data: CLayoutData,
extraPtr: MutableDataElementPtr
) {
var curPtr = extraPtr
for i in 0..<Int(data.nodes_count) {
assert(MemoryLayout.size(ofValue: data.nodes![i])
<= MemoryLayout<RawSyntaxDataElement>.size)
initializeElement(curPtr, with: data.nodes![i])
curPtr = curPtr.successor()
}
}
/// Returns header `RawSyntaxData` value and number of elements to tail-allocate.
static func dataAndExtraCapacity(
for kind: SyntaxKind,
data: ConstructedLayoutData
) -> (RawSyntaxData, Int) {
var totalCount = 0
for raw in data.layout {
totalCount += raw?.totalNodes ?? 0
}
let rawData: RawSyntaxData = .layout(.init(kind: kind,
nodeCount: UInt32(truncatingIfNeeded: data.layout.count),
totalSubNodeCount: UInt32(truncatingIfNeeded: totalCount),
isConstructed: true))
let capacity = numberOfElements(for: data)
return (rawData, capacity)
}
/// Initializes the tail-allocated elements.
static func initializeExtra(
_ data: ConstructedLayoutData,
extraPtr: MutableDataElementPtr
) {
initializeElement(extraPtr, with: data)
}
/// De-initializes memory from tail-allocated data.
fileprivate func deinitialize(extraPtr: MutableDataElementPtr) {
if isParsed {
for i in 0..<numberOfChildren {
let cnode: CClientNode? = readElement(extraPtr.advanced(by: i))
_ = RawSyntax.moveFromOpaque(cnode)
}
} else {
let ptr: UnsafeMutablePointer<ConstructedLayoutData> = castElementAs(extraPtr)
ptr.deinitialize(count: 1)
}
}
private var isParsed: Bool { return !isConstructed }
/// Total number of nodes in this sub-tree, including `self` node.
var totalNodes: Int {
return Int(totalSubNodeCount) + 1
}
var numberOfChildren: Int {
return Int(nodeCount)
}
func child(
at index: Int,
extraPtr: DataElementPtr
) -> RawSyntax? {
if isParsed {
let cnode: CClientNode? = readElement(extraPtr.advanced(by: index))
return RawSyntax.getFromOpaque(cnode)
} else {
let p: UnsafePointer<ConstructedLayoutData> = castElementAs(extraPtr)
return p.pointee.layout[index]
}
}
func hasChild(
at index: Int,
extraPtr: DataElementPtr
) -> Bool {
if isParsed {
let cnode: CClientNode? = readElement(extraPtr.advanced(by: index))
return cnode != nil
} else {
let p: UnsafePointer<ConstructedLayoutData> = castElementAs(extraPtr)
return p.pointee.layout[index] != nil
}
}
func formLayoutArray(extraPtr: DataElementPtr) -> [RawSyntax?] {
if isParsed {
var layout: [RawSyntax?] = []
layout.reserveCapacity(numberOfChildren)
let p: UnsafePointer<CClientNode?> = castElementAs(extraPtr)
for i in 0..<numberOfChildren {
layout.append(.getFromOpaque(p[i]))
}
return layout
} else {
let p: UnsafePointer<ConstructedLayoutData> = castElementAs(extraPtr)
return p.pointee.layout
}
}
}
/// Value used when a token is programmatically constructed, instead of the
/// parser producing it.
fileprivate struct ConstructedTokenData {
let kind: TokenKind
let leadingTrivia: Trivia
let trailingTrivia: Trivia
func write<Target>(
to target: inout Target
) where Target: TextOutputStream {
for piece in leadingTrivia {
piece.write(to: &target)
}
target.write(kind.text)
for piece in trailingTrivia {
piece.write(to: &target)
}
}
}
/// Value used when a layout node is programmatically constructed, instead of the
/// parser producing it.
fileprivate struct ConstructedLayoutData {
let layout: [RawSyntax?]
}
/// The data that is specific to a tree or token node
fileprivate enum RawSyntaxData {
/// A token with a token kind, leading trivia, and trailing trivia
case token(TokenData)
/// A tree node with a kind and an array of children
case layout(LayoutData)
}
/// Header for `RawSyntax`.
struct RawSyntaxBase {
fileprivate let data: RawSyntaxData
fileprivate let byteLength: UInt32
fileprivate let isPresent: Bool
fileprivate init(data: RawSyntaxData, byteLength: Int, isPresent: Bool) {
self.data = data
self.byteLength = UInt32(truncatingIfNeeded: byteLength)
self.isPresent = isPresent
}
fileprivate func deinitialize(extraPtr: MutableDataElementPtr) {
switch data {
case .token(let data): data.deinitialize(extraPtr: extraPtr)
case .layout(let data): data.deinitialize(extraPtr: extraPtr)
}
}
fileprivate var kind: SyntaxKind {
switch data {
case .token(_): return .token
case .layout(let data): return data.syntaxKind
}
}
fileprivate var isToken: Bool {
switch data {
case .token(_): return true
case .layout(_): return false
}
}
fileprivate func child(
at index: Int,
extraPtr: DataElementPtr
) -> RawSyntax? {
switch data {
case .token(_): return nil
case .layout(let data): return data.child(at: index, extraPtr: extraPtr)
}
}
fileprivate func hasChild(
at index: Int,
extraPtr: DataElementPtr
) -> Bool {
switch data {
case .token(_): return false
case .layout(let data): return data.hasChild(at: index, extraPtr: extraPtr)
}
}
/// The number of children, `present` or `missing`, in this node.
fileprivate var numberOfChildren: Int {
switch data {
case .token(_): return 0
case .layout(let data): return data.numberOfChildren
}
}
/// Total number of nodes in this sub-tree, including `self` node.
fileprivate var totalNodes: Int {
switch data {
case .token(_): return 1
case .layout(let data): return data.totalNodes
}
}
fileprivate func formLayoutArray(extraPtr: DataElementPtr) -> [RawSyntax?] {
switch data {
case .token(_): return []
case .layout(let data): return data.formLayoutArray(extraPtr: extraPtr)
}
}
/// Returns the `TokenKind` for a token node.
/// - Returns: nil if called on a layout node.
fileprivate func formTokenKind(extraPtr: DataElementPtr) -> TokenKind? {
switch data {
case .token(let data):
return data.formTokenKind(length: byteLength, extraPtr: extraPtr)
case .layout(_): return nil
}
}
/// Returns the leading `Trivia` length for a token node.
/// - Returns: .zero if called on a layout node.
fileprivate func getTokenLeadingTriviaLength(
extraPtr: DataElementPtr
) -> SourceLength {
switch data {
case .token(let data):
return data.getLeadingTriviaLength(length: byteLength, extraPtr: extraPtr)
case .layout(_): return .zero
}
}
/// Returns the trailing `Trivia` length for a token node.
/// - Returns: .zero if called on a layout node.
fileprivate func getTokenTrailingTriviaLength(
extraPtr: DataElementPtr
) -> SourceLength {
switch data {
case .token(let data):
return data.getTrailingTriviaLength(length: byteLength, extraPtr: extraPtr)
case .layout(_): return .zero
}
}
/// Returns the leading `Trivia` for a token node.
/// - Returns: nil if called on a layout node.
fileprivate func formTokenLeadingTrivia(extraPtr: DataElementPtr) -> Trivia? {
switch data {
case .token(let data):
return data.formLeadingTrivia(length: byteLength, extraPtr: extraPtr)
case .layout(_): return nil
}
}
/// Returns the trailing `Trivia` for a token node.
/// - Returns: nil if called on a layout node.
fileprivate func formTokenTrailingTrivia(extraPtr: DataElementPtr) -> Trivia? {
switch data {
case .token(let data):
return data.formTrailingTrivia(length: byteLength, extraPtr: extraPtr)
case .layout(_): return nil
}
}
fileprivate func withUnsafeTokenText<Result>(
relativeOffset: Int,
extraPtr: DataElementPtr,
_ body: (UnsafeTokenText?) -> Result
) -> Result {
switch data {
case .token(let data):
return data.withUnsafeTokenText(relativeOffset: relativeOffset,
length: byteLength, extraPtr: extraPtr, body)
case .layout(_): return body(nil)
}
}
fileprivate func withUnsafeLeadingTriviaPiece<Result>(
at index: Int,
relativeOffset: Int,
extraPtr: DataElementPtr,
_ body: (UnsafeTriviaPiece?) -> Result
) -> Result {
switch data {
case .token(let data):
return data.withUnsafeLeadingTriviaPiece(at: index, relativeOffset: relativeOffset,
length: byteLength, extraPtr: extraPtr, body)
case .layout(_): return body(nil)
}
}
fileprivate func withUnsafeTrailingTriviaPiece<Result>(
at index: Int,
relativeOffset: Int,
extraPtr: DataElementPtr,
_ body: (UnsafeTriviaPiece?) -> Result
) -> Result {
switch data {
case .token(let data):
return data.withUnsafeTrailingTriviaPiece(at: index, relativeOffset: relativeOffset,
length: byteLength, extraPtr: extraPtr, body)
case .layout(_): return body(nil)
}
}
/// Prints the RawSyntax token. If self is a layout node it does nothing.
fileprivate func writeToken<Target>(
to target: inout Target, extraPtr: DataElementPtr
) where Target: TextOutputStream {
switch data {
case .token(let data):
data.write(to: &target, length: byteLength, extraPtr: extraPtr)
case .layout(_): return
}
}
}
/// Represents the raw tree structure underlying the syntax tree. These nodes
/// have no notion of identity and only provide structure to the tree. They
/// are immutable and can be freely shared between syntax nodes.
///
/// This is using ManagedBuffer as its underlying storage in order to reduce
/// heap allocations down to a single one, when it's created by the parser.
final class RawSyntax: ManagedBuffer<RawSyntaxBase, RawSyntaxDataElement> {
/// Create a token or layout node using the C parser library object.
static func create(
from p: UnsafePointer<CSyntaxNode>,
source: String
) -> RawSyntax {
let cnode = p.pointee
let byteLength = Int(cnode.range.length)
let isPresent = cnode.present
let data: RawSyntaxData
let capacity: Int
if cnode.kind == 0 {
(data, capacity) = TokenData.dataAndExtraCapacity(for: cnode)
} else {
(data, capacity) = LayoutData.dataAndExtraCapacity(
for: SyntaxKind.fromRawValue(cnode.kind), data: cnode.layout_data)
}
let buffer = self.create(minimumCapacity: capacity) { _ in
RawSyntaxBase(data: data, byteLength: byteLength, isPresent: isPresent)
}
let raw = unsafeDowncast(buffer, to: RawSyntax.self)
raw.withUnsafeMutablePointers {
switch $0.pointee.data {
case .token(let tokdata):
TokenData.initializeExtra(cnode, source: source,
hasCustomText: tokdata.hasCustomText, extraPtr: $1)
case .layout(_):
LayoutData.initializeExtra(cnode.layout_data, extraPtr: $1)
}
}
return raw
}
/// Create a layout node using the programmatic APIs.
static func create(
kind: SyntaxKind,
layout: [RawSyntax?],
length: SourceLength,
presence: SourcePresence
) -> RawSyntax {
let layoutData = ConstructedLayoutData(layout: layout)
let (data, capacity) =
LayoutData.dataAndExtraCapacity(for: kind, data: layoutData)
let buffer = self.create(minimumCapacity: capacity) { _ in
RawSyntaxBase(data: data, byteLength: length.utf8Length,
isPresent: presence == .present)
}
let raw = unsafeDowncast(buffer, to: RawSyntax.self)
raw.withUnsafeMutablePointerToElements {
LayoutData.initializeExtra(layoutData, extraPtr: $0)
}
return raw
}
/// Create a token node using the programmatic APIs.
static func create(
kind: TokenKind,
leadingTrivia: Trivia,
trailingTrivia: Trivia,
length: SourceLength,
presence: SourcePresence
) -> RawSyntax {
let tokdata = ConstructedTokenData(kind: kind, leadingTrivia: leadingTrivia,
trailingTrivia: trailingTrivia)
let (data, capacity) = TokenData.dataAndExtraCapacity(for: tokdata)
let buffer = self.create(minimumCapacity: capacity) { _ in
RawSyntaxBase(data: data, byteLength: length.utf8Length,
isPresent: presence == .present)
}
let raw = unsafeDowncast(buffer, to: RawSyntax.self)
raw.withUnsafeMutablePointerToElements {
TokenData.initializeExtra(tokdata, extraPtr: $0)
}
return raw
}
deinit {
return withUnsafeMutablePointers {
$0.pointee.deinitialize(extraPtr: $1)
}
}
/// The syntax kind of this raw syntax.
var kind: SyntaxKind {
return header.kind
}
/// Whether or not this node is a token one.
var isToken: Bool {
return header.isToken
}
func child(at index: Int) -> RawSyntax? {
return withUnsafeMutablePointers {
$0.pointee.child(at: index, extraPtr: $1)
}
}
func hasChild(at index: Int) -> Bool {
return withUnsafeMutablePointers {
$0.pointee.hasChild(at: index, extraPtr: $1)
}
}
/// The number of children, `present` or `missing`, in this node.
var numberOfChildren: Int {
return header.numberOfChildren
}
/// Total number of nodes in this sub-tree, including `self` node.
var totalNodes: Int {
return header.totalNodes
}
/// Whether this node is present in the original source.
var isPresent: Bool {
return header.isPresent
}
/// Whether this node is missing from the original source.
var isMissing: Bool {
return !isPresent
}
var presence: SourcePresence {
return isPresent ? .present : .missing
}
var totalLength: SourceLength {
return SourceLength(utf8Length: Int(header.byteLength))
}
func formTokenKind() -> TokenKind? {
return withUnsafeMutablePointers {
$0.pointee.formTokenKind(extraPtr: $1)
}
}
/// Returns the leading `Trivia` length for a token node.
/// - Returns: .zero if called on a layout node.
var tokenLeadingTriviaLength: SourceLength {
return withUnsafeMutablePointers {
$0.pointee.getTokenLeadingTriviaLength(extraPtr: $1)
}
}
/// Returns the trailing `Trivia` length for a token node.
/// - Returns: .zero if called on a layout node.
var tokenTrailingTriviaLength: SourceLength {
return withUnsafeMutablePointers {
$0.pointee.getTokenTrailingTriviaLength(extraPtr: $1)
}
}
/// Returns the leading `Trivia` for a token node.
/// - Returns: nil if called on a layout node.
func formTokenLeadingTrivia() -> Trivia? {
return withUnsafeMutablePointers {
$0.pointee.formTokenLeadingTrivia(extraPtr: $1)
}
}
/// Returns the trailing `Trivia` for a token node.
/// - Returns: nil if called on a layout node.
func formTokenTrailingTrivia() -> Trivia? {
return withUnsafeMutablePointers {
$0.pointee.formTokenTrailingTrivia(extraPtr: $1)
}
}
/// Passes token info to the provided closure as `UnsafeTokenText`.
/// - Parameters:
/// - relativeOffset: For efficiency, the caller keeps track of the relative
/// byte offset (from start of leading trivia) of the token text, to avoid
/// calculating it within this function.
/// - body: The closure that accepts the `UnsafeTokenText` value. This value
/// must not escape the closure.
/// - Returns: Return value of `body`.
func withUnsafeTokenText<Result>(
relativeOffset: Int,
_ body: (UnsafeTokenText?) -> Result
) -> Result {
return withUnsafeMutablePointers {
$0.pointee.withUnsafeTokenText(relativeOffset: relativeOffset,
extraPtr: $1, body)
}
}
/// Passes trivia piece info to the provided closure as `UnsafeTriviaPiece`.
/// - Parameters:
/// - at: The index for the trivia piace.
/// - relativeOffset: For efficiency, the caller keeps track of the relative
/// byte offset (from start of leading trivia) of the trivia piece text,
/// to avoid calculating it within this function.
/// - body: The closure that accepts the `UnsafeTokenText` value. This value
/// must not escape the closure.
/// - Returns: Return value of `body`.
func withUnsafeLeadingTriviaPiece<Result>(
at index: Int,
relativeOffset: Int,
_ body: (UnsafeTriviaPiece?) -> Result
) -> Result {
return withUnsafeMutablePointers {
$0.pointee.withUnsafeLeadingTriviaPiece(at: index,
relativeOffset: relativeOffset, extraPtr: $1, body)
}
}
/// Passes trivia piece info to the provided closure as `UnsafeTriviaPiece`.
/// - Parameters:
/// - at: The index for the trivia piace.
/// - relativeOffset: For efficiency, the caller keeps track of the relative
/// byte offset (from start of leading trivia) of the trivia piece text,
/// to avoid calculating it within this function.
/// - body: The closure that accepts the `UnsafeTokenText` value. This value
/// must not escape the closure.
/// - Returns: Return value of `body`.
func withUnsafeTrailingTriviaPiece<Result>(
at index: Int,
relativeOffset: Int,
_ body: (UnsafeTriviaPiece?) -> Result
) -> Result {
return withUnsafeMutablePointers {
$0.pointee.withUnsafeTrailingTriviaPiece(at: index,
relativeOffset: relativeOffset, extraPtr: $1, body)
}
}
func formLayoutArray() -> [RawSyntax?] {
return withUnsafeMutablePointers {
$0.pointee.formLayoutArray(extraPtr: $1)
}
}
func withLeadingTrivia(_ leadingTrivia: Trivia) -> RawSyntax {
if isToken {
return RawSyntax.createAndCalcLength(
kind: formTokenKind()!,
leadingTrivia: leadingTrivia,
trailingTrivia: formTrailingTrivia()!,
presence: presence)
} else {
var layout = formLayoutArray()
for (index, raw) in layout.enumerated() {
if let raw = raw {
layout[index] = raw.withLeadingTrivia(leadingTrivia)
return replacingLayout(layout)
}
}
return self
}
}
func withTrailingTrivia(_ trailingTrivia: Trivia) -> RawSyntax {
if isToken {
return RawSyntax.createAndCalcLength(
kind: formTokenKind()!,
leadingTrivia: formLeadingTrivia()!,
trailingTrivia: trailingTrivia,
presence: presence)
} else {
var layout = formLayoutArray()
for (index, raw) in layout.enumerated().reversed() {
if let raw = raw {
layout[index] = raw.withTrailingTrivia(trailingTrivia)
return replacingLayout(layout)
}
}
return self
}
}
/// Creates a RawSyntax node that's marked missing in the source with the
/// provided kind and layout.
/// - Parameters:
/// - kind: The syntax kind underlying this node.
/// - layout: The children of this node.
/// - Returns: A new RawSyntax `.node` with the provided kind and layout, with
/// `.missing` source presence.
static func missing(_ kind: SyntaxKind) -> RawSyntax {
return create(kind: kind, layout: [], length: .zero, presence: .missing)
}
/// Creates a RawSyntax token that's marked missing in the source with the
/// provided kind and no leading/trailing trivia.
/// - Parameter kind: The token kind.
/// - Returns: A new RawSyntax `.token` with the provided kind, no
/// leading/trailing trivia, and `.missing` source presence.
static func missingToken(_ kind: TokenKind) -> RawSyntax {
return create(kind: kind, leadingTrivia: [], trailingTrivia: [],
length: .zero, presence: .missing)
}
/// Returns a new RawSyntax node with the provided layout instead of the
/// existing layout.
/// - Note: This function does nothing with `.token` nodes --- the same token
/// is returned.
/// - Parameter newLayout: The children of the new node you're creating.
func replacingLayout(_ newLayout: [RawSyntax?]) -> RawSyntax {
if isToken { return self }
return .createAndCalcLength(kind: kind, layout: newLayout, presence: presence)
}
/// Creates a new RawSyntax with the provided child appended to its layout.
/// - Parameter child: The child to append
/// - Note: This function does nothing with `.token` nodes --- the same token
/// is returned.
/// - Return: A new RawSyntax node with the provided child at the end.
func appending(_ child: RawSyntax) -> RawSyntax {
var newLayout = formLayoutArray()
newLayout.append(child)
return replacingLayout(newLayout)
}
/// Returns the child at the provided cursor in the layout.
/// - Parameter index: The index of the child you're accessing.
/// - Returns: The child at the provided index.
subscript<CursorType: RawRepresentable>(_ index: CursorType) -> RawSyntax?
where CursorType.RawValue == Int {
return child(at: index.rawValue)
}
/// Replaces the child at the provided index in this node with the provided
/// child.
/// - Parameters:
/// - index: The index of the child to replace.
/// - newChild: The new child that should occupy that index in the node.
func replacingChild(_ index: Int,
with newChild: RawSyntax?) -> RawSyntax {
precondition(index < numberOfChildren, "Cursor \(index) reached past layout")
var newLayout = formLayoutArray()
newLayout[index] = newChild
return replacingLayout(newLayout)
}
}
extension RawSyntax {
static func moveFromOpaque(_ cn: CClientNode?) -> RawSyntax? {
if let subnode = cn {
return Unmanaged<RawSyntax>.fromOpaque(subnode).takeRetainedValue()
} else {
return nil
}
}
static func getFromOpaque(_ cn: CClientNode?) -> RawSyntax? {
if let subnode = cn {
return Unmanaged<RawSyntax>.fromOpaque(subnode).takeUnretainedValue()
} else {
return nil
}
}
}
extension RawSyntax: TextOutputStreamable, CustomStringConvertible {
/// Prints the RawSyntax node, and all of its children, to the provided
/// stream. This implementation must be source-accurate.
/// - Parameter stream: The stream on which to output this node.
func write<Target>(to target: inout Target)
where Target: TextOutputStream {
guard isPresent else { return }
if isToken {
withUnsafeMutablePointers {
$0.pointee.writeToken(to: &target, extraPtr: $1)
}
} else {
for i in 0..<self.numberOfChildren {
self.child(at: i)?.write(to: &target)
}
}
}
/// A source-accurate description of this node.
var description: String {
var s = ""
self.write(to: &s)
return s
}
}
extension RawSyntax {
/// Return the first `present` token of a layout node or self if it is a token.
var firstPresentToken: RawSyntax? {
guard isPresent else { return nil }
if isToken { return self }
for i in 0..<self.numberOfChildren {
if let token = self.child(at: i)?.firstPresentToken {
return token
}
}
return nil
}
/// Return the last `present` token of a layout node or self if it is a token.
var lastPresentToken: RawSyntax? {
guard isPresent else { return nil }
if isToken { return self }
for i in (0..<self.numberOfChildren).reversed() {
if let token = self.child(at: i)?.lastPresentToken {
return token
}
}
return nil
}
func formLeadingTrivia() -> Trivia? {
guard let token = self.firstPresentToken else { return nil }
return token.formTokenLeadingTrivia()
}
func formTrailingTrivia() -> Trivia? {
guard let token = self.lastPresentToken else { return nil }
return token.formTokenTrailingTrivia()
}
}
extension RawSyntax {
var leadingTriviaLength: SourceLength {
guard let token = self.firstPresentToken else { return .zero }
return token.tokenLeadingTriviaLength
}
var trailingTriviaLength: SourceLength {
guard let token = self.lastPresentToken else { return .zero }
return token.tokenTrailingTriviaLength
}
/// The length of this node excluding its leading and trailing trivia.
var contentLength: SourceLength {
return totalLength - (leadingTriviaLength + trailingTriviaLength)
}
var tokenContentLength: SourceLength {
return totalLength - (tokenLeadingTriviaLength + tokenTrailingTriviaLength)
}
/// Convenience function to create a RawSyntax when its byte length is not
/// known in advance, e.g. it is programmatically constructed instead of
/// created by the parser.
///
/// This is a separate function than in the initializer to make it more
/// explicit and visible in the code for the instances where we don't have
/// the length of the raw node already available.
static func createAndCalcLength(kind: SyntaxKind, layout: [RawSyntax?],
presence: SourcePresence) -> RawSyntax {
let length: SourceLength
if case .missing = presence {
length = SourceLength.zero
} else {
var totalen = SourceLength.zero
for child in layout {
totalen += child?.totalLength ?? .zero
}
length = totalen
}
return create(kind: kind, layout: layout, length: length, presence: presence)
}
/// Convenience function to create a RawSyntax when its byte length is not
/// known in advance, e.g. it is programmatically constructed instead of
/// created by the parser.
///
/// This is a separate function than in the initializer to make it more
/// explicit and visible in the code for the instances where we don't have
/// the length of the raw node already available.
static func createAndCalcLength(kind: TokenKind, leadingTrivia: Trivia,
trailingTrivia: Trivia, presence: SourcePresence) -> RawSyntax {
let length: SourceLength
if case .missing = presence {
length = SourceLength.zero
} else {
length = kind.sourceLength + leadingTrivia.sourceLength +
trailingTrivia.sourceLength
}
return create(kind: kind, leadingTrivia: leadingTrivia,
trailingTrivia: trailingTrivia, length: length, presence: presence)
}
}
/// Token info with its custom text as `UnsafeBufferPointer`. This is only safe
/// to use from within the `withUnsafeTokenText` methods.
internal struct UnsafeTokenText {
let kind: RawTokenKind
let length: Int
let customText: UnsafeBufferPointer<UInt8>
init(kind: RawTokenKind, length: Int) {
self.kind = kind
self.length = length
self.customText = .init(start: nil, count: 0)
}
init(kind: RawTokenKind, length: Int, customText: UnsafeBufferPointer<UInt8>) {
self.kind = kind
self.length = length
self.customText = customText
}
}
/// Trivia piece info with its custom text as `UnsafeBufferPointer`. This is
/// only safe to use from within the `withUnsafeLeadingTriviaPiece` and
/// `withUnsafeTrailingTriviaPiece` methods.
internal struct UnsafeTriviaPiece {
let kind: TriviaPieceKind
let length: Int
let customText: UnsafeBufferPointer<UInt8>
init(kind: TriviaPieceKind, length: Int) {
self.kind = kind
self.length = length
self.customText = .init(start: nil, count: 0)
}
init(kind: TriviaPieceKind, length: Int, customText: UnsafeBufferPointer<UInt8>) {
self.kind = kind
self.length = length
self.customText = customText
}
static func fromRawValue(
_ piece: CTriviaPiece, textBuffer: UnsafeBufferPointer<UInt8>
) -> UnsafeTriviaPiece {
return UnsafeTriviaPiece(kind: .fromRawValue(piece.kind),
length: Int(piece.length), customText: textBuffer)
}
}
| 34.002857 | 93 | 0.692442 |
8744182d8222f4144709f5ff4666b2fec2c471a2
| 548 |
//
// AKeychainServicesAPIError.swift
// ASecurity
//
// Created by Ihor Myroniuk on 3/10/20.
// Copyright © 2020 ihormyroniuk. All rights reserved.
//
public struct KeychainServicesApiError: Error, CustomStringConvertible {
let status: OSStatus
// MARK: CustomStringConvertible
public var description: String {
if #available(iOS 11.3, *), let message = SecCopyErrorMessageString(status, nil) {
return "\(status) \(message)"
} else {
return "\(status)"
}
}
}
| 22.833333 | 90 | 0.618613 |
87de3018a55bc24f2affa91cb566e30f28eeef0e
| 4,688 |
//
// CivicViewModel.swift
// SmartMacOSUILibrary
//
// Created by Michael Rommel on 16.05.21.
//
import SwiftUI
import SmartAILibrary
import SmartAssets
enum CivicTypeState {
case researched
case selected
case possible
case disabled
func backgroundTexture() -> String {
switch self {
case .researched:
return "civicInfo-researched"
case .selected:
return "civicInfo-researching"
case .possible:
return "civicInfo-active"
case .disabled:
return "civicInfo-disabled"
}
}
}
protocol CivicViewModelDelegate: AnyObject {
func selected(civic: CivicType)
}
class CivicViewModel: ObservableObject, Identifiable {
let id: UUID = UUID()
var civicType: CivicType
@Published
var state: CivicTypeState
@Published
var achievementViewModels: [AchievementViewModel] = []
let boosted: Bool
let turns: Int
weak var delegate: CivicViewModelDelegate?
init(civicType: CivicType, state: CivicTypeState, boosted: Bool, turns: Int) {
self.civicType = civicType
self.state = state
self.boosted = boosted
self.turns = turns
self.achievementViewModels = self.achievements()
}
func title() -> String {
return self.civicType.name()
}
func icon() -> NSImage {
return ImageCache.shared.image(for: self.civicType.iconTexture())
}
func background() -> NSImage {
return ImageCache.shared.image(for: self.state.backgroundTexture()).resize(withSize: NSSize(width: 42, height: 42))!
}
private func achievements() -> [AchievementViewModel] {
var achievementViewModels: [AchievementViewModel] = []
let achievements = self.civicType.achievements()
for buildingType in achievements.buildingTypes {
achievementViewModels.append(
AchievementViewModel(
imageName: buildingType.iconTexture(),
toolTipText: buildingType.toolTip()
)
)
}
for unitType in achievements.unitTypes {
achievementViewModels.append(
AchievementViewModel(
imageName: unitType.typeTexture(),
toolTipText: unitType.toolTip()
)
)
}
for wonderType in achievements.wonderTypes {
achievementViewModels.append(
AchievementViewModel(
imageName: wonderType.iconTexture(),
toolTipText: wonderType.toolTip()
)
)
}
for buildType in achievements.buildTypes {
achievementViewModels.append(
AchievementViewModel(
imageName: buildType.iconTexture(),
toolTipText: buildType.toolTip()
)
)
}
for districtType in achievements.districtTypes {
achievementViewModels.append(
AchievementViewModel(
imageName: districtType.iconTexture(),
toolTipText: districtType.toolTip()
)
)
}
for policyCard in achievements.policyCards {
achievementViewModels.append(
AchievementViewModel(
imageName: policyCard.iconTexture(),
toolTipText: policyCard.toolTip()
)
)
}
if self.civicType.governorTitle() {
achievementViewModels.append(
AchievementViewModel(
imageName: "header-button-governors-active",
toolTipText: NSAttributedString(string: "Governor title")
)
)
}
return achievementViewModels
}
func turnsText() -> String {
if self.turns == -1 {
return ""
}
return "Turns \(self.turns)"
}
func boostText() -> String {
if self.civicType.eurekaSummary() == "" {
return ""
}
if self.boosted {
return "Boosted: " + self.civicType.eurekaSummary()
} else {
return "To boost: " + self.civicType.eurekaSummary()
}
}
func selectCivic() {
self.delegate?.selected(civic: self.civicType)
}
}
extension CivicViewModel: Hashable {
static func == (lhs: CivicViewModel, rhs: CivicViewModel) -> Bool {
return lhs.civicType == rhs.civicType
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.civicType)
}
}
| 24.164948 | 124 | 0.564206 |
90d41c6db5a7045a4e3dd97528eede2757fbac6e
| 1,453 |
//
// NetworkRequestStatusCode.swift
// XrayLogger
//
// Created by Alex Zchut on 21/12/2021.
// Copyright © 2021 Applicaster. All rights reserved.
//
import Foundation
public enum NetworkRequestStatusCode: NSInteger {
case x000 = 0
case x200 = 200
case x300 = 300
case x400 = 400
case x500 = 500
public init?(statusCode: String) {
let stringValue = "\(statusCode.first ?? "1")00"
guard let intValue = Int(stringValue),
let value = NetworkRequestStatusCode(rawValue: intValue) else {
return nil
}
self = value
}
public func toString() -> String {
switch self {
case .x200:
return "2xx"
case .x300:
return "3xx"
case .x400:
return "4xx"
case .x500:
return "5xx"
default:
return "0"
}
}
public func toColor() -> UIColor {
switch self {
case .x200:
return UIColor(red: 76 / 255, green: 153 / 255, blue: 0 / 255, alpha: 1)
case .x300:
return UIColor(red: 153 / 255, green: 153 / 255, blue: 0 / 255, alpha: 1)
case .x400:
return UIColor(red: 153 / 255, green: 76 / 255, blue: 0 / 255, alpha: 1)
case .x500:
return UIColor(red: 153 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1)
default:
return UIColor.white
}
}
}
| 25.491228 | 85 | 0.52925 |
fe035a14fd3a5c906a3b9c27daa542ac821aab1a
| 1,036 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -disable-availability-checking -enable-implicit-dynamic -enable-private-imports %S/Inputs/opaque_return_type_parameter.swift -module-name Repo -emit-module -emit-module-path %t/Repo.swiftmodule -requirement-machine-abstract-signatures=verify
// RUN: %target-swift-frontend -disable-availability-checking -I %t -module-name A -swift-version 5 -primary-file %s -emit-ir -requirement-machine-abstract-signatures=verify | %FileCheck %s
// RUN: %target-swift-frontend -disable-availability-checking -I %t -module-name A -swift-version 5 -primary-file %s -c -o %t/tmp.o -requirement-machine-abstract-signatures=verify
@_private(sourceFile: "opaque_return_type_parameter.swift") import Repo
// Make sure we are not emitting a replacement for the opaque result type used as parameter (Assoc).
// CHECK-NOT: @"\01l_unnamed_dynamic_replacements"{{.*}}(%swift.type_descriptor* ()*
extension Container {
@_dynamicReplacement(for: update(arg:)) private func __update(arg: Assoc) {}
}
| 74 | 272 | 0.772201 |
ab6d4ba32b52b840cd20175f315cbd2aad29ec1b
| 112 |
import PalveluData
import NaamioCore
public class HealthQueryResponse: Mappable {
public init() {}
}
| 12.444444 | 44 | 0.723214 |
144bf4793a51176b9ce3a73a5c6ffc70e2ad1ef4
| 417 |
//
// AddUserDomainModel.swift
// Pods
//
// Created by Timmy Nguyen on 2/16/18.
//
//
import Foundation
import ObjectMapper
public class AddRoomModel: BaseApiResponseModel {
public var roomId: Int?
required public init?(map: Map){
super.init(map: map)
}
override public func mapping(map: Map) {
super.mapping(map: map)
roomId <- map["room_id"]
}
}
| 16.68 | 49 | 0.606715 |
263e6936c236ceb3ba782a280073ed2f1a1511ac
| 12,479 |
import UIKit
internal struct CellArticle {
let articleURL: URL?
let title: String?
let titleHTML: String?
let description: String?
let imageURL: URL?
}
public protocol SideScrollingCollectionViewCellDelegate: class {
func sideScrollingCollectionViewCell(_ sideScrollingCollectionViewCell: SideScrollingCollectionViewCell, didSelectArticleWithURL articleURL: URL, at indexPath: IndexPath)
}
public protocol SubCellProtocol {
func deselectSelectedSubItems(animated: Bool)
}
public class SideScrollingCollectionViewCell: CollectionViewCell, SubCellProtocol {
static let articleCellIdentifier = "ArticleRightAlignedImageCollectionViewCell"
var theme: Theme = Theme.standard
public weak var selectionDelegate: SideScrollingCollectionViewCellDelegate?
public let imageView = UIImageView()
public let titleLabel = UILabel()
public let subTitleLabel = UILabel()
public let descriptionLabel = UILabel()
internal var flowLayout: UICollectionViewFlowLayout? {
return collectionView.collectionViewLayout as? UICollectionViewFlowLayout
}
internal let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
internal let prototypeCell = ArticleRightAlignedImageCollectionViewCell()
var semanticContentAttributeOverride: UISemanticContentAttribute = .unspecified {
didSet {
titleLabel.semanticContentAttribute = semanticContentAttributeOverride
subTitleLabel.semanticContentAttribute = semanticContentAttributeOverride
descriptionLabel.semanticContentAttribute = semanticContentAttributeOverride
collectionView.semanticContentAttribute = semanticContentAttributeOverride
}
}
internal var articles: [CellArticle] = []
override open func setup() {
titleLabel.isOpaque = true
subTitleLabel.isOpaque = true
descriptionLabel.isOpaque = true
imageView.isOpaque = true
addSubview(titleLabel)
addSubview(subTitleLabel)
addSubview(descriptionLabel)
addSubview(imageView)
addSubview(collectionView)
addSubview(prototypeCell)
wmf_configureSubviewsForDynamicType()
//Setup the prototype cell with placeholder content so we can get an accurate height calculation for the collection view that accounts for dynamic type changes
prototypeCell.configure(with: CellArticle(articleURL: nil, title: "Lorem", titleHTML: "Lorem", description: "Ipsum", imageURL: nil), semanticContentAttribute: .forceLeftToRight, theme: self.theme, layoutOnly: true)
prototypeCell.isHidden = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
titleLabel.numberOfLines = 1
subTitleLabel.numberOfLines = 1
descriptionLabel.numberOfLines = 0
flowLayout?.scrollDirection = .horizontal
collectionView.register(ArticleRightAlignedImageCollectionViewCell.self, forCellWithReuseIdentifier: SideScrollingCollectionViewCell.articleCellIdentifier)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.alwaysBounceHorizontal = true
super.setup()
}
override open func reset() {
super.reset()
imageView.wmf_reset()
}
public var isImageViewHidden = false {
didSet {
imageView.isHidden = isImageViewHidden
setNeedsLayout()
}
}
public var imageViewHeight: CGFloat = 130 {
didSet {
setNeedsLayout()
}
}
public let spacing: CGFloat = 6
override public func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let layoutMargins = calculatedLayoutMargins
var origin = CGPoint(x: layoutMargins.left, y: layoutMargins.top)
let widthToFit = size.width - layoutMargins.left - layoutMargins.right
if !isImageViewHidden {
if (apply) {
let imageViewWidth = size.width - widthToFit > 50 ? widthToFit : size.width
imageView.frame = CGRect(x: round(0.5 * (size.width - imageViewWidth)), y: 0, width: imageViewWidth, height: imageViewHeight)
}
origin.y += imageViewHeight
}
if titleLabel.wmf_hasAnyText {
origin.y += spacing
origin.y += titleLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: round(0.4 * spacing), apply: apply)
}
if subTitleLabel.wmf_hasAnyText {
origin.y += 0
origin.y += subTitleLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: spacing, apply: apply)
}
origin.y += spacing
origin.y += descriptionLabel.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: spacing, apply: apply)
let collectionViewSpacing: CGFloat = 10
var height = prototypeCell.wmf_preferredHeight(at: origin, maximumWidth: widthToFit, alignedBy: semanticContentAttributeOverride, spacing: 2*collectionViewSpacing, apply: false)
if articles.isEmpty {
height = 0
}
if (apply) {
flowLayout?.itemSize = CGSize(width: 250, height: height - 2*collectionViewSpacing)
flowLayout?.minimumInteritemSpacing = collectionViewSpacing
flowLayout?.minimumLineSpacing = 15
flowLayout?.sectionInset = UIEdgeInsets(top: collectionViewSpacing, left: collectionViewSpacing, bottom: collectionViewSpacing, right: collectionViewSpacing)
collectionView.frame = CGRect(x: 0, y: origin.y, width: size.width, height: height)
if semanticContentAttributeOverride == .forceRightToLeft {
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: layoutMargins.right - collectionViewSpacing)
} else {
collectionView.contentInset = UIEdgeInsets(top: 0, left: layoutMargins.left - collectionViewSpacing, bottom: 0, right: 0)
}
collectionView.reloadData()
collectionView.layoutIfNeeded()
deselectSelectedSubItems(animated: false)
}
origin.y += height
origin.y += layoutMargins.bottom
return CGSize(width: size.width, height: origin.y)
}
public func resetContentOffset() {
let x: CGFloat = semanticContentAttributeOverride == .forceRightToLeft ? collectionView.contentSize.width - collectionView.bounds.size.width + collectionView.contentInset.right : -collectionView.contentInset.left
collectionView.contentOffset = CGPoint(x: x, y: 0)
}
public func deselectSelectedSubItems(animated: Bool) {
guard let selectedIndexPaths = collectionView.indexPathsForSelectedItems else {
return
}
for indexPath in selectedIndexPaths {
collectionView.deselectItem(at: indexPath, animated: animated)
}
}
override public func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
titleLabel.backgroundColor = labelBackgroundColor
subTitleLabel.backgroundColor = labelBackgroundColor
descriptionLabel.backgroundColor = labelBackgroundColor
}
}
extension SideScrollingCollectionViewCell: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedArticle = articles[indexPath.item]
guard let articleURL = selectedArticle.articleURL else {
return
}
selectionDelegate?.sideScrollingCollectionViewCell(self, didSelectArticleWithURL: articleURL, at: indexPath)
}
}
extension SideScrollingCollectionViewCell: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return articles.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SideScrollingCollectionViewCell.articleCellIdentifier, for: indexPath)
guard let articleCell = cell as? ArticleRightAlignedImageCollectionViewCell else {
return cell
}
let articleForCell = articles[indexPath.item]
articleCell.configure(with: articleForCell, semanticContentAttribute: semanticContentAttributeOverride, theme: self.theme, layoutOnly: false)
return articleCell
}
}
fileprivate extension ArticleRightAlignedImageCollectionViewCell {
func configure(with cellArticle: CellArticle, semanticContentAttribute: UISemanticContentAttribute, theme: Theme, layoutOnly: Bool) {
apply(theme: theme)
backgroundColor = .clear
setBackgroundColors(theme.colors.subCellBackground, selected: theme.colors.midBackground)
backgroundView?.layer.cornerRadius = 3
backgroundView?.layer.masksToBounds = true
selectedBackgroundView?.layer.cornerRadius = 3
selectedBackgroundView?.layer.masksToBounds = true
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowOpacity = 1.0
layer.shadowRadius = 3
layer.shadowColor = theme.colors.shadow.cgColor
layer.masksToBounds = false
titleLabel.backgroundColor = backgroundView?.backgroundColor
descriptionLabel.backgroundColor = backgroundView?.backgroundColor
titleTextStyle = .subheadline
descriptionTextStyle = .footnote
imageViewDimension = 40
layoutMargins = UIEdgeInsets(top: 9, left: 10, bottom: 9, right: 10)
isImageViewHidden = layoutOnly || cellArticle.imageURL == nil
titleHTML = cellArticle.titleHTML ?? cellArticle.title
descriptionLabel.text = cellArticle.description
articleSemanticContentAttribute = semanticContentAttribute
if let imageURL = cellArticle.imageURL {
isImageViewHidden = false
if !layoutOnly {
imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: { (error) in }, success: { })
}
} else {
isImageViewHidden = true
}
updateFonts(with: traitCollection)
setNeedsLayout()
}
}
extension SideScrollingCollectionViewCell {
public func subItemIndex(at point: CGPoint) -> Int { // NSNotFound for not found
let collectionViewFrame = collectionView.frame
guard collectionViewFrame.contains(point) else {
return NSNotFound
}
let pointInCollectionViewCoordinates = convert(point, to: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: pointInCollectionViewCoordinates) else {
return NSNotFound
}
return indexPath.item
}
public func viewForSubItem(at index: Int) -> UIView? {
guard index != NSNotFound, index >= 0, index < collectionView.numberOfItems(inSection: 0) else {
return nil
}
guard let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) else {
return nil
}
return cell
}
}
extension SideScrollingCollectionViewCell: Themeable {
public func apply(theme: Theme) {
self.theme = theme
imageView.alpha = theme.imageOpacity
setBackgroundColors(theme.colors.paperBackground, selected: theme.colors.midBackground)
titleLabel.textColor = theme.colors.primaryText
subTitleLabel.textColor = theme.colors.secondaryText
descriptionLabel.textColor = theme.colors.primaryText
collectionView.backgroundColor = theme.colors.paperBackground
descriptionLabel.textColor = theme.colors.primaryText
updateSelectedOrHighlighted()
collectionView.reloadData()
imageView.accessibilityIgnoresInvertColors = true
}
}
| 43.329861 | 222 | 0.699655 |
038419551a3858c8fde82525c8f54667cc3b84da
| 3,026 |
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Created by Sam Deane on 10/02/22.
// All code (c) 2022 - present day, Elegant Chaos Limited.
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import BinaryCoding
import Foundation
/// Maps the coding keys for fields to their types
public struct FieldTypeMap {
struct Entry {
let type: BinaryDecodable.Type // TODO: Codable may be enough here.
let readKey: Tag
var groupWith: [Tag]
}
typealias Map = [String:Entry]
typealias NameMap = [Tag:String]
typealias GroupMap = [Tag:[Tag]]
private let index: Map
private let tagToName: NameMap
let tagOrder: [Tag]
init() {
index = [:]
tagToName = [:]
tagOrder = []
}
struct FieldSpec<K: CodingKey, T> {
let codingKey: K
let property: PartialKeyPath<T>
let tag: Tag
let groupWith: Tag?
internal init(_ key: K, _ path: PartialKeyPath<T>, _ tag: Tag, groupWith: Tag? = nil) {
self.codingKey = key
self.property = path
self.tag = tag
self.groupWith = groupWith
}
}
init<K, T>(fields map: [FieldSpec<K, T>]) where K: CodingKey {
var entries = Map()
var tagToName = NameMap()
var tagOrder: [Tag] = []
for spec in map {
let t: Any.Type
if let p = spec.property as? EnclosingType {
t = type(of: p).baseType
} else {
t = type(of: spec.property).valueType
}
entries[spec.codingKey.stringValue] = Entry(type: t as! BinaryDecodable.Type, readKey: spec.tag, groupWith: spec.groupWith == nil ? [spec.tag] : [])
tagToName[spec.tag] = spec.codingKey.stringValue
tagOrder.append(spec.tag)
}
for spec in map {
if let tag = spec.groupWith {
let name = tagToName[tag]!
entries[name]!.groupWith.append(spec.tag)
}
}
self.index = entries
self.tagToName = tagToName
self.tagOrder = tagOrder
}
init<K, T>(paths map: [(K, PartialKeyPath<T>, String)]) where K: CodingKey {
let specs: [FieldSpec<K, T>] = map.map{ .init($0.0, $0.1, Tag($0.2))}
self.init(fields: specs)
}
func haveMapping(forTag tag: Tag) -> Bool {
return tagToName[tag] != nil
}
func entry(forTag tag: Tag) -> Entry? {
guard let name = tagToName[tag] else { return nil }
return index[name]
}
func fieldType(forKey key: CodingKey) -> BinaryDecodable.Type? {
index[key.stringValue]?.type
}
func fieldType(forTag tag: Tag) -> BinaryDecodable.Type? {
guard let name = tagToName[tag] else { return nil }
return index[name]?.type
}
func fieldTag(forKey key: CodingKey) -> Tag? {
return index[key.stringValue]?.readKey
}
}
| 29.096154 | 160 | 0.52842 |
71e5c13d215c55465edca5a75e8b590091b3de15
| 328 |
//
// Chat.swift
// ADB
//
// Created by s on 2017-09-16.
// Copyright © 2017 Hudson Graeme. All rights reserved.
//
import Foundation
import Cocoa
class Chat: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.window?.styleMask.remove(NSWindowStyleMask.resizable)
}
}
| 17.263158 | 71 | 0.670732 |
fcc21e6e0c532c860217438d128da96aa1b6721e
| 1,029 |
//
// Filters.swift
// Perfect-App-Template
//
// Created by Jonathan Guthrie on 2017-02-20.
// Copyright (C) 2017 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectHTTPServer
import PerfectRequestLogger
func filters() -> [[String: Any]] {
var filters: [[String: Any]] = [[String: Any]]()
filters.append(["type":"response","priority":"high","name":PerfectHTTPServer.HTTPFilter.contentCompression])
filters.append(["type":"request","priority":"high","name":RequestLogger.filterAPIRequest])
filters.append(["type":"response","priority":"low","name":RequestLogger.filterAPIResponse])
return filters
}
| 31.181818 | 109 | 0.60447 |
f9069a9e3232ea0ca9b89452c6c9b375c0cb2333
| 1,403 |
//: A UIKit based Playground for presenting user interface
import UIKit
// Operadores Binários
// Operador de Atribuição: =
let gravity = 9.81
var (name, age) = ("Pablo", 39)
// Operadores Aritméticos:
/* Soma (+)
Subtração (-)
Multiplucação (*)
Divisão (/)
Módulo (%)
*/
var num1 = 5
var num2 = 10
// Soma
let sum = num1 + num2
// Subtração
let minus = num1 - num2
// Multiplicação
let multiply = num1 * num2
// Divisão
let division = num1 / num2
// Módulo ("Resto da divisão")
let toys = 35
let kids = 6
let modulus = toys % kids
/*===========================================================================================*/
// Operadores Compostos - "Atribui e opera ao mesmo tempo"
num2 += num1
//-=, *=, /=, %=
var products = 150
var lastBuy = 25
products -= lastBuy
// Operadores de Comparação - "Fazem comparação entre valores ( sempre retornam um bool, True or false)"
// Maior que: >
let grade1 = 7.5
let grade2 = 6.7
let betterthanFriend = grade1 > grade2
// Menor que: <
let grade = 8.0
let minimumGrade = 8.0
let reproved = grade < minimumGrade
// Maior ou igua: >=
// Menor ou igual: <=
let approved = grade >= minimumGrade
// Igualdade: ==
let name1 = "Pablo"
let name2 = "pablo"
let sameNames = name1.lowercased() == name2.lowercased() // .lowercased() {deixar letras em minusculas de uma string}
// Desigualdade; !=
let differentNames = name1 != name2
| 19.486111 | 117 | 0.618674 |
efaa51498f2e65d50b3410b4cbfc7aa4a22e2465
| 155 |
import AWSLambdaRuntime
Lambda.run { (_: Lambda.Context, _: String, callback: (Result<String, Error>) -> Void) in
callback(.success("hello, world!"))
}
| 25.833333 | 89 | 0.696774 |
6a3f8b950cab5a0cd9b46ec02c67f13efc017e0c
| 2,046 |
// Copyright (c) 2017 Hèctor Marquès Ranea
//
// 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 XCTest
@testable import StringsFileLib
final class ToExitStatusFromErrorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// 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.
}
}
static var allTests = [
("testExample", testExample),
]
}
| 39.346154 | 111 | 0.703324 |
f94ed4c1f63acb219697b54e0a35931fc0388b3e
| 276 |
//: [Previous](@previous)
import Foundation
var numbers = (1...9).publisher
/// First filtering will emit until finds the first value that meets the condition { $0 % 2 == 0 }
numbers
.first(where: { $0 % 2 == 0 })
.sink {
print($0)
}
//: [Next](@next)
| 18.4 | 98 | 0.57971 |
01a2c5646e22e690bdb53b9e388da9a1d2aa66bf
| 546 |
//
// LoadingView.swift
// Ahobsu
//
// Created by 김선재 on 05/03/2020.
// Copyright © 2020 ahobsu. All rights reserved.
//
import SwiftUI
struct LoadingView: View {
var isShowing: Bool
var body: some View {
VStack {
Text("불러오는 중...")
ActivityIndicator(isAnimating: .constant(true), style: .large)
}
.padding(28)
.background(Color.secondary.colorInvert())
.foregroundColor(Color.primary)
.cornerRadius(20)
.opacity(self.isShowing ? 1 : 0)
}
}
| 19.5 | 74 | 0.580586 |
e85674f98f7ea38825c7baa1380bcbb2af44d7c6
| 747 |
//
// SpecValidator.swift
//
//
// Created by Dmitry Demyanov on 29.11.2020.
//
import Swagger
class SpecValidator {
/// Checks if path does not include query parameters
/// https://swagger.io/docs/specification/paths-and-operations/#query-string-in-paths
func isPathValid(_ path: String) -> Bool {
return !path.contains("?")
}
/// Detect if parameters contain external reference
/// Swagger parser cannot handle external references
func findInvalidParameter(in parameters: [PossibleReference<Parameter>]) -> String? {
for parameter in parameters {
guard parameter.possibleValue != nil else {
return parameter.name
}
}
return nil
}
}
| 24.9 | 89 | 0.638554 |
ef7046db6cc9d975a55c04d009751e9d2ec4f32f
| 4,258 |
//
// CategoriesCoordinator.swift
// FoodViewer
//
// Created by arnaud on 08/02/2020.
// Copyright © 2020 Hovering Above. All rights reserved.
//
import UIKit
final class CategoriesCoordinator: Coordinator {
// MARK: - Public variables
var childCoordinator: Coordinator?
weak var parentCoordinator: Coordinator? = nil
var childCoordinators: [Coordinator] = []
var viewController: UIViewController? = nil
// MARK: - Private variables
weak private var productPair: ProductPair? = nil
private var coordinatorViewController: CategoriesTableViewController? {
self.viewController as? CategoriesTableViewController
}
// MARK: - Initialisation
init(with coordinator: Coordinator?) {
self.viewController = CategoriesTableViewController.instantiate()
self.coordinatorViewController?.coordinator = self
self.parentCoordinator = coordinator
}
init(with viewController:UIViewController) {
self.viewController = viewController
}
// MARK: - Child viewControllers
func show() {
// Done in the viewController?
}
/// Show the robotoff question viewcontroller
func showQuestion(for productPair: ProductPair?, question: RobotoffQuestion, image: ProductImageSize?) {
self.productPair = productPair
let coordinator = RobotoffQuestionCoordinator.init(with: self, question: question, image: image)
self.childCoordinators.append(coordinator)
coordinator.show()
}
func selectCategory(for productPair: ProductPair?) {
self.productPair = productPair
let coordinator = SelectPairCoordinator.init(with:self,
original: self.productPair?.categoriesInterpreted?.list,
allPairs: OFFplists.manager.allCategories,
multipleSelectionIsAllowed: true,
showOriginalsAsSelected: true,
tag: 0,
assignedHeader: TranslatableStrings.SelectedCategories,
unAssignedHeader: TranslatableStrings.UnselectedCategories,
undefinedText: TranslatableStrings.NoCategoryDefined)
childCoordinators.append(coordinator)
coordinator.show()
}
// MARK: - Lifecycle
/// The viewController informs its owner that it has disappeared
func viewControllerDidDisappear(_ sender: UIViewController) {
if self.childCoordinators.isEmpty {
self.viewController = nil
informParent()
}
}
/// A child coordinator informs its owner that it has disappeared
func canDisappear(_ coordinator: Coordinator) {
if let index = self.childCoordinators.lastIndex(where: ({ $0 === coordinator }) ) {
self.childCoordinators.remove(at: index)
informParent()
}
}
private func informParent() {
if self.childCoordinators.isEmpty
&& self.viewController == nil {
parentCoordinator?.canDisappear(self)
}
}
}
// MARK: - SelectPairCoordinatorProtocol
extension CategoriesCoordinator: SelectPairCoordinatorProtocol {
func selectPairViewController(_ sender:SelectPairViewController, selected strings: [String]?, tag: Int) {
if let validStrings = strings {
productPair?.update(categories: validStrings)
}
sender.dismiss(animated: true, completion: nil)
}
func selectPairViewControllerDidCancel(_ sender:SelectPairViewController) {
sender.dismiss(animated: true, completion: nil)
}
}
// MARK: - RobotoffQuestionCoordinatorProtocol
extension CategoriesCoordinator: RobotoffQuestionCoordinatorProtocol {
func robotoffQuestionTableViewController(_ sender: RobotoffQuestionViewController, answered question: RobotoffQuestion?) {
guard let validProductPair = productPair else { return }
guard let validQuestion = question else { return }
OFFProducts.manager.startRobotoffUpload(for: validQuestion, in: validProductPair)
sender.dismiss(animated: true, completion: nil)
}
}
| 33.793651 | 126 | 0.659699 |
f58abd58851a14fdd6885b2eb243e2835f33b50e
| 2,180 |
//
// AppDelegate.swift
// 015-AddingMachine
//
// Created by lichuanjun on 2017/6/4.
// Copyright © 2017年 lichuanjun. 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.382979 | 285 | 0.756422 |
bbe5e7321d36679d5c43747cb054730c5cf1cbff
| 1,588 |
/*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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
import RxSwift
protocol SceneCoordinatorType {
/// transition to another scene
@discardableResult
func transition(to scene: Scene, type: SceneTransitionType) -> Completable
/// pop scene from navigation stack or dismiss current modal
@discardableResult
func pop(animated: Bool) -> Completable
}
extension SceneCoordinatorType {
@discardableResult
func pop() -> Completable {
return pop(animated: true)
}
}
| 37.809524 | 80 | 0.745592 |
0a87fa6769335823f1fc3f0b2142ada1aa7a47e9
| 32,486 |
// RUN: %target-parse-verify-swift
//===----------------------------------------------------------------------===//
// Tests and samples.
//===----------------------------------------------------------------------===//
// Comment. With unicode characters: ¡ç®åz¥!
func markUsed<T>(t: T) {}
// Various function types.
var func1 : () -> () // No input, no output.
var func2 : (Int) -> Int
var func3 : () -> () -> () // Takes nothing, returns a fn.
var func3a : () -> (() -> ()) // same as func3
var func6 : (fn : (Int,Int) -> Int) -> () // Takes a fn, returns nothing.
var func7 : () -> (Int,Int,Int) // Takes nothing, returns tuple.
// Top-Level expressions. These are 'main' content.
func1()
4+7
var bind_test1 : () -> () = func1
var bind_test2 : Int = 4; func1 // expected-error {{expression resolves to an unused l-value}}
(func1, func2) // expected-error {{expression resolves to an unused l-value}}
func basictest() {
// Simple integer variables.
var x : Int
var x2 = 4 // Simple Type inference.
var x3 = 4+x*(4+x2)/97 // Basic Expressions.
// Declaring a variable Void, aka (), is fine too.
var v : Void
var x4 : Bool = true
var x5 : Bool =
4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}}
//var x6 : Float = 4+5
var x7 = 4; 5 // TODO: 5 should get a "unused expr" warning.
// Test implicit conversion of integer literal to non-Int64 type.
var x8 : Int8 = 4
x8 = x8 + 1
x8 + 1
0 + x8
1.0 + x8 // expected-error{{binary operator '+' cannot be applied to operands of type 'Double' and 'Int8'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var x9 : Int16 = x8 + 1 // expected-error{{cannot convert value of type 'Int8' to expected argument type 'Int16'}}
// Various tuple types.
var tuple1 : ()
var tuple2 : (Int)
var tuple3 : (Int, Int, ())
var tuple2a : (a : Int) // expected-error{{cannot create a single-element tuple with an element label}}{{18-22=}}
var tuple3a : (a : Int, b : Int, c : ())
var tuple4 = (1, 2) // Tuple literal.
var tuple5 = (1, 2, 3, 4) // Tuple literal.
var tuple6 = (1 2) // expected-error {{expected ',' separator}} {{18-18=,}}
// Brace expressions.
var brace3 = {
var brace2 = 42 // variable shadowing.
brace2+7
}
// Function calls.
var call1 : () = func1()
var call2 = func2(1)
var call3 : () = func3()()
// Cannot call an integer.
bind_test2() // expected-error {{cannot call value of non-function type 'Int'}}
}
// Infix operators and attribute lists.
infix operator %% {
associativity left
precedence 2
}
func %%(a: Int, b: Int) -> () {}
var infixtest : () = 4 % 2 + 27 %% 123
// The 'func' keyword gives a nice simplification for function definitions.
func funcdecl1(a: Int, _ y: Int) {}
func funcdecl2() {
return funcdecl1(4, 2)
}
func funcdecl3() -> Int {
return 12
}
func funcdecl4(a: ((Int) -> Int), b: Int) {}
func signal(sig: Int, f: (Int) -> Void) -> (Int) -> Void {}
// Doing fun things with named arguments. Basic stuff first.
func funcdecl6(a: Int, b: Int) -> Int { a+b }
// Can dive into tuples, 'b' is a reference to a whole tuple, c and d are
// fields in one. Cannot dive into functions or through aliases.
func funcdecl7(a: Int, b: (c: Int, d: Int), third: (c: Int, d: Int)) -> Int {
a + b.0 + b.c + third.0 + third.1
b.foo // expected-error {{value of tuple type '(c: Int, d: Int)' has no member 'foo'}}
}
// Error recovery.
func testfunc2 (_: ((), Int) -> Int) -> Int {}
func errorRecovery() {
testfunc2({ $0 + 1 }) // expected-error{{cannot convert value of type '((), Int)' to expected argument type 'Int'}}
enum union1 {
case bar
case baz
}
var a: Int = .hello // expected-error {{type 'Int' has no member 'hello'}}
var b: union1 = .bar // ok
var c: union1 = .xyz // expected-error {{type 'union1' has no member 'xyz'}}
var d: (Int,Int,Int) = (1,2) // expected-error {{cannot convert value of type '(Int, Int)' to specified type '(Int, Int, Int)'}}
var e: (Int,Int) = (1, 2, 3) // expected-error {{cannot convert value of type '(Int, Int, Int)' to specified type '(Int, Int)'}}
var f: (Int,Int) = (1, 2, f : 3) // expected-error {{cannot convert value of type '(Int, Int, f: Int)' to specified type '(Int, Int)'}}
// <rdar://problem/22426860> CrashTracer: [USER] swift at …mous_namespace::ConstraintGenerator::getTypeForPattern + 698
var (g1, g2, g3) = (1, 2) // expected-error {{'(Int, Int)' is not convertible to '(_, _, _)', tuples have a different number of elements}}
}
func acceptsInt(x: Int) {}
acceptsInt(unknown_var) // expected-error {{use of unresolved identifier 'unknown_var'}}
var test1a: (Int) -> (Int) -> Int = { { $0 } } // expected-error{{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{38-38= _ in}}
var test1b = { 42 }
var test1c = { { 42 } }
var test1d = { { { 42 } } }
func test2(a: Int, b: Int) -> (c: Int) { // expected-error{{cannot create a single-element tuple with an element label}} {{32-35=}}
a+b
a+b+c // expected-error{{use of unresolved identifier 'c'}}
return a+b
}
func test3(arg1: Int, arg2: Int) -> Int {
return 4
}
func test4() -> ((arg1: Int, arg2: Int) -> Int) {
return test3
}
func test5() {
let a: (Int, Int) = (1,2)
var
_: ((Int) -> Int, Int) = a // expected-error {{cannot convert value of type '(Int, Int)' to specified type '((Int) -> Int, Int)' (aka '(Int -> Int, Int)')}}
let c: (a: Int, b: Int) = (1,2)
let _: (b: Int, a: Int) = c // Ok, reshuffle tuple.
}
// Functions can obviously take and return values.
func w3(a: Int) -> Int { return a }
func w4(_: Int) -> Int { return 4 }
func b1() {}
func foo1(a: Int, b: Int) -> Int {}
func foo2(a: Int) -> (b: Int) -> Int {}
func foo3(a: Int = 2, b: Int = 3) {}
prefix operator ^^ {}
prefix func ^^(a: Int) -> Int {
return a + 1
}
func test_unary1() {
var x: Int
x = ^^(^^x)
x = *x // expected-error {{'*' is not a prefix unary operator}}
x = x* // expected-error {{'*' is not a postfix unary operator}}
x = +(-x)
x = + -x // expected-error {{unary operator cannot be separated from its operand}} {{8-9=}}
}
func test_unary2() {
var x: Int
// FIXME: second diagnostic is redundant.
x = &; // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}}
}
func test_unary3() {
var x: Int
// FIXME: second diagnostic is redundant.
x = &, // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}}
}
func test_as_1() {
var _: Int
}
func test_as_2() {
let x: Int = 1
x as [] // expected-error {{expected element type}}
}
func test_lambda() {
// A simple closure.
var a = { (value: Int) -> () in markUsed(value+1) }
// A recursive lambda.
// FIXME: This should definitely be accepted.
var fib = { (n: Int) -> Int in
if (n < 2) {
return n
}
return fib(n-1)+fib(n-2) // expected-error 2 {{variable used within its own initial value}}
}
}
func test_lambda2() {
{ () -> protocol<Int> in // expected-error {{non-protocol type 'Int' cannot be used within 'protocol<...>'}}
return 1
}()
}
func test_floating_point() {
_ = 0.0
_ = 100.1
var _: Float = 0.0
var _: Double = 0.0
}
func test_nonassoc(x: Int, y: Int) -> Bool {
// FIXME: the second error and note here should arguably disappear
return x == y == x // expected-error {{non-associative operator is adjacent to operator of same precedence}} expected-error {{binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '==' exist with these partially matching parameter lists:}}
}
// More realistic examples.
func fib(n: Int) -> Int {
if (n < 2) {
return n
}
return fib(n-2) + fib(n-1)
}
//===----------------------------------------------------------------------===//
// Integer Literals
//===----------------------------------------------------------------------===//
// FIXME: Should warn about integer constants being too large <rdar://problem/14070127>
var
il_a: Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}}
var il_b: Int8
= 123123
var il_c: Int8 = 4 // ok
struct int_test4 : IntegerLiteralConvertible {
typealias IntegerLiteralType = Int
init(integerLiteral value: Int) {} // user type.
}
var il_g: int_test4 = 4
// This just barely fits in Int64.
var il_i: Int64 = 18446744073709551615
// This constant is too large to fit in an Int64, but it is fine for Int128.
// FIXME: Should warn about the first. <rdar://problem/14070127>
var il_j: Int64 = 18446744073709551616
// var il_k: Int128 = 18446744073709551616
var bin_literal: Int64 = 0b100101
var hex_literal: Int64 = 0x100101
var oct_literal: Int64 = 0o100101
// verify that we're not using C rules
var oct_literal_test: Int64 = 0123
assert(oct_literal_test == 123)
// ensure that we swallow random invalid chars after the first invalid char
var invalid_num_literal: Int64 = 0QWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_bin_literal: Int64 = 0bQWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_hex_literal: Int64 = 0xQWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_oct_literal: Int64 = 0oQWERTY // expected-error{{expected a digit after integer literal prefix}}
var invalid_exp_literal: Double = 1.0e+QWERTY // expected-error{{expected a digit in floating point exponent}}
// rdar://11088443
var negative_int32: Int32 = -1
// <rdar://problem/11287167>
var tupleelemvar = 1
markUsed((tupleelemvar, tupleelemvar).1)
func int_literals() {
// Fits exactly in 64-bits - rdar://11297273
_ = 1239123123123123
// Overly large integer.
// FIXME: Should warn about it. <rdar://problem/14070127>
_ = 123912312312312312312
}
// <rdar://problem/12830375>
func tuple_of_rvalues(a:Int, b:Int) -> Int {
return (a, b).1
}
extension Int {
func testLexingMethodAfterIntLiteral() {}
func _0() {}
}
123.testLexingMethodAfterIntLiteral()
0b101.testLexingMethodAfterIntLiteral()
0o123.testLexingMethodAfterIntLiteral()
0x1FFF.testLexingMethodAfterIntLiteral()
123._0()
0b101._0()
0o123._0()
0x1FFF._0()
var separator1: Int = 1_
var separator2: Int = 1_000
var separator4: Int = 0b1111_0000_
var separator5: Int = 0b1111_0000
var separator6: Int = 0o127_777_
var separator7: Int = 0o127_777
var separator8: Int = 0x12FF_FFFF
var separator9: Int = 0x12FF_FFFF_
//===----------------------------------------------------------------------===//
// Float Literals
//===----------------------------------------------------------------------===//
var fl_a = 0.0
var fl_b: Double = 1.0
var fl_c: Float = 2.0
// FIXME: crummy diagnostic
var fl_d: Float = 2.0.0 // expected-error {{expected named member of numeric literal}}
var fl_e: Float = 1.0e42
var fl_f: Float = 1.0e+ // expected-error {{expected a digit in floating point exponent}}
var fl_g: Float = 1.0E+42
var fl_h: Float = 2e-42
var vl_i: Float = -.45 // expected-error {{'.45' is not a valid floating point literal; it must be written '0.45'}} {{20-20=0}}
var fl_j: Float = 0x1p0
var fl_k: Float = 0x1.0p0
var fl_l: Float = 0x1.0 // expected-error {{hexadecimal floating point literal must end with an exponent}}
var fl_m: Float = 0x1.FFFFFEP-2
var fl_n: Float = 0x1.fffffep+2
var fl_o: Float = 0x1.fffffep+ // expected-error {{expected a digit in floating point exponent}}
var if1: Double = 1.0 + 4 // integer literal ok as double.
var if2: Float = 1.0 + 4 // integer literal ok as float.
var fl_separator1: Double = 1_.2_
var fl_separator2: Double = 1_000.2_
var fl_separator3: Double = 1_000.200_001
var fl_separator4: Double = 1_000.200_001e1_
var fl_separator5: Double = 1_000.200_001e1_000
var fl_separator6: Double = 1_000.200_001e1_000
var fl_separator7: Double = 0x1_.0FFF_p1_
var fl_separator8: Double = 0x1_0000.0FFF_ABCDp10_001
var fl_bad_separator1: Double = 1e_ // expected-error {{expected a digit in floating point exponent}}
var fl_bad_separator2: Double = 0x1p_ // expected-error {{expected a digit in floating point exponent}} expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} expected-error {{consecutive statements on a line must be separated by ';'}} {{37-37=;}}
//===----------------------------------------------------------------------===//
// String Literals
//===----------------------------------------------------------------------===//
var st_a = ""
var st_b: String = ""
var st_c = "asdfasd // expected-error {{unterminated string literal}}
var st_d = " \t\n\r\"\'\\ " // Valid simple escapes
var st_e = " \u{12}\u{0012}\u{00000078} " // Valid unicode escapes
var st_u1 = " \u{1} "
var st_u2 = " \u{123} "
var st_u3 = " \u{1234567} " // expected-error {{invalid unicode scalar}}
var st_u4 = " \q " // expected-error {{invalid escape sequence in literal}}
var st_u5 = " \u{FFFFFFFF} " // expected-error {{invalid unicode scalar}}
var st_u6 = " \u{D7FF} \u{E000} " // Fencepost UTF-16 surrogate pairs.
var st_u7 = " \u{D800} " // expected-error {{invalid unicode scalar}}
var st_u8 = " \u{DFFF} " // expected-error {{invalid unicode scalar}}
var st_u10 = " \u{0010FFFD} " // Last valid codepoint, 0xFFFE and 0xFFFF are reserved in each plane
var st_u11 = " \u{00110000} " // expected-error {{invalid unicode scalar}}
func stringliterals(d: [String: Int]) {
// rdar://11385385
let x = 4
"Hello \(x+1) world"
"Error: \(x+1"; // expected-error {{unterminated string literal}}
"Error: \(x+1 // expected-error {{unterminated string literal}}
; // expected-error {{';' statements are not allowed}}
// rdar://14050788 [DF] String Interpolations can't contain quotes
"test \("nested")"
"test \("\("doubly nested")")"
"test \(d["hi"])"
"test \("quoted-paren )")"
"test \("quoted-paren (")"
"test \("\\")"
"test \("\n")"
"test \("\")" // expected-error {{unterminated string literal}}
"test \
// expected-error @-1 {{unterminated string literal}} expected-error @-1 {{invalid escape sequence in literal}}
"test \("\
// expected-error @-1 {{unterminated string literal}}
"test newline \("something" +
"something else")"
// expected-error @-2 {{unterminated string literal}} expected-error @-1 {{unterminated string literal}}
// FIXME: bad diagnostics.
// expected-warning @+1 {{initialization of variable 'x2' was never used; consider replacing with assignment to '_' or removing it}}
/* expected-error {{unterminated string literal}} expected-error {{expected ',' separator}} expected-error {{expected ',' separator}} expected-note {{to match this opening '('}} */ var x2 : () = ("hello" + "
; // expected-error {{expected expression in list of expressions}}
} // expected-error {{expected ')' in expression list}}
func testSingleQuoteStringLiterals() {
'abc' // expected-error{{single-quoted string literal found, use '"'}}{{3-8="abc"}}
_ = 'abc' + "def" // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}}
'ab\nc' // expected-error{{single-quoted string literal found, use '"'}}{{3-10="ab\\nc"}}
"abc\('def')" // expected-error{{single-quoted string literal found, use '"'}}{{9-14="def"}}
"abc' // expected-error{{unterminated string literal}}
'abc" // expected-error{{unterminated string literal}}
"a'c"
'ab\'c' // expected-error{{single-quoted string literal found, use '"'}}{{3-10="ab'c"}}
'ab"c' // expected-error{{single-quoted string literal found, use '"'}}{{3-9="ab\\"c"}}
'ab\"c' // expected-error{{single-quoted string literal found, use '"'}}{{3-10="ab\\"c"}}
'ab\\"c' // expected-error{{single-quoted string literal found, use '"'}}{{3-11="ab\\\\\\"c"}}
}
// <rdar://problem/17128913>
var s = ""
s.append(contentsOf: ["x"])
//===----------------------------------------------------------------------===//
// InOut arguments
//===----------------------------------------------------------------------===//
func takesInt(x: Int) {}
func takesExplicitInt(x: inout Int) { }
func testInOut(arg: inout Int) {
var x: Int
takesExplicitInt(x) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
takesExplicitInt(&x)
takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}}
var y = &x // expected-error{{'&' can only appear immediately in a call argument list}} \
// expected-error {{type 'inout Int' of variable is not materializable}}
var z = &arg // expected-error{{'&' can only appear immediately in a call argument list}} \
// expected-error {{type 'inout Int' of variable is not materializable}}
takesExplicitInt(5) // expected-error {{cannot pass immutable value as inout argument: literals are not mutable}}
}
//===----------------------------------------------------------------------===//
// Conversions
//===----------------------------------------------------------------------===//
var pi_f: Float
var pi_d: Double
struct SpecialPi {} // Type with no implicit construction.
var pi_s: SpecialPi
func getPi() -> Float {} // expected-note 3 {{found this candidate}}
func getPi() -> Double {} // expected-note 3 {{found this candidate}}
func getPi() -> SpecialPi {}
enum Empty { }
extension Empty {
init(_ f: Float) { }
}
func conversionTest(a: inout Double, b: inout Int) {
var f: Float
var d: Double
a = Double(b)
a = Double(f)
a = Double(d) // no-warning
b = Int(a)
f = Float(b)
var pi_f1 = Float(pi_f)
var pi_d1 = Double(pi_d)
var pi_s1 = SpecialPi(pi_s) // expected-error {{argument passed to call that takes no arguments}}
var pi_f2 = Float(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_d2 = Double(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_s2: SpecialPi = getPi() // no-warning
var float = Float.self
var pi_f3 = float.init(getPi()) // expected-error {{ambiguous use of 'getPi()'}}
var pi_f4 = float.init(pi_f)
var e = Empty(f)
var e2 = Empty(d) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Float'}}
var e3 = Empty(Float(d))
}
struct Rule {
var target: String
var dependencies: String
}
var ruleVar: Rule
ruleVar = Rule("a") // expected-error {{missing argument for parameter 'dependencies' in call}}
class C {
var x: C?
init(other: C?) { x = other }
func method() {}
}
_ = C(3) // expected-error {{missing argument label 'other:' in call}}
_ = C(other: 3) // expected-error {{cannot convert value of type 'Int' to expected argument type 'C?'}}
//===----------------------------------------------------------------------===//
// Unary Operators
//===----------------------------------------------------------------------===//
func unaryOps(i8: inout Int8, i64: inout Int64) {
i8 = ~i8
i64 += 1
i8 -= 1
Int64(5) += 1 // expected-error{{left side of mutating operator isn't mutable: function call returns immutable value}}
// <rdar://problem/17691565> attempt to modify a 'let' variable with ++ results in typecheck error not being able to apply ++ to Float
let a = i8 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
a += 1 // expected-error {{left side of mutating operator isn't mutable: 'a' is a 'let' constant}}
var b : Int { get { }}
b += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a get-only property}}
}
//===----------------------------------------------------------------------===//
// Iteration
//===----------------------------------------------------------------------===//
func..<(x: Double, y: Double) -> Double {
return x + y
}
func iterators() {
_ = 0..<42
_ = 0.0..<42.0
}
//===----------------------------------------------------------------------===//
// Magic literal expressions
//===----------------------------------------------------------------------===//
func magic_literals() {
_ = __FILE__ // expected-warning {{__FILE__ is deprecated and will be removed in Swift 3, please use #file}}
_ = __LINE__ // expected-warning {{__LINE__ is deprecated and will be removed in Swift 3, please use #line}}
_ = __COLUMN__ // expected-warning {{__COLUMN__ is deprecated and will be removed in Swift 3, please use #column}}
_ = __DSO_HANDLE__ // expected-warning {{__DSO_HANDLE__ is deprecated and will be removed in Swift 3, please use #dsohandle}}
_ = #file
_ = #line + #column
var _: UInt8 = #line + #column
}
//===----------------------------------------------------------------------===//
// lvalue processing
//===----------------------------------------------------------------------===//
infix operator +-+= {}
func +-+= (x: inout Int, y: Int) -> Int { return 0}
func lvalue_processing() {
var i = 0
i += 1 // obviously ok
var fn = (+-+=)
var n = 42
fn(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{6-6=&}}
fn(&n, 12)
n +-+= 12
(+-+=)(&n, 12) // ok.
(+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
}
struct Foo {
func method() {}
}
func test() {
var x = Foo()
// rdar://15708430
(&x).method() // expected-error {{'inout Foo' is not convertible to 'Foo'}}
}
// Unused results.
func unusedExpressionResults() {
// Unused l-value
_ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}}
// <rdar://problem/20749592> Conditional Optional binding hides compiler error
let optionalc:C? = nil
optionalc?.method() // ok
optionalc?.method // expected-error {{expression resolves to an unused function}}
}
//===----------------------------------------------------------------------===//
// Collection Literals
//===----------------------------------------------------------------------===//
func arrayLiterals() {
var a = [1,2,3]
var b : [Int] = []
var c = [] // expected-error {{cannot infer type for empty collection literal without a contextual type}}
}
func dictionaryLiterals() {
var a = [1 : "foo",2 : "bar",3 : "baz"]
var b : Dictionary<Int, String> = [:]
var c = [:] // expected-error {{cannot infer type for empty collection literal without a contextual type}}
}
func invalidDictionaryLiteral() {
// FIXME: lots of unnecessary diagnostics.
var a = [1: ; // expected-error {{expected value in dictionary literal}} expected-error 2{{expected ',' separator}} {{14-14=,}} {{14-14=,}} expected-error {{expected key expression in dictionary literal}} expected-error {{expected ']' in container literal expression}} expected-note {{to match this opening '['}}
var b = [1: ;] // expected-error {{expected value in dictionary literal}} expected-error 2{{expected ',' separator}} {{14-14=,}} {{14-14=,}} expected-error {{expected key expression in dictionary literal}}
var c = [1: "one" ;] // expected-error {{expected key expression in dictionary literal}} expected-error 2{{expected ',' separator}} {{20-20=,}} {{20-20=,}}
var d = [1: "one", ;] // expected-error {{expected key expression in dictionary literal}} expected-error {{expected ',' separator}} {{21-21=,}}
var e = [1: "one", 2] // expected-error {{expected ':' in dictionary literal}}
var f = [1: "one", 2 ;] // expected-error 2{{expected ',' separator}} {{23-23=,}} {{23-23=,}} expected-error 1{{expected key expression in dictionary literal}} expected-error {{expected ':' in dictionary literal}}
var g = [1: "one", 2: ;] // expected-error {{expected value in dictionary literal}} expected-error 2{{expected ',' separator}} {{24-24=,}} {{24-24=,}} expected-error {{expected key expression in dictionary literal}}
}
// FIXME: The issue here is a type compatibility problem, there is no ambiguity.
[4].joined(separator: [1]) // expected-error {{type of expression is ambiguous without more context}}
[4].joined(separator: [[[1]]]) // expected-error {{type of expression is ambiguous without more context}}
//===----------------------------------------------------------------------===//
// nil/metatype comparisons
//===----------------------------------------------------------------------===//
Int.self == nil // expected-error {{value of type 'Int.Type' can never be nil, comparison isn't allowed}}
nil == Int.self // expected-error {{binary operator '==' cannot be applied to operands}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists}}
Int.self != nil // expected-error {{value of type 'Int.Type' can never be nil, comparison isn't allowed}}
nil != Int.self // expected-error {{binary operator '!=' cannot be applied to operands}}
// expected-note @-1 {{overloads for '!=' exist with these partially matching parameter lists}}
// <rdar://problem/19032294> Disallow postfix ? when not chaining
func testOptionalChaining(a : Int?, b : Int!, c : Int??) {
a? // expected-error {{optional chain has no effect, expression already produces 'Int?'}} {{4-5=}}
a?.customMirror
b? // expected-error {{'?' must be followed by a call, member lookup, or subscript}}
b?.customMirror
var _: Int? = c? // expected-error {{'?' must be followed by a call, member lookup, or subscript}}
}
// <rdar://problem/19657458> Nil Coalescing operator (??) should have a higher precedence
func testNilCoalescePrecedence(cond: Bool, a: Int?, r: Range<Int>?) {
// ?? should have higher precedence than logical operators like || and comparisons.
if cond || (a ?? 42 > 0) {} // Ok.
if (cond || a) ?? 42 > 0 {} // Not ok: expected-error {{cannot be used as a boolean}} {{6-6=(}} {{17-17= != nil)}}
if (cond || a) ?? (42 > 0) {} // Not ok: expected-error {{cannot be used as a boolean}} {{6-6=((}} {{29-29=) != nil)}}
if cond || a ?? 42 > 0 {} // Parses as the first one, not the others.
// ?? should have lower precedence than range and arithmetic operators.
let r1 = r ?? (0...42) // ok
let r2 = (r ?? 0)...42 // not ok: expected-error {{binary operator '??' cannot be applied to operands of type 'Range<Int>?' and 'Int'}}
// expected-note @-1 {{overloads for '??' exist with these partially matching parameter lists:}}
let r3 = r ?? 0...42 // parses as the first one, not the second.
}
// <rdar://problem/19772570> Parsing of as and ?? regressed
func testOptionalTypeParsing(a : AnyObject) -> String {
return a as? String ?? "default name string here"
}
func testParenExprInTheWay() {
let x = 42
if x & 4.0 {} // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
if (x & 4.0) {} // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
if !(x & 4.0) {} // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
if x & x {} // expected-error {{type 'Int' does not conform to protocol 'Boolean'}}
}
// <rdar://problem/21352576> Mixed method/property overload groups can cause a crash during constraint optimization
public struct TestPropMethodOverloadGroup {
public typealias Hello = String
public let apply:(Hello) -> Int
public func apply(input:Hello) -> Int {
return apply(input)
}
}
// <rdar://problem/18496742> Passing ternary operator expression as inout crashes Swift compiler
func inoutTests(arr: inout Int) {
var x = 1, y = 2
(true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}}
let a = (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}}
// expected-error @-1 {{type 'inout Int' of variable is not materializable}}
inoutTests(true ? &x : &y); // expected-error 2 {{'&' can only appear immediately in a call argument list}}
&_ // expected-error {{expression type 'inout _' is ambiguous without more context}}
inoutTests((&x)) // expected-error {{'&' can only appear immediately in a call argument list}}
inoutTests(&x)
// <rdar://problem/17489894> inout not rejected as operand to assignment operator
&x += y // expected-error {{'&' can only appear immediately in a call argument list}}
// <rdar://problem/23249098>
func takeAny(x: Any) {}
takeAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
func takeManyAny(x: Any...) {}
takeManyAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any' (aka 'protocol<>')}}
takeManyAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
func takeIntAndAny(x: Int, _ y: Any) {}
takeIntAndAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}}
}
// <rdar://problem/20802757> Compiler crash in default argument & inout expr
var g20802757 = 2
func r20802757(z: inout Int = &g20802757) { // expected-error {{'&' can only appear immediately in a call argument list}}
print(z)
}
_ = _.foo // expected-error {{type of expression is ambiguous without more context}}
// <rdar://problem/22211854> wrong arg list crashing sourcekit
func r22211854() {
func f(x: Int, _ y: Int, _ z: String = "") {}
func g<T>(x: T, _ y: T, _ z: String = "") {}
f(1) // expected-error{{missing argument for parameter #2 in call}}
g(1) // expected-error{{missing argument for parameter #2 in call}}
func h() -> Int { return 1 }
f(h() == 1) // expected-error{{missing argument for parameter #2 in call}}
g(h() == 1) // expected-error{{missing argument for parameter #2 in call}}
}
// <rdar://problem/22348394> Compiler crash on invoking function with labeled defaulted param with non-labeled argument
func r22348394() {
func f(x x: Int = 0) { }
f(Int(3)) // expected-error{{missing argument label 'x:' in call}}
}
// <rdar://problem/23185177> Compiler crashes in Assertion failed: ((AllowOverwrite || !E->hasLValueAccessKind()) && "l-value access kind has already been set"), function visit
protocol P { var y: String? { get } }
func r23185177(x: P?) -> [String] {
return x?.y // expected-error{{cannot convert return expression of type 'String?' to return type '[String]'}}
}
// <rdar://problem/22913570> Miscompile: wrong argument parsing when calling a function in swift2.0
func r22913570() {
func f(from: Int = 0, to: Int) {}
f(1 + 1) // expected-error{{missing argument for parameter 'to' in call}}
}
// <rdar://problem/23708702> Emit deprecation warnings for ++/-- in Swift 2.2
func swift22_deprecation_increment_decrement() {
var i = 0
var f = 1.0
var si = "foo".startIndex
i++ // expected-warning {{'++' is deprecated: it will be removed in Swift 3}} {{4-6= += 1}}
--i // expected-warning {{'--' is deprecated: it will be removed in Swift 3}} {{3-5=}} {{6-6= -= 1}}
_ = i++ // expected-warning {{'++' is deprecated: it will be removed in Swift 3}}
++f // expected-warning {{'++' is deprecated: it will be removed in Swift 3}} {{3-5=}} {{6-6= += 1}}
f-- // expected-warning {{'--' is deprecated: it will be removed in Swift 3}} {{4-6= -= 1}}
_ = f-- // expected-warning {{'--' is deprecated: it will be removed in Swift 3}} {{none}}
++si // expected-warning {{'++' is deprecated: it will be removed in Swift 3}} {{3-5=}} {{7-7= = si.successor()}}
--si // expected-warning {{'--' is deprecated: it will be removed in Swift 3}} {{3-5=}} {{7-7= = si.predecessor()}}
si++ // expected-warning {{'++' is deprecated: it will be removed in Swift 3}} {{5-7= = si.successor()}}
si-- // expected-warning {{'--' is deprecated: it will be removed in Swift 3}} {{5-7= = si.predecessor()}}
_ = --si // expected-warning {{'--' is deprecated: it will be removed in Swift 3}} {{none}}
// <rdar://problem/24530312> Swift ++fix-it produces bad code in nested expressions
// This should not get a fixit hint.
var j = 2
i = ++j // expected-warning {{'++' is deprecated: it will be removed in Swift 3}} {{none}}
}
// SR-628 mixing lvalues and rvalues in tuple expression
var x = 0
var y = 1
let _ = (x, x.successor()).0
let _ = (x, 3).1
(x,y) = (2,3)
(x,4) = (1,2) // expected-error {{cannot assign to value: literals are not mutable}}
(x,y).1 = 7 // expected-error {{cannot assign to immutable expression of type 'Int'}}
x = (x,(3,y)).1.1
| 38.084408 | 314 | 0.612879 |
672faf5e93fa4cf91648f37d0521cb4902bffa6c
| 306 |
//
// SSProfile.swift
// SS_Authentication
//
// Created by Eddie Li on 25/05/16.
// Copyright © 2016 Software and Support Media GmbH. All rights reserved.
//
import Foundation
import SwiftyJSON
open class SSProfile: NSObject {
open var profileId: String = ""
open var courses: [JSON] = []
}
| 19.125 | 74 | 0.686275 |
ff3d8328806105be7b3ccc32be653784282c6c16
| 817 |
//
// Created by Alexander Ubillus on 3/30/20.
//
import Foundation
public final class AtomicInteger {
private let lock = DispatchSemaphore(value: 1)
private var _value: Int
public init(value initialValue: Int = 0) {
_value = initialValue
}
public var value: Int {
get {
lock.wait()
defer { lock.signal() }
return _value
}
set {
lock.wait()
defer { lock.signal() }
_value = newValue
}
}
public func decrementAndGet() -> Int {
lock.wait()
defer { lock.signal() }
_value -= 1
return _value
}
public func incrementAndGet() -> Int {
lock.wait()
defer { lock.signal() }
_value += 1
return _value
}
}
| 19.452381 | 50 | 0.510404 |
291ba94da17cbd1a2b835d2fab8bf2dd2afac651
| 1,554 |
//
// RRHTTPStatusCodeEnum.swift
// Dog
//
// Created by Rahul Mayani on 14/04/21.
//
import Foundation
import UIKit
enum RRHTTPStatusCode: Int {
//1xx Informationals
case `continue` = 100
case switchingProtocols = 101
//2xx Successfuls
case ok = 200
case created = 201
case accepted = 202
case nonAuthoritativeInformation = 203
case noContent = 204
case resetContent = 205
case partialContent = 206
//3xx Redirections
case multipleChoices = 300
case movedPermanently = 301
case found = 302
case seeOther = 303
case notModified = 304
case useProxy = 305
case unused = 306
case temporaryRedirect = 307
//4xx Client Errors
case badRequest = 400
case unauthorized = 401
case paymentRequired = 402
case forbidden = 403
case notFound = 404
case methodNotAllowed = 405
case notAcceptable = 406
case proxyAuthenticationRequired = 407
case requestTimeout = 408
case conflict = 409
case gone = 410
case lengthRequired = 411
case preconditionFailed = 412
case requestEntityTooLarge = 413
case requestURITooLong = 414
case unsupportedMediaType = 415
case requestedRangeNotSatisfiable = 416
case expectationFailed = 417
//5xx Server Errors
case internalServerError = 500
case notImplemented = 501
case badGateway = 502
case serviceUnavailable = 503
case gatewayTimeout = 504
case httpVersionNotSupported = 505
//10xx Internet Error
case noInternetConnection = -1009
}
| 25.064516 | 43 | 0.69112 |
c15a5795598d4fab7fec98a317f9909e1daff480
| 907 |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm 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.
//
////////////////////////////////////////////////////////////////////////////
import SwiftUI
import RealmSwift
@main
struct App: SwiftUI.App {
var body: some Scene {
return WindowGroup {
MainView()
}
}
}
| 30.233333 | 76 | 0.584344 |
ef8d29ec7e079417c84ff4cd9fc53472fb9db40e
| 3,130 |
//
// ViewController.swift
// WikiLocation
//
// Created by Christian Menschel on 27.06.14.
// Copyright (c) 2014 enterprise. All rights reserved.
//
import UIKit
import GeoManager
import WikiManager
let kSegueIdentifier = "ShowWebDetails"
let kCellID = "WikiTableViewCellID"
class ViewController: UITableViewController {
//MARK: - Properties
let geoManager = GeoManager.sharedInstance
var dataSource = [WikiArticle]()
//MARK: - Init & deinit
deinit {
geoManager.removeObserver(self, forKeyPath: "location")
}
//MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
geoManager.addObserver(self, forKeyPath: "location", options: .New, context: nil)
GeoManager.sharedInstance.start()
}
func loadWikisNearBy() {
if let location = GeoManager.sharedInstance.location {
WikiManager.sharedInstance.downloadWikis(
latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
completion: {(articles:[WikiArticle]) in
self.dataSource = articles
self.tableView.reloadData()
})
}
}
//MARK: - TableView
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kCellID) as UITableViewCell
if let article = self.dataSource[indexPath.row] as WikiArticle? {
cell.textLabel.text = article.title
cell.detailTextLabel?.text = article.distance
}
return cell
}
let kSegueIdentifier = "ShowWebDetails"
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
super.prepareForSegue(segue, sender: sender)
if segue.identifier == kSegueIdentifier {
let indexPath = self.tableView.indexPathForSelectedRow();
if let article = self.dataSource[indexPath!.row] as WikiArticle? {
let webViewController:DetailViewController = segue.destinationViewController as DetailViewController
webViewController.url = article.url
}
}
}
//MARK: - Memory
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - KVO
override func observeValueForKeyPath(keyPath: String,
ofObject object: AnyObject,
change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) {
if object === geoManager && keyPath == "location" {
self.loadWikisNearBy()
}
}
}
| 30.686275 | 118 | 0.622364 |
f4e5c1cf90ca63af627deea813f603675b691f74
| 265 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return ( ) {
enum b {
struct A {
let c {
if true {
func c {
protocol A {
class d {
class
case ,
| 17.666667 | 87 | 0.709434 |
4609b78d3d9e3d2d8e88c3a04b584780f8a79065
| 1,468 |
//: Playground - noun: a place where people can play
import UIKit
import CoreGraphics
var str = "Hello, playground"
func drawARect() -> UIView {
let view: UIView = UIView(frame: CGRectMake(0.0, 0.0, 100.0, 200.0))
view.backgroundColor = UIColor.yellowColor()
let interiorView: UIView = UIView(frame: CGRectInset(view.frame, 10.0, 10.0))
interiorView.backgroundColor = UIColor.redColor()
view.addSubview(interiorView)
let bezier: UIBezierPath = getSomeCurves()
let mask: CAShapeLayer = makeTheMask(forPath: bezier)
// interiorView.layer.addSublayer(mask)
return view
}
func getSomeCurves() -> UIBezierPath {
let transparentFrame: CGRect = CGRectMake(5.0, 5.0, 20.0, 50.0)
let maskLayerPathBase: UIBezierPath = UIBezierPath(roundedRect: transparentFrame, cornerRadius: 5.0)
let maskLayerPathDefined: UIBezierPath = UIBezierPath(roundedRect: CGRectInset(transparentFrame, 4.0, 4.0), cornerRadius: 4.0)
maskLayerPathBase.appendPath(maskLayerPathDefined)
return maskLayerPathBase
}
func makeTheMask(forPath path: UIBezierPath) -> CAShapeLayer {
let transparentFrameLocation = path.bounds
let maskLayer: CAShapeLayer = CAShapeLayer()
maskLayer.bounds = transparentFrameLocation
maskLayer.frame = transparentFrameLocation
maskLayer.path = path.CGPath
maskLayer.backgroundColor = UIColor.whiteColor().CGColor
maskLayer.fillRule = kCAFillRuleEvenOdd
return maskLayer
}
let rects: UIView = drawARect()
| 28.784314 | 128 | 0.756812 |
d5fed881d7c1e23deafc267bd3a43403ea57554e
| 927 |
//
// PasswordValidator.swift
// LoginSignupModule
//
import Foundation
class PasswordValidator {
func validate(_ value: String) -> Bool {
if ((value.count < 6) || (value.count > 10)) {
return false
}
let whitespace = Set(" ")
if (value.filter {whitespace.contains($0)}).count > 0 {
return false
}
let uppercaseAlphabets = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
if (value.filter {uppercaseAlphabets.contains($0)}).count == 0 {
return false
}
let lowercaseAlphabets = Set("abcdefghijklmnopqrstuvwxyz")
if (value.filter {lowercaseAlphabets.contains($0)}).count == 0 {
return false
}
let numbers = Set("0123456789")
if (value.filter {numbers.contains($0)}).count == 0 {
return false
}
return true
}
}
| 24.394737 | 72 | 0.538296 |
e0e0df7a8ec22161724e88952d4e0e6b3d50b354
| 11,692 |
//
// SearchParameters.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct SearchParameters: Codable {
/** The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. */
public var q: String
/** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */
public var queryBy: String
/** The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. */
public var queryByWeights: String?
/** Maximum number of hits returned. Increasing this value might increase search latency. Default: 500. Use `all` to return all hits found. */
public var maxHits: String?
/** Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. */
public var _prefix: String?
/** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */
public var filterBy: String?
/** A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` */
public var sortBy: String?
/** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */
public var facetBy: String?
/** Maximum number of facet values to be returned. */
public var maxFacetValues: Int?
/** Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". */
public var facetQuery: String?
/** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */
public var numTypos: Int?
/** Results from this specific page number would be fetched. */
public var page: Int?
/** Number of results to fetch per page. Default: 10 */
public var perPage: Int?
/** You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. */
public var groupBy: String?
/** Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 */
public var groupLimit: Int?
/** List of fields from the document to include in the search result */
public var includeFields: String?
/** List of fields from the document to exclude in the search result */
public var excludeFields: String?
/** List of fields which should be highlighted fully without snippeting */
public var highlightFullFields: String?
/** The number of tokens that should surround the highlighted text on each side. Default: 4 */
public var highlightAffixNumTokens: Int?
/** The start tag used for the highlighted snippets. Default: `<mark>` */
public var highlightStartTag: String?
/** The end tag used for the highlighted snippets. Default: `</mark>` */
public var highlightEndTag: String?
/** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */
public var snippetThreshold: Int?
/** If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 */
public var dropTokensThreshold: Int?
/** If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 */
public var typoTokensThreshold: Int?
/** A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. */
public var pinnedHits: String?
/** A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. */
public var hiddenHits: String?
/** A list of custom fields that must be highlighted even if you don't query for them */
public var highlightFields: String?
/** You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to tre to do the same */
public var preSegmentedQuery: Bool?
/** If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false */
public var enableOverrides: Bool?
/** Set this parameter to true to ensure that an exact match is ranked above the others */
public var prioritizeExactMatch: Bool?
/** Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). */
public var exhaustiveSearch: Bool?
/** Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. */
public var searchCutoffMs: Int?
/** Enable server side caching of search query results. By default, caching is disabled. */
public var useCache: Bool?
/** The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. */
public var cacheTtl: Int?
/** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */
public var minLen1typo: Int?
/** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */
public var minLen2typo: Int?
public init(q: String, queryBy: String, queryByWeights: String? = nil, maxHits: String? = nil, _prefix: String? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: Int? = nil, page: Int? = nil, perPage: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, typoTokensThreshold: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = nil, enableOverrides: Bool? = nil, prioritizeExactMatch: Bool? = nil, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil) {
self.q = q
self.queryBy = queryBy
self.queryByWeights = queryByWeights
self.maxHits = maxHits
self._prefix = _prefix
self.filterBy = filterBy
self.sortBy = sortBy
self.facetBy = facetBy
self.maxFacetValues = maxFacetValues
self.facetQuery = facetQuery
self.numTypos = numTypos
self.page = page
self.perPage = perPage
self.groupBy = groupBy
self.groupLimit = groupLimit
self.includeFields = includeFields
self.excludeFields = excludeFields
self.highlightFullFields = highlightFullFields
self.highlightAffixNumTokens = highlightAffixNumTokens
self.highlightStartTag = highlightStartTag
self.highlightEndTag = highlightEndTag
self.snippetThreshold = snippetThreshold
self.dropTokensThreshold = dropTokensThreshold
self.typoTokensThreshold = typoTokensThreshold
self.pinnedHits = pinnedHits
self.hiddenHits = hiddenHits
self.highlightFields = highlightFields
self.preSegmentedQuery = preSegmentedQuery
self.enableOverrides = enableOverrides
self.prioritizeExactMatch = prioritizeExactMatch
self.exhaustiveSearch = exhaustiveSearch
self.searchCutoffMs = searchCutoffMs
self.useCache = useCache
self.cacheTtl = cacheTtl
self.minLen1typo = minLen1typo
self.minLen2typo = minLen2typo
}
public enum CodingKeys: String, CodingKey {
case q
case queryBy = "query_by"
case queryByWeights = "query_by_weights"
case maxHits = "max_hits"
case _prefix = "prefix"
case filterBy = "filter_by"
case sortBy = "sort_by"
case facetBy = "facet_by"
case maxFacetValues = "max_facet_values"
case facetQuery = "facet_query"
case numTypos = "num_typos"
case page
case perPage = "per_page"
case groupBy = "group_by"
case groupLimit = "group_limit"
case includeFields = "include_fields"
case excludeFields = "exclude_fields"
case highlightFullFields = "highlight_full_fields"
case highlightAffixNumTokens = "highlight_affix_num_tokens"
case highlightStartTag = "highlight_start_tag"
case highlightEndTag = "highlight_end_tag"
case snippetThreshold = "snippet_threshold"
case dropTokensThreshold = "drop_tokens_threshold"
case typoTokensThreshold = "typo_tokens_threshold"
case pinnedHits = "pinned_hits"
case hiddenHits = "hidden_hits"
case highlightFields = "highlight_fields"
case preSegmentedQuery = "pre_segmented_query"
case enableOverrides = "enable_overrides"
case prioritizeExactMatch = "prioritize_exact_match"
case exhaustiveSearch = "exhaustive_search"
case searchCutoffMs = "search_cutoff_ms"
case useCache = "use_cache"
case cacheTtl = "cache_ttl"
case minLen1typo = "min_len_1typo"
case minLen2typo = "min_len_2typo"
}
}
| 70.433735 | 992 | 0.715361 |
469030f9b56521cdba4390255ef32f3c53bbab9f
| 1,995 |
//
// Created by entaoyang on 2019-02-19.
// Copyright (c) 2019 yet.net. All rights reserved.
//
import Foundation
import UIKit
//let at = AttrText(item.body).lineSpace(8).font(Fonts.regular(16)).foreColor(Theme.Text.primaryColor).indent(32).value
//lb.attributedText = at
public class AttrText {
private var dic: [NSAttributedString.Key: Any] = [NSAttributedString.Key: Any]()
private var p: NSMutableParagraphStyle? = nil
private var ps: NSMutableParagraphStyle {
if p == nil {
p = NSMutableParagraphStyle()
}
return p!
}
private let text: String
public init(_ text: String) {
self.text = text
}
}
public extension AttrText {
var value: NSAttributedString {
return NSAttributedString(string: self.text, attributes: self.dic)
}
func lineBreakMode(_ n: NSLineBreakMode) -> AttrText {
self.ps.lineBreakMode = n
self.dic[.paragraphStyle] = self.ps
return self
}
func alignment(_ n: NSTextAlignment) -> AttrText {
self.ps.alignment = n
self.dic[.paragraphStyle] = self.ps
return self
}
func paragraphSpacing(_ n: CGFloat) -> AttrText {
self.ps.paragraphSpacing = n
self.dic[.paragraphStyle] = self.ps
return self
}
func lineSpace(_ n: CGFloat) -> AttrText {
self.ps.lineSpacing = n
self.dic[.paragraphStyle] = self.ps
return self
}
func indent(_ n: CGFloat) -> AttrText {
self.ps.firstLineHeadIndent = n
self.dic[.paragraphStyle] = self.ps
return self
}
func foreColor(_ c: UIColor) -> AttrText {
self.dic[.foregroundColor] = c
return self
}
func backColor(_ c: UIColor) -> AttrText {
self.dic[.backgroundColor] = c
return self
}
func underlineStyle(_ b: NSUnderlineStyle) -> AttrText {
self.dic[.underlineStyle] = b.rawValue
return self
}
func underlineColor(_ c: UIColor) -> AttrText {
self.dic[.underlineColor] = c
return self
}
func shadow(_ c: NSShadow) -> AttrText {
self.dic[.shadow] = c
return self
}
func font(_ c: UIFont) -> AttrText {
self.dic[.font] = c
return self
}
}
| 21 | 119 | 0.694236 |
766a93d736a0c2da066a15411bbcfb1063b5d008
| 2,996 |
import When
import YandexCheckoutPaymentsApi
enum PaymentProcessingError: PresentableError {
case emptyList
case internetConnection
var title: String? {
return nil
}
var message: String {
switch self {
case .emptyList:
return §Localized.Error.emptyPaymentMethods
case .internetConnection:
return §Localized.Error.internetConnection
}
}
var style: PresentableNotificationStyle {
return .alert
}
var actions: [PresentableNotificationAction] {
return []
}
}
protocol PaymentProcessing {
func fetchPaymentOptions(clientApplicationKey: String,
passportToken: String?,
gatewayId: String?,
amount: String?,
currency: String?) -> Promise<[PaymentOption]>
func fetchPaymentMethod(
clientApplicationKey: String,
paymentMethodId: String
) -> Promise<YandexCheckoutPaymentsApi.PaymentMethod>
func tokenizeBankCard(clientApplicationKey: String,
bankCard: BankCard,
confirmation: Confirmation,
amount: MonetaryAmount?,
tmxSessionId: String) -> Promise<Tokens>
func tokenizeWallet(clientApplicationKey: String,
yamoneyToken: String,
confirmation: Confirmation,
amount: MonetaryAmount?,
tmxSessionId: String) -> Promise<Tokens>
func tokenizeLinkedBankCard(clientApplicationKey: String,
yamoneyToken: String,
cardId: String,
csc: String,
confirmation: Confirmation,
amount: MonetaryAmount?,
tmxSessionId: String) -> Promise<Tokens>
func tokenizeSberbank(clientApplicationKey: String,
phoneNumber: String,
confirmation: Confirmation,
amount: MonetaryAmount?,
tmxSessionId: String) -> Promise<Tokens>
func tokenizeApplePay(clientApplicationKey: String,
paymentData: String,
amount: MonetaryAmount?,
tmxSessionId: String) -> Promise<Tokens>
func tokenizeRepeatBankCard(
clientApplicationKey: String,
amount: MonetaryAmount,
tmxSessionId: String,
confirmation: Confirmation,
paymentMethodId: String,
csc: String
) -> Promise<Tokens>
}
// MARK: - Localized
private extension PaymentProcessingError {
enum Localized {
enum Error: String {
case emptyPaymentMethods = "Error.emptyPaymentOptions"
case internetConnection = "Error.internet"
}
}
}
| 32.565217 | 75 | 0.550401 |
cc716a1e2dfd25cedaefd4c89305f3840593b626
| 109 |
import LiswTests
import XCTest
var tests = [XCTestCaseEntry]()
tests += LiswTests.allTests()
XCTMain(tests)
| 15.571429 | 31 | 0.770642 |
75849a16589c3aacefad9dffd0a8148340b07b3d
| 4,034 |
// Copyright 2019 rideOS, 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.
//
import Auth0
import RideOsApi
import RxSwift
public class User {
public static let scopes = "email offline_access openid profile"
public static let currentUser = User()
weak var delegate: UserDelegate?
private let credentialsManager: CredentialsManager
private var cachedProfile: Profile?
public var profile: Profile? {
return cachedProfile
}
init(credentialsManager: CredentialsManager = CredentialsManager(authentication: Auth0.authentication()),
configuration: Configuration = Configuration.sharedConfiguration) {
self.credentialsManager = credentialsManager
configuration.setTokenProvider(getAccessToken)
}
public func getAccessToken(_ callback: @escaping (String?) -> Void) {
credentialsManager.credentials(withScope: User.scopes) { error, credentials in
guard error == nil, let accessToken = credentials?.accessToken else {
// There's an issue with the credentials, force the user to log in again
print("User: Could not get credentials \(error!.localizedDescription)")
self.delegate?.credentials(areInvalid: self)
callback(nil)
return
}
callback(accessToken)
}
}
public func fetchProfile(callback: ((Profile?) -> Void)?) {
getAccessToken { accessToken in
guard let accessToken = accessToken else {
print("User: Could not fetch user info, not logged in")
callback?(nil)
return
}
Auth0.authentication()
.userInfo(token: accessToken)
.start { result in
switch result {
case let .success(profile):
self.cachedProfile = profile
callback?(profile)
case let .failure(error):
logError("User: Could not fetch user info (\(error.localizedDescription))")
callback?(nil)
}
}
}
}
public var profileObservable: Observable<Profile> {
return Observable.create { observer in
self.getAccessToken { accessToken in
guard let accessToken = accessToken else {
observer.onError(FetchAccessTokenError.noAccessToken)
return
}
Auth0.authentication()
.userInfo(token: accessToken)
.start { result in
switch result {
case let .success(profile):
observer.onNext(profile)
case let .failure(error):
observer.onError(error)
}
}
}
return Disposables.create()
}
}
public func hasCredentials() -> Bool {
return credentialsManager.hasValid()
}
public func updateCredentials(_ credentials: Credentials) -> Bool {
return credentialsManager.store(credentials: credentials)
}
public func clearCredentials() -> Bool {
return credentialsManager.clear()
}
}
protocol UserDelegate: NSObjectProtocol {
func credentials(areInvalid user: User)
}
public enum FetchAccessTokenError: Error {
case noAccessToken
}
| 34.186441 | 109 | 0.593704 |
7adbafcb7f2ca3a1e28bcb35f0d32145b8cb79e3
| 1,264 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t/Test.swiftmodule -emit-interface-path %t/Test.swiftinterface -module-name Test %s
// RUN: %FileCheck %s < %t/Test.swiftinterface
// RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/Test.swiftmodule -disable-objc-attr-requires-foundation-module -emit-interface-path - -module-name Test | %FileCheck %s
// CHECK: final public class FinalClass {
public final class FinalClass {
// CHECK: @inlinable final public class var a: [[INT:(Swift.)?Int]] {
// CHECK-NEXT: {{^}} get {
// CHECK-NEXT: return 3
// CHECK-NEXT: }
// CHECK-NEXT: }
@inlinable
public final class var a: Int {
return 3
}
// CHECK: final public class var b: [[INT]] {
// CHECK-NEXT: {{^}} @inlinable get {
// CHECK-NEXT: return 3
// CHECK-NEXT: }
// CHECK-NEXT: set[[NEWVALUE:(\(newValue\))?]]{{$}}
// CHECK-NEXT: }
public final class var b: Int {
@inlinable get {
return 3
}
set {
print("x")
}
}
// CHECK: public static var c: [[INT]] {
// CHECK-NEXT: {{^}} get
// CHECK-NEXT: @inlinable set[[NEWVALUE]] {}
// CHECK-NEXT: }
public static var c: Int {
get {
return 0
}
@inlinable set {}
}
}
| 28.727273 | 194 | 0.602848 |
3aca7d839c6f8c812973af5fadd602069e074237
| 523 |
//
// User+CoreDataProperties.swift
// eComerceApp
//
// Created by Oswaldo Morales on 6/28/20.
// Copyright © 2020 Oswaldo Morales. All rights reserved.
//
import Foundation
import CoreData
extension User {
@nonobjc public class func fetchRequest() -> NSFetchRequest<User> {
return NSFetchRequest<User>(entityName: "User")
}
@NSManaged public var user: String?
@NSManaged public var birthdate: String?
@NSManaged public var password: String?
@NSManaged public var avatar: Data?
}
| 20.92 | 71 | 0.699809 |
fcfc6c0b18f99065c046dcf3321aa7ff011e6d24
| 910 |
//
// PiggyKitTests.swift
// PiggyKitTests
//
// Created by Casey Langen on 6/26/19.
// Copyright © 2019 NerdWallet, Inc. All rights reserved.
//
import XCTest
@testable import PiggyKit
class PiggyKitTests: 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.
}
}
}
| 26 | 111 | 0.654945 |
b9f881fb664b88c0f5ba494521c4e708fc8910f2
| 1,042 |
//
// UINavigationBarComponent.swift
// ThenGeneratorApp
//
// Created by Kanz on 2021/01/14.
//
import SwiftUI
struct UINavigationBarComponent: View {
@EnvironmentObject private var homeState: HomeViewModel
var body: some View {
VStack {
Text("UINavigationBar")
.foregroundColor(.primary)
.font(.largeTitle)
.padding(.top, 20.0)
ScrollView {
VStack(alignment: .leading, spacing: 10.0) {
// delegate
SwitchView(value: $homeState.navigationBarModel.delegate, title: "delegate")
// setItems
SwitchView(value: $homeState.navigationBarModel.setItems, title: "setItems")
}
}
}
.padding(.horizontal, 30.0)
}
}
struct UINavigationBarComponent_Previews: PreviewProvider {
static var previews: some View {
UINavigationBarComponent()
}
}
| 26.05 | 96 | 0.537428 |
f778b8df6d78fbcf7cb961bd877414b391773939
| 3,473 |
//
// PaymentHandler.swift
// pragueParking
//
// Created by Jakub Bednář on 23.06.2021.
//
import Foundation
import PassKit
typealias PaymentCompletionHandler = (Bool) -> Void
class PaymentHandler: NSObject {
static let supportedNetworks: [PKPaymentNetwork] = [
.masterCard,
.visa
]
var paymentController: PKPaymentAuthorizationController?
var paymentSummaryItems = [PKPaymentSummaryItem]()
var paymentStatus = PKPaymentAuthorizationStatus.failure
var completionHandler: PaymentCompletionHandler?
var priceListItemID: String?
func startPayment(paymentSummaryItems: [PKPaymentSummaryItem], priceListItemID: String, completion: @escaping PaymentCompletionHandler) {
self.priceListItemID = priceListItemID
completionHandler = completion
// Create our payment request
let paymentRequest = PKPaymentRequest()
paymentRequest.paymentSummaryItems = paymentSummaryItems
paymentRequest.merchantIdentifier = "merchant.cz.parkovani"
paymentRequest.merchantCapabilities = .capability3DS
paymentRequest.countryCode = "CZ"
paymentRequest.currencyCode = "CZK"
paymentRequest.requiredShippingContactFields = [.emailAddress]
paymentRequest.supportedNetworks = PaymentHandler.supportedNetworks
// Display our payment request
paymentController = PKPaymentAuthorizationController(paymentRequest: paymentRequest)
paymentController?.delegate = self
paymentController?.present(completion: { (presented: Bool) in
if presented {
NSLog("Presented payment controller")
} else {
NSLog("Failed to present payment controller")
self.completionHandler!(false)
}
})
}
}
/*
PKPaymentAuthorizationControllerDelegate conformance.
*/
extension PaymentHandler: PKPaymentAuthorizationControllerDelegate {
func paymentAuthorizationController(_ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
// Perform some very basic validation on the provided contact information
if payment.shippingContact?.emailAddress == nil {
paymentStatus = .failure
} else {
print("PriceListID:")
print(self.priceListItemID!)
print("PaymentToken:")
let paymentToken = payment.token.paymentData.base64EncodedString()
print(paymentToken)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
let request = postApplePayPaymentRequest(applePaymentToken: paymentToken, priceListItemId: self.priceListItemID!, sourceApplication: "PidLitacka")
Observer().getPriceList(request: request)
})
self.paymentStatus = .success
}
completion(paymentStatus)
}
func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {
controller.dismiss {
DispatchQueue.main.async {
if self.paymentStatus == .success {
self.completionHandler!(true)
} else {
self.completionHandler!(false)
}
}
}
}
}
| 36.946809 | 191 | 0.655341 |
e4f41df03b1502aa248c7f3d181be1bca6b2d3ca
| 549 |
import Fluent
import Vapor
final class DeviceToken: Model {
static let schema = "devices"
@ID(key: .id)
var id: UUID?
@Parent(key: "user_id")
var user: User
@Field(key: "token")
var token: String
@Field(key: "is_production")
var isProduction: Bool
init() {}
init(id: UUID? = nil, user: User, token: String, isProduction: Bool) throws {
self.id = id
$user.id = try user.requireID()
$user.value = user
self.token = token
self.isProduction = isProduction
}
}
| 20.333333 | 81 | 0.590164 |
6af2276767ed6113bf544f7918690a5ec2b00306
| 319 |
//
// ExpectationHandler.swift
// AutocompleteClientTests
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import XCTest
class ExpectationHandler {
let expectation: XCTestExpectation
init(expectation: XCTestExpectation) {
self.expectation = expectation
}
}
| 17.722222 | 52 | 0.708464 |
162c456973dbf829395993b9c3a96d313f48b8b9
| 1,633 |
import Foundation
import XCTest
@testable import TestingViewControllersExample
final class TagEventFactoryTests: XCTestCase {
// MARK: - Refresh button pressed event
func test_refreshButtonPressedEvent_hasCorrectUserId() {
let refreshButtonPressedEvent = TagEventFactory.refreshButtonPressedEvent()
XCTAssertEqual(refreshButtonPressedEvent.userId, 123)
}
func test_refreshButtonPressedEvent_hasCorrectBody() {
let refreshButtonPressedEvent = TagEventFactory.refreshButtonPressedEvent()
XCTAssertEqual(refreshButtonPressedEvent.body, "refresh button pressed")
}
// MARK: - Search button pressed event
func test_searchButtonPressedEvent_hasCorrectUserId() {
let searchButtonPressedEvent = TagEventFactory.searchButtonPressedEvent()
XCTAssertEqual(searchButtonPressedEvent.userId, 123)
}
func test_searchButtonPressedEvent_hasCorrectBody() {
let searchButtonPressedEvent = TagEventFactory.searchButtonPressedEvent()
XCTAssertEqual(searchButtonPressedEvent.body, "search button pressed")
}
// MARK: - Search cancel button event
func test_searchCancelButtonPressedEvent_hasCorrectUserId() {
let searchCancelButtonPressedEvent = TagEventFactory.searchCancelButtonPressedEvent()
XCTAssertEqual(searchCancelButtonPressedEvent.userId, 123)
}
func test_searchCancelButtonPressedEvent_hasCorrectBody() {
let searchCancelButtonPressedEvent = TagEventFactory.searchCancelButtonPressedEvent()
XCTAssertEqual(searchCancelButtonPressedEvent.body, "search cancel button pressed")
}
}
| 37.976744 | 93 | 0.778934 |
16f17f361acfb4f15dd7b5ccb2134dc678a2086e
| 534 |
//
// AddCategoriaViewModel.swift
// Wollen
//
// Created by Mayara Mendonça de Souza on 20/07/21.
//
import Foundation
class AddCategoriaViewModel: ObservableObject {
var nome: String = ""
var cor: String = ""
func saveCategoria() {
let manager = CoreDataManager.shared
let categoria = Categoria(context: manager.persistentContainer.viewContext)
categoria.nome = nome
categoria.cor = cor
manager.save()
print("Salvou a categoria!")
}
}
| 20.538462 | 83 | 0.617978 |
9b538770d24a3a0dcc78a6a09f45898842dac336
| 1,932 |
//
// Define.swift
// OnceNaive_Swift
//
// Created by LangFZ on 2019/3/7.
// Copyright © 2019 LangFZ. All rights reserved.
//
import UIKit
public var kScreen: CGRect { return UIScreen.main.bounds }
public var kScreenW: CGFloat { return kScreen.size.width }
public var kScreenH: CGFloat { return kScreen.size.height }
public var kNaviBarH: CGFloat { return getNavigationBarHeight() }
public var kStatusH: CGFloat { return getStatusHeight() }
public var kTabBarH: CGFloat { return getTabBarHeight() }
public var kTabBarBotH: CGFloat { return getTabBarBottomHeight() }
public func frameMath(_ frame: CGFloat) -> CGFloat {
return frame/375.0*UIScreen.main.bounds.width
}
// MARK: - NavigationBar
public func getNavigationBarHeight() -> CGFloat {
if isIphoneX() {
return CGFloat.init(88)
} else {
return CGFloat.init(64)
}
}
public func getStatusHeight() -> CGFloat {
if isIphoneX() {
return CGFloat.init(44)
} else {
return CGFloat.init(20)
}
}
// MARK: - TabBar
public func getTabBarHeight() -> CGFloat {
if isIphoneX() {
return CGFloat.init(83)
} else {
return CGFloat.init(49)
}
}
public func getTabBarBottomHeight() -> CGFloat {
if isIphoneX() {
return CGFloat.init(34)
} else {
return 0
}
}
// MARK: - 刘海屏
public func isIphoneX()->Bool {
if UIApplication.shared.windows[0].windowScene?.statusBarManager?.statusBarFrame.height ?? 0 >= 44 {
return true
} else {
return false
}
}
// MARK: - Debug模式下打印
public func print_debug(_ items: Any..., file:String = #file, funcName:String = #function, lineNum:Int = #line) {
#if DEBUG
let fileName = (file as NSString).lastPathComponent
var text = ""
for item in items {
text += "\n"
text += "\(item)"
}
print("\nClass: \(fileName) === line: \(lineNum)\(text)")
#endif
}
| 23.560976 | 113 | 0.635093 |
d91070dde9e744271ae1fc77d36c93637ad1a18e
| 5,096 |
//
// ComplicationController.swift
// Diabetapp for AppleWatch Extension
//
// Created by Alex Telek on 05/12/2015.
// Copyright © 2015 Diabetapp. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
let timeline = DATimeline().timelineData()
// MARK: - Timeline Configuration
func getEntryFor(complication: CLKComplication, entry: DAEntry, date: NSDate) -> CLKComplicationTimelineEntry? {
switch complication.family {
case .ModularSmall:
let modularSmallTemplate = CLKComplicationTemplateModularSmallRingText()
modularSmallTemplate.textProvider = CLKSimpleTextProvider(text: "\(entry.level)")
modularSmallTemplate.fillFraction = Float(entry.estimate) / 100.0
modularSmallTemplate.ringStyle = .Closed
let entry = CLKComplicationTimelineEntry(date: date, complicationTemplate: modularSmallTemplate)
return entry
case .ModularLarge:
let modularLargeTemplate = CLKComplicationTemplateModularLargeStandardBody()
modularLargeTemplate.headerTextProvider = CLKTimeIntervalTextProvider(startDate: entry.entryDate,
endDate: NSDate(timeInterval: 60, sinceDate: entry.entryDate))
modularLargeTemplate.body1TextProvider =
CLKSimpleTextProvider(text: "\(entry.level) mg/dL", shortText: "\(entry.level) mg/dL")
modularLargeTemplate.body2TextProvider =
CLKSimpleTextProvider(text: "\(entry.estimate)% confidence", shortText: nil)
let entry = CLKComplicationTimelineEntry(date: date, complicationTemplate: modularLargeTemplate)
return entry
case .UtilitarianLarge:
let template = CLKComplicationTemplateUtilitarianLargeFlat()
template.textProvider = CLKSimpleTextProvider(text: "\(entry.level) mg/dL (\(entry.estimate)%)")
let entry = CLKComplicationTimelineEntry(date: date, complicationTemplate: template)
return entry
default: return nil
}
}
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Forward, .Backward])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(NSDate(timeIntervalSinceNow: -3.5 * DATimeline.HOUR))
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(NSDate(timeIntervalSinceNow: 3.5 * DATimeline.HOUR))
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
for entry in timeline {
if (entry.entryDate.timeIntervalSinceNow >= 0) {
handler(getEntryFor(complication, entry: entry, date: entry.entryDate))
return
}
}
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
var timelineEntries: [CLKComplicationTimelineEntry] = []
for entry in timeline {
if timelineEntries.count < limit && entry.entryDate.timeIntervalSinceDate(date) < 0 {
timelineEntries.append(getEntryFor(complication, entry: entry, date: entry.entryDate)!)
}
}
handler(timelineEntries)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
var timelineEntries: [CLKComplicationTimelineEntry] = []
for entry in timeline {
if timelineEntries.count < limit && entry.entryDate.timeIntervalSinceDate(date) > 0 {
timelineEntries.append(getEntryFor(complication, entry: entry, date: entry.entryDate)!)
}
}
handler(timelineEntries)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
handler(NSDate(timeIntervalSinceNow: DATimeline.HOUR));
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
handler(nil)
}
}
| 45.5 | 178 | 0.68387 |
1c18449454639f159b8d105ec31de2b1ed069138
| 1,067 |
import BundlePlugin
import ProjectDescription
let project = Project(
name: "App",
targets: [
Target(
name: "App",
platform: .iOS,
product: .app,
bundleId: .bundleId(for: "App"),
infoPlist: "App/Info.plist",
sources: ["App/Sources/**"],
resources: [
/* Path to resources can be defined here */
// "Resources/**"
],
dependencies: [
/* Target dependencies can be defined here */
// .framework(path: "Frameworks/MyFramework.framework")
.project(target: "FrameworkA", path: "Frameworks/FeatureAFramework"),
]
),
Target(
name: "AppTests",
platform: .iOS,
product: .unitTests,
bundleId: .bundleId(for: "AppTests"),
infoPlist: "App/Tests.plist",
sources: "App/Tests/**",
dependencies: [
.target(name: "App"),
]
),
]
)
| 28.837838 | 85 | 0.462043 |
0afbecb318445196d39ef64ac6df0910a3cd5969
| 10,014 |
/*:
# AMP
## Overview
The GEOINT App Store AIMS Mobile Platform (AMP) for iOS is an XCFramework package used to enable management of installs,
subscription licenses, and other metrics about the [IGAPP](https://igapp.com/) program products available on the [GEOINT
App Store (GAS)](https://apps.nga.mil) website. Adding AMP is a requirement of [IGAPP](https://igapp.com/) applications.
This document will explain the process of adding AMP to an iOS application.
## Module
One module is vended by this package: AMP
*/
import AMP
/*:
## Adding AMP to your project
The easiest way to add AMP is through Swift Package Manager if using XCode 12 or later:
1. Open your project, navigate to 'File' > 'Swift Packages' > 'Add Package Dependency...'.
2. Select your project and click 'Next' (if required).
3. Enter this repository URL and tap 'Next'
4. Choose the version you want to use (ideally the latest version) and click 'Next'
5. Choose the target and click 'Finish'
## Implementing AMP in iOS
1. In the Signing & Capabilities tab of your target, enable Keychain Sharing and add "AMPGroup" to your list of groups.
2. In the Info tab of your target, add the URL Type of "$(PRODUCT_BUNDLE_IDENTIFIER)"
3. In the Build Settings tab of your target, set the Enable Bitcode setting to "No".
4. If using a _SceneDelegate_, skip to next step, otherwise, go to your _AppDelegate_ class and add the following to your
applicationDidFinishLaunchingWithOptions override.
*/
import UIKit
import AMP
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// Add in AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let signature = "test"
Amp.start(with: window, environment: .TESTING, signature: signature) {
// TODO - Your segue will go here. See step 7 for more details.
}
return true
}
}
/*:
6. If using a _SceneDelegate_, go to your _SceneDelegate_ class and add the following to your scene function.
*/
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
// Add in SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
self.window = UIWindow(windowScene: windowScene)
self.window?.rootViewController = UIViewController(nibName: nil, bundle: nil) // This placeholder VC will be replaced by AMP VC
self.window?.makeKeyAndVisible()
// Start AMP
let signature = "test"
Amp.start(with: self.window, environment: .TESTING, signature: signature) {
// TODO - Your segue will go here. See step 7 for more details.
}
}
}
/*:
7. Fill in the start method’s completion block with a segue to your initial view controller. Below are several examples
of how this can be accomplished in different scenarios. These are only examples, and you should feel free to segue to your
view controller however you wish as long as it takes place within this block.
*/
//////////////////////////////////////////////////////////////////
// START playground specific code
// The following is just here for the playground to compile. This is already defined in the AppDelegate or SceneDelegate
import SwiftUI
var window: UIWindow?
struct ContentView: View { var body: some View { VStack {} } }
class ViewController: UIViewController { }
// END playground specific code
//////////////////////////////////////////////////////////////////
// For Swift Projects with SceneDelegate:
//////////////////////////////////////////////////////////////////
// Create the SwiftUI view that provides the window contents.
// Use a UIHostingController as window root view controller.
window?.rootViewController = UIHostingController(rootView: ContentView())
window?.makeKeyAndVisible()
// For Swift Projects with AppDelegate:
//////////////////////////////////////////////////////////////////
// Example A: If you've created your first VC programmatically
let vc_a = ViewController()
window?.rootViewController = vc_a
// Example B: If your VC is listed in Storyboard as initial VC
let storyboard_b = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc_b: ViewController = storyboard_b.instantiateInitialViewController() as! ViewController
window?.rootViewController = vc_b
// Example C: If your VC is listed in Storyboard
let storyboard_c = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc_c = storyboard_c.instantiateViewController(withIdentifier: "Starting VC")
window?.rootViewController = vc_c
// Example D: If your initial VC needs a nav controller
let storyboard_d = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc_d = storyboard_d.instantiateViewController(withIdentifier: "Starting VC")
let navigationVC_d = UINavigationController(rootViewController: vc_d)
window?.rootViewController = navigationVC_d
// Example E: If your navigation controller is already in Storyboard
let storyboard_e = UIStoryboard(name: "Main", bundle: Bundle.main)
let navVC_e = storyboard_e.instantiateViewController(withIdentifier: "Nav VC")
/*:
8. Allow OAuth redirection back into App handler. This method allows for OAuth using GEOAxIS. The AMP UI will show a "Login with PKI" button that will open a
web browser to GEOAxIS to allow PKI authentication. This will redirect back into the AMP app and a handler needs added to process the redirect result. This is that handler:
*/
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return Amp.oauthStart(url)
}
/*:
9. Disable third party keyboards. This is for security reasons, so that a user's username and password cannot be recorded. Add this method if it is
not already in your _AppDelegate_.
*/
func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplication.ExtensionPointIdentifier) -> Bool {
return extensionPointIdentifier != UIApplication.ExtensionPointIdentifier.keyboard
}
/*:
10. Modify your info.plist:
1. Set the name of your app. Add a new key named "Bundle display name" with a value of the name of your application
2. Enable location services. Add a new key named "Privacy - Location When In Use Usage Description" with a value
of "GEOINT App Store will access your location when opening this application." If you already have a value here, you should
keep your existing message.
3. Enable biometric authentication. Add a new key named "Privacy - Face ID Usage Description" with a value of "Use
your stored credentials to log in to the GEOINT App Store." If you already have a value here, you should keep your existing
message.
11. Run your application on a device, and you should see a login screen. As long as you used the TESTING environment in the
start method, you should see a "TESTING" label at the bottom of the screen. This testing environment will simulate network
behavior, but will not actually make any network calls. Feel free to test your app with it. Tap the Login button to test a
successful login, and verify that the initial view controller you specified is displayed.
## AMP Options
### Start Method Completion Block
The Start method is used to authenticate a user with the GEOINT App Store and activate the application. If you would like to
ensure a block of code is called after AMP has finished with its Start method, you can pass a completion block into the Start
method. Note that using the Start method with a completion handler should replace your existing call to Start.
*/
let signature: String = "exampleSignature"
Amp.start(with: window, environment: .NGA_PRODUCTION, signature: signature) {
// TODO - Place your completion code here
}
/*:
### Device ID
This method will return a device ID associated with the device the user has installed the app on. This device ID will match
what the GEOINT App Store uses to identify the device.
*/
let deviceId: String? = Amp.getDeviceId()
/*:
### Login ID
This method will return a login ID unique to the user who activates the application, and this login ID remains the same
across devices for this user. Note that this method will only return a value after the Start method has finished running.
Otherwise it returns an empty string. For this reason, you may want to access login ID in the completion handler for the
Start method.
*/
let loginId: String? = Amp.getLoginId()
/*:
### Usage Count
This method will return a count of the number of usages of your AMP app. This usage count is used to prompt a ratings dialogue.
*/
let usageCount: Int = Amp.getUsageCount()
/*:
### AMP Version
This method will return the version number of the AMP framework.
*/
let ampVersion: String = Amp.getVersionNumber()
/*:
### In-App Reviews
This method allows you to specify a number of usages (any integer greater than zero) of your application before a review prompt is displayed. This review will appear in
the GEOINT App Store for your product. Regardless of if you implement this option, users still have the ability to add a review in the GEOINT App Store.
The user has the options of leaving a review, dismissing and never showing the review prompt again, or dismissing the review prompt this time (it will not appear again
until the user has completed the same amount of usages again). Note that this method must be called prior to calling the start method.
*/
Amp.setUsagesBeforeRatingsPrompt(5)
// Then call Amp.start ...
/*:
### Network Availability
This method will return true if the GEOINT App Store is available on the network.
*/
let networkAvailable: Bool = Amp.isNetworkAvailable()
| 40.707317 | 176 | 0.732475 |
e004d0bac4218753745305acbdf07c0ca892077c
| 8,890 |
//
// TextRewriter.swift
// Magarikado
//
// Copyright (c) 2021 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// Utility for rewriting text lines.
public struct TextRewriter {
private var lines: [String]
private var marks: [Mark] = [] // marks are sorted in ascending order by position
private struct Mark {
var position: Position
var newTextLines: [String]
}
/// Initialize object with text lines to rewrite.
/// - Parameter lines: Text lines to rewrite.
public init(lines: [String]) {
self.lines = lines
}
/// Add a rewriting mark.
/// - Parameters:
/// - position: position
/// - newText: new text
/// - Throws: Throws ``TextRewriterError.positionOverlapped`` when the position is overlapped to existing one.
public mutating func addMark(at position: Position, newText: String) throws {
let newTextLines = newText
.replacingOccurrences(of: "\r", with: "")
.split(separator: "\n", omittingEmptySubsequences: false)
.map { String($0) }
try addMark(at: position, newTextLines: newTextLines)
}
/// Add a rewriting mark.
/// - Parameters:
/// - position: position
/// - newText: lines of new text
/// - Throws: Throws ``TextRewriterError.positionOverlapped`` when the position is overlapped to existing one.
public mutating func addMark(at position: Position, newTextLines: [String]) throws {
let (_, index) = Utility.binarySearch(startIndex: marks.startIndex, endIndex: marks.endIndex) { index in
let mark = marks[index]
let lineComp = mark.position.startLine - position.startLine
if lineComp == 0 {
return mark.position.startColumn - position.startColumn
} else {
return lineComp
}
}
// check if overlapping with previous range
if index - 1 >= marks.startIndex {
if marks[index - 1].position.endLine > position.startLine
|| (marks[index - 1].position.endLine == position.startLine && marks[index - 1].position.endColumn > position.startColumn) {
throw MagarikadoError.markedPositionOverlapped
}
}
// check if overlapping with next range
if index < marks.endIndex {
if marks[index].position.startLine < position.endLine
|| (marks[index].position.startLine == position.endLine && marks[index].position.startColumn < position.endColumn) {
throw MagarikadoError.markedPositionOverlapped
}
}
marks.insert(Mark(position: position, newTextLines: newTextLines), at: index)
}
/// Rewrite text lines.
/// - Returns: Rewriiten lines.
public func rewrite() -> [String] {
var lines = self.lines
for mark in marks.reversed() {
let newTextLinesCount = mark.newTextLines.count
if mark.position.startLine == mark.position.endLine {
switch newTextLinesCount {
case 0:
var targetLine = lines[mark.position.startLine]
targetLine.removeSubrange(targetLine.index(targetLine.startIndex, offsetBy: mark.position.startColumn) ..< targetLine.index(targetLine.startIndex, offsetBy: mark.position.endColumn))
lines[mark.position.startLine] = targetLine
break
case 1:
var targetLine = lines[mark.position.startLine]
targetLine.replaceSubrange(targetLine.index(targetLine.startIndex, offsetBy: mark.position.startColumn) ..< targetLine.index(targetLine.startIndex, offsetBy: mark.position.endColumn),
with: mark.newTextLines[0])
lines[mark.position.startLine] = targetLine
default:
var startLine = lines[mark.position.startLine]
var endLine = startLine
startLine.replaceSubrange(startLine.index(startLine.startIndex, offsetBy: mark.position.startColumn) ..< startLine.endIndex,
with: mark.newTextLines[0])
endLine.replaceSubrange(endLine.startIndex ..< endLine.index(endLine.startIndex, offsetBy: mark.position.endColumn),
with: mark.newTextLines[mark.newTextLines.count - 1])
lines[mark.position.startLine] = startLine
if newTextLinesCount > 2 {
lines.insert(contentsOf: mark.newTextLines[1 ..< newTextLinesCount - 1], at: mark.position.startLine + 1)
}
lines.insert(endLine, at: mark.position.startLine + newTextLinesCount - 1)
}
} else {
switch newTextLinesCount {
case 0:
let startLine = lines[mark.position.startLine]
let endLine = lines[mark.position.endLine]
let rewrittenLine = String(startLine[startLine.startIndex ..< startLine.index(startLine.startIndex, offsetBy: mark.position.startColumn)])
+ String(endLine[endLine.index(endLine.startIndex, offsetBy: mark.position.endColumn)...])
lines[mark.position.startLine] = rewrittenLine
if mark.position.startLine + 1 <= mark.position.endLine {
lines.removeSubrange(mark.position.startLine + 1 ... mark.position.endLine)
}
case 1:
let startLine = lines[mark.position.startLine]
let endLine = lines[mark.position.endLine]
let rewrittenStartLine = String(startLine[startLine.startIndex ..< startLine.index(startLine.startIndex, offsetBy: mark.position.startColumn)])
+ mark.newTextLines[0]
lines[mark.position.startLine] = rewrittenStartLine
let rewrittenEndLine = String(endLine[endLine.index(endLine.startIndex, offsetBy: mark.position.endColumn)...])
if mark.position.endColumn != 0 && rewrittenEndLine.isEmpty {
lines.remove(at: mark.position.endLine)
} else {
lines[mark.position.endLine] = rewrittenEndLine
}
if mark.position.startLine + 1 < mark.position.endLine {
lines.removeSubrange(mark.position.startLine + 1 ..< mark.position.endLine)
}
default:
let startLine = lines[mark.position.startLine]
let endLine = lines[mark.position.endLine]
let rewrittenStartLine = String(startLine[startLine.startIndex ..< startLine.index(startLine.startIndex, offsetBy: mark.position.startColumn)])
+ mark.newTextLines[0]
lines[mark.position.startLine] = rewrittenStartLine
let rewrittenEndLine = mark.newTextLines[mark.newTextLines.count - 1] + String(endLine[endLine.index(endLine.startIndex, offsetBy: mark.position.endColumn)...])
lines[mark.position.endLine] = rewrittenEndLine
if mark.position.startLine + 1 < mark.position.endLine {
lines.removeSubrange(mark.position.startLine + 1 ..< mark.position.endLine)
}
lines.insert(contentsOf: mark.newTextLines[1 ..< mark.newTextLines.count - 1], at: mark.position.startLine + 1)
}
}
}
return lines
}
}
| 52.916667 | 203 | 0.605624 |
75612d3486ce0ab1980bcd78cd8f329b5f7141d6
| 974 |
//
// OptimizeTests.swift
// OptimizeTests
//
// Created by Scott Hoyt on 9/3/15.
// Copyright © 2015 Scott Hoyt. All rights reserved.
//
import XCTest
@testable import Optimize
class OptimizeTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// 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.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.324324 | 111 | 0.63347 |
1a2135744f02b1beeecb151c41c8d6415cb850ef
| 2,358 |
//
// SceneDelegate.swift
// SimpleGameOfLife
//
// Created by Sugeng Wibowo on 15/04/20.
// Copyright © 2020 Sugeng Wibowo. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.666667 | 147 | 0.714589 |
3a6dc407015d8b0386a82f48059530c792118f9f
| 6,624 |
//
// Adjacent5CollectionIndex.swift
//
import Foundation
import HDXLCommonUtilities
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - Definition
// -------------------------------------------------------------------------- //
/// Index for the arity-5 adjacent-tuple collection.
@frozen
public struct Adjacent5CollectionIndex<PositionRepresentation:AlgebraicProduct5> : IndexPositionStorageWrapper
where
PositionRepresentation.A:Comparable,
PositionRepresentation.A == PositionRepresentation.B,
PositionRepresentation.A == PositionRepresentation.C,
PositionRepresentation.A == PositionRepresentation.D,
PositionRepresentation.A == PositionRepresentation.E {
@usableFromInline
typealias Storage = IndexPositionStorage<PositionRepresentation>
@usableFromInline
internal var storage: Storage
@inlinable
internal init(storage: Storage) {
self.storage = storage
}
}
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - Validatable
// -------------------------------------------------------------------------- //
extension Adjacent5CollectionIndex : Validatable {
@inlinable
public var isValid: Bool {
get {
return self.storage.customizedValidation() {
(position: PositionRepresentation) -> Bool
in
guard
position.a < position.b,
position.b < position.c,
position.c < position.d,
position.d < position.e else {
return false
}
return true
}
}
}
}
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - Equatable
// -------------------------------------------------------------------------- //
extension Adjacent5CollectionIndex : Equatable {
@inlinable
public static func ==(
lhs: Adjacent5CollectionIndex<PositionRepresentation>,
rhs: Adjacent5CollectionIndex<PositionRepresentation>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage.customizedEquivalence(to: rhs.storage) {
(l,r) -> Bool
in
return l.firstValue == r.firstValue
}
}
}
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - Comparable
// -------------------------------------------------------------------------- //
extension Adjacent5CollectionIndex : Comparable {
@inlinable
public static func <(
lhs: Adjacent5CollectionIndex<PositionRepresentation>,
rhs: Adjacent5CollectionIndex<PositionRepresentation>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage.customizedComparison(to: rhs.storage) {
(l,r) -> ComparisonResult
in
return l.firstValue <=> r.firstValue
}.impliesLessThan
}
@inlinable
public static func >(
lhs: Adjacent5CollectionIndex<PositionRepresentation>,
rhs: Adjacent5CollectionIndex<PositionRepresentation>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage.customizedComparison(to: rhs.storage) {
(l,r) -> ComparisonResult
in
return l.firstValue <=> r.firstValue
}.impliesGreaterThan
}
@inlinable
public static func <=(
lhs: Adjacent5CollectionIndex<PositionRepresentation>,
rhs: Adjacent5CollectionIndex<PositionRepresentation>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage.customizedComparison(to: rhs.storage) {
(l,r) -> ComparisonResult
in
return l.firstValue <=> r.firstValue
}.impliesLessThanOrEqual
}
@inlinable
public static func >=(
lhs: Adjacent5CollectionIndex<PositionRepresentation>,
rhs: Adjacent5CollectionIndex<PositionRepresentation>) -> Bool {
// /////////////////////////////////////////////////////////////////////////
pedantic_assert(lhs.isValid)
pedantic_assert(rhs.isValid)
// /////////////////////////////////////////////////////////////////////////
return lhs.storage.customizedComparison(to: rhs.storage) {
(l,r) -> ComparisonResult
in
return l.firstValue <=> r.firstValue
}.impliesGreaterThanOrEqual
}
}
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - Hashable
// -------------------------------------------------------------------------- //
extension Adjacent5CollectionIndex : Hashable where PositionRepresentation:Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
self.storage.hash(into: &hasher)
}
}
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - CustomStringConvertible
// -------------------------------------------------------------------------- //
extension Adjacent5CollectionIndex : CustomStringConvertible {
@inlinable
public var description: String {
get {
return self.storage.description
}
}
}
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - CustomDebugStringConvertible
// -------------------------------------------------------------------------- //
extension Adjacent5CollectionIndex : CustomDebugStringConvertible {
@inlinable
public var debugDescription: String {
get {
return "Adjacent5CollectionIndex<\(String(reflecting: PositionRepresentation.self))>(storage: \(String(reflecting: self.storage)))"
}
}
}
// -------------------------------------------------------------------------- //
// MARK: Adjacent5CollectionIndex - Codable
// -------------------------------------------------------------------------- //
extension Adjacent5CollectionIndex : Codable where PositionRepresentation:Codable {
}
| 32.630542 | 137 | 0.491999 |
5dd57678289cae8fd1cf52ff6a0fe16c455f6549
| 2,988 |
//
// Post01ViewController.swift
// LittleMarket
//
// Created by J on 2016/10/10.
// Copyright © 2016年 J. All rights reserved.
//
import UIKit
class Post01ViewController: UIViewController {
// MARK: - 变量
let segueID = "Post02"
@IBOutlet weak var lbName: UITextField!
@IBOutlet weak var lbPrice: UITextField!
@IBOutlet weak var lbNote: UITextView!
// MARK: - 事件
@IBAction func goNext(_ sender: UIButton) {
// 取消键盘
self.view.endEditing(true)
// 验证
self.check()
}
// MARK: - 函数
// 验证
func check() {
// 为空
let Name = lbName.text
let Price = lbPrice.text
let Note = lbNote.text
if Name!.isEmpty || Price!.isEmpty || Note!.isEmpty{
// HUD提示
self.HUDtext(text: "请确认信息")
return
}
if !Validate.text(Name!).isRight {
self.HUDtext(text: "请确认名称格式")
return
}
if !Validate.numDe(Price!).isRight {
self.HUDtext(text: "请确认价格格式")
return
}
self.performSegue(withIdentifier:self.segueID, sender: nil)
}
// 取消键盘
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// HUD.dismiss()
self.view.endEditing(true)
}
// MARK: - 系统
override func viewDidLoad() {
super.viewDidLoad()
// self.tabBarController?.tabBar.isHidden = true
// 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == segueID{
let controller = segue.destination as! Post02ViewController
controller.nameStr = lbName.text!
controller.priceStr = lbPrice.text!
controller.noteStr = lbNote.text!
}
}
// MRAK: - HUDTEXT
var hud:MBProgressHUD?
func HUDtext(text:String) {
hud = MBProgressHUD.showAdded(to: self.view.window!, animated: true)
hud?.mode = MBProgressHUDMode.text
hud?.label.text = NSLocalizedString(text, comment: "HUD message title")
hud?.offset = CGPoint.init(x: 0, y: MBProgressMaxOffset)
hud?.hide(animated: true, afterDelay: 2)
}
func HUDHide() {
hud?.hide(animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// 清空提示框
self.HUDHide()
}
}
| 27.412844 | 106 | 0.580991 |
8addd50de4617ac9dff87ab586e930816a3c8de2
| 27,378 |
#if os(iOS) || os(tvOS)
import UIKit
typealias View = UIView
extension View {
var snp_constraints: [AnyObject] {
return self.constraints
.filter { $0 is LayoutConstraint }
.filter { $0.isActive }
}
}
#else
import AppKit
typealias View = NSView
extension View {
var snp_constraints: [AnyObject] {
return self.constraints
.filter { $0 is LayoutConstraint }
.filter { $0.isActive }
}
}
#endif
import XCTest
@testable import SnapKit
class SnapKitTests: XCTestCase {
let container = View()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testMakeConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
v1.snp.makeConstraints { (make) -> Void in
make.top.equalTo(v2.snp.top).offset(50)
make.left.equalTo(v2.snp.top).offset(50)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints installed")
v2.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(v1)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 6, "Should have 6 constraints installed")
}
func testGuideMakeConstraints() {
guard #available(iOS 9.0, OSX 10.11, *) else { return }
let v1 = View()
let g1 = ConstraintLayoutGuide()
self.container.addSubview(v1)
self.container.addLayoutGuide(g1)
v1.snp.makeConstraints { (make) -> Void in
make.top.equalTo(g1).offset(50)
make.left.equalTo(g1.snp.top).offset(50)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints installed")
g1.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(v1)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 6, "Should have 6 constraints installed")
}
func testMakeImpliedSuperviewConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
v1.snp.makeConstraints { (make) -> Void in
make.top.equalTo(50.0)
make.left.equalTo(50.0)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints installed")
v2.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(v1)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 6, "Should have 6 constraints installed")
}
func testUpdateConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
v1.snp.makeConstraints { (make) -> Void in
make.top.equalTo(v2.snp.top).offset(50)
make.left.equalTo(v2.snp.top).offset(50)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints installed")
v1.snp.updateConstraints { (make) -> Void in
make.top.equalTo(v2.snp.top).offset(15)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should still have 2 constraints installed")
}
func testRemakeConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
v1.snp.makeConstraints { (make) -> Void in
make.top.equalTo(v2.snp.top).offset(50)
make.left.equalTo(v2.snp.top).offset(50)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints installed")
v1.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(v2)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints installed")
}
func testRemoveConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
v1.snp.makeConstraints { (make) -> Void in
make.top.equalTo(v2).offset(50)
make.left.equalTo(v2).offset(50)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints installed")
print(self.container.snp_constraints)
v1.snp.removeConstraints()
print(self.container.snp_constraints)
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints installed")
}
func testPrepareConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
let constraints = v1.snp.prepareConstraints { (make) -> Void in
make.edges.equalTo(v2)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints installed")
for constraint in constraints {
constraint.activate()
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints installed")
for constraint in constraints {
constraint.deactivate()
}
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints installed")
}
func testReactivateConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
let constraints = v1.snp.prepareConstraints { (make) -> Void in
make.edges.equalTo(v2)
return
}
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints installed")
for constraint in constraints {
constraint.activate()
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints installed")
for constraint in constraints {
constraint.deactivate()
}
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints installed")
}
func testActivateDeactivateConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
var c1: Constraint? = nil
var c2: Constraint? = nil
v1.snp.prepareConstraints { (make) -> Void in
c1 = make.top.equalTo(v2.snp.top).offset(50).constraint
c2 = make.left.equalTo(v2.snp.top).offset(50).constraint
return
}
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints")
c1?.activate()
c2?.activate()
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
c1?.deactivate()
c2?.deactivate()
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints")
c1?.activate()
c2?.activate()
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
}
func testSetIsActivatedConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
var c1: Constraint? = nil
var c2: Constraint? = nil
v1.snp.prepareConstraints { (make) -> Void in
c1 = make.top.equalTo(v2.snp.top).offset(50).constraint
c2 = make.left.equalTo(v2.snp.top).offset(50).constraint
return
}
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints")
c1?.isActive = true
c2?.isActive = false
XCTAssertEqual(self.container.snp_constraints.count, 1, "Should have 1 constraint")
c1?.isActive = true
c2?.isActive = true
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
c1?.isActive = false
c2?.isActive = false
XCTAssertEqual(self.container.snp_constraints.count, 0, "Should have 0 constraints")
}
func testEdgeConstraints() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.container).offset(50.0)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
let constraints = self.container.snp_constraints as! [NSLayoutConstraint]
XCTAssertEqual(constraints[0].constant, 50, "Should be 50")
XCTAssertEqual(constraints[1].constant, 50, "Should be 50")
XCTAssertEqual(constraints[2].constant, 50, "Should be 50")
XCTAssertEqual(constraints[3].constant, 50, "Should be 50")
}
func testUpdateReferencedConstraints() {
let v1 = View()
let v2 = View()
self.container.addSubview(v1)
self.container.addSubview(v2)
var c1: Constraint! = nil
var c2: Constraint! = nil
v1.snp.makeConstraints { (make) -> Void in
c1 = make.top.equalTo(v2).offset(50).constraint
c2 = make.bottom.equalTo(v2).offset(25).constraint
return
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
let constraints = (self.container.snp_constraints as! [NSLayoutConstraint]).sorted { $0.constant > $1.constant }
XCTAssertEqual(constraints[0].constant, 50, "Should be 50")
XCTAssertEqual(constraints[1].constant, 25, "Should be 25")
c1.update(offset: 15)
c2.update(offset: 20)
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
XCTAssertEqual(constraints[0].constant, 15, "Should be 15")
XCTAssertEqual(constraints[1].constant, 20, "Should be 20")
c1.update(inset: 15)
c2.update(inset: 20)
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
XCTAssertEqual(constraints[0].constant, 15, "Should be 15")
XCTAssertEqual(constraints[1].constant, -20, "Should be -20")
}
func testInsetsAsConstraintsConstant() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.container).inset(50.0)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
let constraints = (self.container.snp_constraints as! [NSLayoutConstraint]).sorted { $0.constant > $1.constant }
XCTAssertEqual(constraints[0].constant, 50, "Should be 50")
XCTAssertEqual(constraints[1].constant, 50, "Should be 50")
XCTAssertEqual(constraints[2].constant, -50, "Should be -50")
XCTAssertEqual(constraints[3].constant, -50, "Should be -50")
}
func testConstraintInsetsAsImpliedEqualToConstraints() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(ConstraintInsets(top: 25, left: 25, bottom: 25, right: 25))
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
let constraints = (self.container.snp_constraints as! [NSLayoutConstraint]).sorted { $0.constant > $1.constant }
XCTAssertEqual(constraints[0].constant, 25, "Should be 25")
XCTAssertEqual(constraints[1].constant, 25, "Should be 25")
XCTAssertEqual(constraints[2].constant, -25, "Should be -25")
XCTAssertEqual(constraints[3].constant, -25, "Should be -25")
}
func testConstraintInsetsAsConstraintsConstant() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.container).inset(ConstraintInsets(top: 25, left: 25, bottom: 25, right: 25))
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
let constraints = (self.container.snp_constraints as! [NSLayoutConstraint]).sorted { $0.constant > $1.constant }
XCTAssertEqual(constraints[0].constant, 25, "Should be 25")
XCTAssertEqual(constraints[1].constant, 25, "Should be 25")
XCTAssertEqual(constraints[2].constant, -25, "Should be -25")
XCTAssertEqual(constraints[3].constant, -25, "Should be -25")
}
#if os(iOS) || os(tvOS)
@available(iOS 11.0, tvOS 11.0, *)
func testConstraintDirectionalInsetsAsImpliedEqualToConstraints() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.top.leading.bottom.trailing.equalTo(self.container).inset(ConstraintDirectionalInsets(top: 25, leading: 25, bottom: 25, trailing: 25))
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
let constraints = (self.container.snp_constraints as! [NSLayoutConstraint]).sorted { $0.firstAttribute.rawValue < $1.firstAttribute.rawValue }
let verify: (NSLayoutConstraint, NSLayoutConstraint.Attribute, CGFloat) -> Void = { constraint, attribute, constant in
XCTAssertEqual(constraint.firstAttribute, attribute, "First attribute \(constraint.firstAttribute.rawValue) is not \(attribute.rawValue)")
XCTAssertEqual(constraint.secondAttribute, attribute, "Second attribute \(constraint.secondAttribute.rawValue) is not \(attribute.rawValue)")
XCTAssertEqual(constraint.constant, constant, "Attribute \(attribute.rawValue) should have constant \(constant)")
}
verify(constraints[0], .top, 25)
verify(constraints[1], .bottom, -25)
verify(constraints[2], .leading, 25)
verify(constraints[3], .trailing, -25)
}
#endif
#if os(iOS) || os(tvOS)
@available(iOS 11.0, tvOS 11.0, *)
func testConstraintDirectionalInsetsAsConstraintsConstant() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.top.leading.bottom.trailing.equalTo(self.container).inset(ConstraintDirectionalInsets(top: 25, leading: 25, bottom: 25, trailing: 25))
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
let constraints = (self.container.snp_constraints as! [NSLayoutConstraint]).sorted { $0.firstAttribute.rawValue < $1.firstAttribute.rawValue }
let verify: (NSLayoutConstraint, NSLayoutConstraint.Attribute, CGFloat) -> Void = { constraint, attribute, constant in
XCTAssertEqual(constraint.firstAttribute, attribute, "First attribute \(constraint.firstAttribute.rawValue) is not \(attribute.rawValue)")
XCTAssertEqual(constraint.secondAttribute, attribute, "Second attribute \(constraint.secondAttribute.rawValue) is not \(attribute.rawValue)")
XCTAssertEqual(constraint.constant, constant, "Attribute \(attribute.rawValue) should have constant \(constant)")
}
verify(constraints[0], .top, 25)
verify(constraints[1], .bottom, -25)
verify(constraints[2], .leading, 25)
verify(constraints[3], .trailing, -25)
}
#endif
#if os(iOS) || os(tvOS)
@available(iOS 11.0, tvOS 11.0, *)
func testConstraintDirectionalInsetsFallBackForNonDirectionalConstraints() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.container).inset(ConstraintDirectionalInsets(top: 25, leading: 25, bottom: 25, trailing: 25))
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
let constraints = (self.container.snp_constraints as! [NSLayoutConstraint]).sorted { $0.firstAttribute.rawValue < $1.firstAttribute.rawValue }
let verify: (NSLayoutConstraint, NSLayoutConstraint.Attribute, CGFloat) -> Void = { constraint, attribute, constant in
XCTAssertEqual(constraint.firstAttribute, attribute, "First attribute \(constraint.firstAttribute.rawValue) is not \(attribute.rawValue)")
XCTAssertEqual(constraint.secondAttribute, attribute, "Second attribute \(constraint.secondAttribute.rawValue) is not \(attribute.rawValue)")
XCTAssertEqual(constraint.constant, constant, "Attribute \(attribute.rawValue) should have constant \(constant)")
}
verify(constraints[0], .left, 25)
verify(constraints[1], .right, -25)
verify(constraints[2], .top, 25)
verify(constraints[3], .bottom, -25)
}
#endif
func testSizeConstraints() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.size.equalTo(CGSize(width: 50, height: 50))
make.left.top.equalTo(self.container)
}
XCTAssertEqual(view.snp_constraints.count, 2, "Should have 2 constraints")
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
let constraints = view.snp_constraints as! [NSLayoutConstraint]
// no guarantee which order the constraints are in, but we should test their couple
let widthHeight = (LayoutAttribute.width.rawValue, LayoutAttribute.height.rawValue)
let heightWidth = (widthHeight.1, widthHeight.0)
let firstSecond = (constraints[0].firstAttribute.rawValue, constraints[1].firstAttribute.rawValue)
// constraint values are correct in either width, height or height, width order
XCTAssertTrue(firstSecond == widthHeight || firstSecond == heightWidth, "2 contraint values should match")
XCTAssertEqual(constraints[0].constant, 50, "Should be 50")
XCTAssertEqual(constraints[1].constant, 50, "Should be 50")
}
func testCenterConstraints() {
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.center.equalTo(self.container).offset(50.0)
}
XCTAssertEqual(self.container.snp_constraints.count, 2, "Should have 2 constraints")
if let constraints = self.container.snp_constraints as? [NSLayoutConstraint], constraints.count > 0 {
XCTAssertEqual(constraints[0].constant, 50, "Should be 50")
XCTAssertEqual(constraints[1].constant, 50, "Should be 50")
}
}
func testConstraintIdentifier() {
let identifier = "Test-Identifier"
let view = View()
self.container.addSubview(view)
view.snp.makeConstraints { (make) -> Void in
make.top.equalTo(self.container.snp.top).labeled(identifier)
}
let constraints = container.snp_constraints as! [NSLayoutConstraint]
XCTAssertEqual(constraints[0].identifier, identifier, "Identifier should be 'Test'")
}
func testEdgesToEdges() {
var fromAttributes = Set<LayoutAttribute>()
var toAttributes = Set<LayoutAttribute>()
let view = View()
self.container.addSubview(view)
view.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(self.container.snp.edges)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
for constraint in (container.snp_constraints as! [NSLayoutConstraint]) {
fromAttributes.insert(constraint.firstAttribute)
toAttributes.insert(constraint.secondAttribute)
}
XCTAssert(fromAttributes == [.top, .left, .bottom, .right])
XCTAssert(toAttributes == [.top, .left, .bottom, .right])
}
func testDirectionalEdgesToDirectionalEdges() {
var fromAttributes = Set<LayoutAttribute>()
var toAttributes = Set<LayoutAttribute>()
let view = View()
self.container.addSubview(view)
view.snp.remakeConstraints { (make) -> Void in
make.directionalEdges.equalTo(self.container.snp.directionalEdges)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
for constraint in (container.snp_constraints as! [NSLayoutConstraint]) {
fromAttributes.insert(constraint.firstAttribute)
toAttributes.insert(constraint.secondAttribute)
}
XCTAssert(fromAttributes == [.top, .leading, .bottom, .trailing])
XCTAssert(toAttributes == [.top, .leading, .bottom, .trailing])
}
#if os(iOS) || os(tvOS)
func testEdgesToMargins() {
var fromAttributes = Set<LayoutAttribute>()
var toAttributes = Set<LayoutAttribute>()
let view = View()
self.container.addSubview(view)
view.snp.remakeConstraints { (make) -> Void in
make.edges.equalTo(self.container.snp.margins)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
for constraint in (container.snp_constraints as! [NSLayoutConstraint]) {
fromAttributes.insert(constraint.firstAttribute)
toAttributes.insert(constraint.secondAttribute)
}
XCTAssert(fromAttributes == [.top, .left, .bottom, .right])
XCTAssert(toAttributes == [.topMargin, .leftMargin, .bottomMargin, .rightMargin])
fromAttributes.removeAll()
toAttributes.removeAll()
view.snp.remakeConstraints { (make) -> Void in
make.margins.equalTo(self.container.snp.edges)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
for constraint in (container.snp_constraints as! [NSLayoutConstraint]) {
fromAttributes.insert(constraint.firstAttribute)
toAttributes.insert(constraint.secondAttribute)
}
XCTAssert(toAttributes == [.top, .left, .bottom, .right])
XCTAssert(fromAttributes == [.topMargin, .leftMargin, .bottomMargin, .rightMargin])
}
func testDirectionalEdgesToDirectionalMargins() {
var fromAttributes = Set<LayoutAttribute>()
var toAttributes = Set<LayoutAttribute>()
let view = View()
self.container.addSubview(view)
view.snp.remakeConstraints { (make) -> Void in
make.directionalEdges.equalTo(self.container.snp.directionalMargins)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
for constraint in (container.snp_constraints as! [NSLayoutConstraint]) {
fromAttributes.insert(constraint.firstAttribute)
toAttributes.insert(constraint.secondAttribute)
}
XCTAssert(fromAttributes == [.top, .leading, .bottom, .trailing])
XCTAssert(toAttributes == [.topMargin, .leadingMargin, .bottomMargin, .trailingMargin])
fromAttributes.removeAll()
toAttributes.removeAll()
view.snp.remakeConstraints { (make) -> Void in
make.directionalMargins.equalTo(self.container.snp.directionalEdges)
}
XCTAssertEqual(self.container.snp_constraints.count, 4, "Should have 4 constraints")
for constraint in (container.snp_constraints as! [NSLayoutConstraint]) {
fromAttributes.insert(constraint.firstAttribute)
toAttributes.insert(constraint.secondAttribute)
}
XCTAssert(toAttributes == [.top, .leading, .bottom, .trailing])
XCTAssert(fromAttributes == [.topMargin, .leadingMargin, .bottomMargin, .trailingMargin])
}
func testLayoutGuideConstraints() {
let vc = UIViewController()
vc.view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
vc.view.addSubview(self.container)
self.container.snp.makeConstraints { (make) -> Void in
make.top.equalTo(vc.topLayoutGuide.snp.bottom)
make.bottom.equalTo(vc.bottomLayoutGuide.snp.top)
}
XCTAssertEqual(vc.view.snp_constraints.count, 2, "Should have 2 constraints installed")
}
#endif
func testCanSetLabel() {
self.container.snp.setLabel("Hello World")
}
func testPriorityShortcuts() {
let view = View()
self.container.addSubview(view)
view.snp.remakeConstraints { make in
make.left.equalTo(1000.0).priority(.required)
}
XCTAssertEqual(self.container.snp_constraints.count, 1, "Should have 1 constraint")
XCTAssertEqual(self.container.snp_constraints.first?.priority, ConstraintPriority.required.value)
view.snp.remakeConstraints { make in
make.left.equalTo(1000.0).priority(.low)
}
XCTAssertEqual(self.container.snp_constraints.count, 1, "Should have 1 constraint")
XCTAssertEqual(self.container.snp_constraints.first?.priority, ConstraintPriority.low.value)
view.snp.remakeConstraints { make in
make.left.equalTo(1000.0).priority(ConstraintPriority.low.value + 1)
}
XCTAssertEqual(self.container.snp_constraints.count, 1, "Should have 1 constraint")
XCTAssertEqual(self.container.snp_constraints.first?.priority, ConstraintPriority.low.value + 1)
}
func testPriorityStride() {
let highPriority: ConstraintPriority = .high
let higherPriority: ConstraintPriority = ConstraintPriority.high.advanced(by: 1)
XCTAssertEqual(higherPriority.value, highPriority.value + 1)
}
}
| 37.50411 | 153 | 0.620096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.