repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
touchopia/HackingWithSwift | project14/Project14/GameScene.swift | 1 | 3351 | //
// GameScene.swift
// Project14
//
// Created by TwoStraws on 18/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import GameplayKit
import SpriteKit
class GameScene: SKScene {
var gameScore: SKLabelNode!
var score: Int = 0 {
didSet {
gameScore.text = "Score: \(score)"
}
}
var slots = [WhackSlot]()
var popupTime = 0.85
var numRounds = 0
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "whackBackground")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .replace
background.zPosition = -1
addChild(background)
gameScore = SKLabelNode(fontNamed: "Chalkduster")
gameScore.text = "Score: 0"
gameScore.position = CGPoint(x: 8, y: 8)
gameScore.horizontalAlignmentMode = .left
gameScore.fontSize = 48
addChild(gameScore)
for i in 0 ..< 5 { createSlot(at: CGPoint(x: 100 + (i * 170), y: 410)) }
for i in 0 ..< 4 { createSlot(at: CGPoint(x: 180 + (i * 170), y: 320)) }
for i in 0 ..< 5 { createSlot(at: CGPoint(x: 100 + (i * 170), y: 230)) }
for i in 0 ..< 4 { createSlot(at: CGPoint(x: 180 + (i * 170), y: 140)) }
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [unowned self] in
self.createEnemy()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let tappedNodes = nodes(at: location)
for node in tappedNodes {
if node.name == "charFriend" {
// they shouldn't have whacked this penguin
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.isVisible { continue }
if whackSlot.isHit { continue }
whackSlot.hit()
score -= 5
run(SKAction.playSoundFileNamed("whackBad.caf", waitForCompletion:false))
} else if node.name == "charEnemy" {
// they should have whacked this one
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.isVisible { continue }
if whackSlot.isHit { continue }
whackSlot.charNode.xScale = 0.85
whackSlot.charNode.yScale = 0.85
whackSlot.hit()
score += 1
run(SKAction.playSoundFileNamed("whack.caf", waitForCompletion:false))
}
}
}
}
func createSlot(at position: CGPoint) {
let slot = WhackSlot()
slot.configure(at: position)
addChild(slot)
slots.append(slot)
}
func createEnemy() {
numRounds += 1
if numRounds >= 30 {
for slot in slots {
slot.hide()
}
let gameOver = SKSpriteNode(imageNamed: "gameOver")
gameOver.position = CGPoint(x: 512, y: 384)
gameOver.zPosition = 1
addChild(gameOver)
return
}
popupTime *= 0.991
slots = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: slots) as! [WhackSlot]
slots[0].show(hideTime: popupTime)
if RandomInt(min: 0, max: 12) > 4 { slots[1].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 8 { slots[2].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 10 { slots[3].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 11 { slots[4].show(hideTime: popupTime) }
let minDelay = popupTime / 2.0
let maxDelay = popupTime * 2
let delay = RandomDouble(min: minDelay, max: maxDelay)
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [unowned self] in
self.createEnemy()
}
}
}
| unlicense | bc53c3f870c4b33e5bf3c3ed115dd072 | 26.235772 | 90 | 0.656119 | 3.346653 | false | false | false | false |
pnhechim/Fiestapp-iOS | Fiestapp/Fiestapp/ViewControllers/Login/LoginViewController.swift | 1 | 3467 | //
// LoginViewController.swift
// fiestapp
//
// Created by Nicolás Hechim on 25/5/17.
// Copyright © 2017 Mint. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import Firebase
class LoginViewController: UIViewController {
var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
@IBOutlet var viewLoginButtons: UIView!
override func viewDidLoad() {
super.viewDidLoad()
viewLoginButtons.applyGradient(colours: [UIColor(red: 0/255, green: 177/255, blue: 255/255, alpha: 1),
UIColor(red: 232/255, green: 0/255, blue: 166/255, alpha: 1)],
locations: [0.0, 1.0])
let currentUser = FIRAuth.auth()?.currentUser
if(currentUser != nil) {
// User is logged in, go to next view controller.
print("User is logged in")
print("photo url facebook: " + (currentUser?.photoURL?.absoluteString)!)
print("user name facebook: " + (currentUser?.displayName!)!)
print("email facebook: " + (currentUser?.email!)!)
let appDelegate = UIApplication.shared.delegate! as! AppDelegate
let initialViewController = self.storyboard!.instantiateViewController(withIdentifier: "HomeTabBarController")
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func facebookLogin(sender: UIButton) {
ProgressOverlayView.shared.showProgressView(self.view)
let fbLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["public_profile", "email"], from: self) { (result, error) in
if let error = error {
print("Failed to login: \(error.localizedDescription)")
return
}
guard let accessToken = FBSDKAccessToken.current() else {
print("Failed to get access token")
return
}
let credential = FIRFacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)
// Perform login by calling Firebase APIs
FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
if let error = error {
print("Login error: \(error.localizedDescription)")
let alertController = UIAlertController(title: "Error de login", message: error.localizedDescription, preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(okayAction)
self.present(alertController, animated: true, completion: nil)
return
}
// Present the main view
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeTabBarController") {
UIApplication.shared.keyWindow?.rootViewController = viewController
self.dismiss(animated: true, completion: nil)
}
})
}
}
}
| mit | 83ed94da466397e287f983a8d5e967aa | 41.777778 | 145 | 0.591342 | 5.625 | false | false | false | false |
radu-costea/ATests | ATests/ATests/Model/PFObject-Additions.swift | 1 | 1369 | //
// ParseContent.swift
// ATests
//
// Created by Radu Costea on 16/06/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
import Parse
protocol CopyableObject: class {
func copyObject() -> PFObject
}
extension PFObject {
func fetchSubEntities(className:String, key: String, inBackgroundWithBlock block: (([PFObject]?, NSError?) -> Void)?) {
let query = PFQuery(className: className)
query.whereKey(key, equalTo: self)
query.findObjectsInBackgroundWithBlock(block)
}
}
extension PFObject: CopyableObject {
func copyObject() -> PFObject {
return PFObject(className: parseClassName)
}
func cleanCopyObject() -> PFObject {
return PFObject(className: parseClassName)
}
}
extension PFObject {
func isValid() -> Bool {
return false
}
public func equalTo(object: AnyObject?) -> Bool {
if let pfObject = object as? PFObject {
return pfObject.objectId == objectId
}
return self.isEqual(object)
}
}
func ==<T: PFObject>(lhs: Array<T>, rhs: Array<T>) -> Bool {
guard lhs.count == rhs.count else {
return false
}
for idx in 0..<lhs.count {
print("comparing variant \(idx)")
guard lhs[idx].equalTo(rhs[idx]) else {
return false
}
}
return true
} | mit | 263b886e2b6a9107085fd036fd48303e | 22.603448 | 123 | 0.61769 | 4.222222 | false | false | false | false |
SakuragiYoshimasa/FluctuateViewController | Demo/Demo/CustomMenuView.swift | 1 | 1165 | //
// CustomMenuView.swift
// Demo
//
// Created by Yoshimasa Sakuragi on 2017/09/26.
// Copyright © 2017年 Yoshimasa Sakuragi. All rights reserved.
//
import UIKit
class CustomMenuView : MenuView {
var buttons: [UIButton] = []
override func recreateMenuViewByContents(dataSource: FluctuateViewDataSource){
backgroundColor = UIColor.colorWithHexString(hex: "E8F0FF")
buttons.forEach({ $0.removeFromSuperview() })
buttons = []
for i in 0..<dataSource.contentsCount() {
let button = UIButton(frame: CGRect(x: i * 120 + 100,y: 100, width: 100, height: 60))
button.backgroundColor = UIColor.colorWithHexString(hex: "000103")
button.setTitleColor(UIColor.colorWithHexString(hex: "DD2D4A"), for: .normal)
button.setTitle("\(i)", for: .normal)
button.tag = i
button.addTarget(self, action: #selector(self.selectContent(_:)), for: .touchUpInside)
buttons.append(button)
addSubview(button)
}
}
@objc func selectContent(_ sender: UIButton) {
select(contentIndex: sender.tag)
}
}
| mit | 757e318f442b586a0e2726e03da234f3 | 32.2 | 98 | 0.623064 | 4.120567 | false | false | false | false |
qualaroo/QualarooSDKiOS | QualarooTests/Interactors/AnswerDropdownInteractorSpec.swift | 1 | 3359 | //
// AnswerDropdownInteractorSpec.swift
// QualarooTests
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class AnswerDropdownInteractorSpec: QuickSpec {
override func spec() {
super.spec()
describe("AnswerDropdownInteractor") {
var builder: SingleSelectionAnswerResponseBuilder!
var buttonHandler: SurveyPresenterMock!
var answerHandler: SurveyInteractorMock!
var interactor: AnswerDropdownInteractor!
var questionDict: [String: Any]!
beforeEach {
let answerList = [JsonLibrary.answer(id: 111),
JsonLibrary.answer(id: 222)]
questionDict = JsonLibrary.question(type: "dropdown",
answerList: answerList)
let question = try! QuestionFactory(with: questionDict).build()
builder = SingleSelectionAnswerResponseBuilder(question: question)
buttonHandler = SurveyPresenterMock()
answerHandler = SurveyInteractorMock()
interactor = AnswerDropdownInteractor(responseBuilder: builder,
buttonHandler: buttonHandler,
answerHandler: answerHandler,
question: question)
}
it("always have button enabled") {
expect(buttonHandler.enableButtonFlag).to(beTrue())
}
it("passes answer to handler") {
expect(answerHandler.answerChangedValue).to(beNil())
interactor.setAnswer(0)
let answer = AnswerResponse(id: 111,
alias: nil,
text: nil)
let model = QuestionResponse(id: 1,
alias: nil,
answerList: [answer])
let response = NodeResponse.question(model)
expect(answerHandler.answerChangedValue).to(equal(response))
}
it("is not passing non-existing answer") {
expect(answerHandler.answerChangedValue).to(beNil())
interactor.setAnswer(3)
expect(answerHandler.answerChangedValue).to(beNil())
}
it("doesn't try to show next node if there is 'Next' button") {
expect(answerHandler.goToNextNodeFlag).to(beFalse())
interactor.setAnswer(0)
expect(answerHandler.goToNextNodeFlag).to(beFalse())
}
it("tries to show next node if there is no 'Next' button") {
questionDict["always_show_send"] = false
let question = try! QuestionFactory(with: questionDict).build()
builder = SingleSelectionAnswerResponseBuilder(question: question)
interactor = AnswerDropdownInteractor(responseBuilder: builder,
buttonHandler: buttonHandler,
answerHandler: answerHandler,
question: question)
expect(answerHandler.goToNextNodeFlag).to(beFalse())
interactor.setAnswer(0)
expect(answerHandler.goToNextNodeFlag).to(beTrue())
}
}
}
}
| mit | f17f255a84c2723af70e6d7cf0dd8e7b | 40.469136 | 75 | 0.599881 | 5.074018 | false | false | false | false |
ykyouhei/KYWheelTabController | KYWheelTabController/Classes/Views/MenuLayer.swift | 1 | 3236 | //
// MenuLayer.swift
// KYWheelTabController
//
// Created by kyo__hei on 2016/02/20.
// Copyright © 2016年 kyo__hei. All rights reserved.
//
import UIKit
internal class MenuLayer: CAShapeLayer {
/* ====================================================================== */
// MARK: Properties
/* ===================================================================== */
let tabBarItem: UITabBarItem
var tintColor: UIColor = UIColor(colorLiteralRed: 0, green: 122/255, blue: 1, alpha: 1) {
didSet {
updateContents()
}
}
var selected = false {
didSet {
updateContents()
}
}
fileprivate let disableColor = UIColor(white: 0.4, alpha: 1)
fileprivate let contentsLayer: CALayer
fileprivate let arcLayer: CAShapeLayer
/* ====================================================================== */
// MARK: initializer
/* ====================================================================== */
init(center: CGPoint,
radius: CGFloat,
startAngle: CGFloat,
endAngle: CGFloat,
tabBarItem: UITabBarItem,
bounds: CGRect,
contentsTransform: CATransform3D)
{
self.tabBarItem = tabBarItem
let scale = UIScreen.main.scale
let arcWidth = CGFloat(5)
let bezierPath = UIBezierPath()
bezierPath.addArc(withCenter: center,
radius: bounds.width/2 - arcWidth/2,
startAngle: startAngle-0.01,
endAngle: endAngle+0.01,
clockwise: true)
arcLayer = CAShapeLayer()
arcLayer.path = bezierPath.cgPath
arcLayer.lineWidth = arcWidth
arcLayer.fillColor = UIColor.clear.cgColor
contentsLayer = CALayer()
contentsLayer.frame = bounds
contentsLayer.contentsGravity = kCAGravityCenter
contentsLayer.contentsScale = scale
contentsLayer.transform = contentsTransform
contentsLayer.rasterizationScale = scale
contentsLayer.shouldRasterize = true
super.init()
let path = UIBezierPath()
path.addArc(withCenter: center,
radius: bounds.width/2,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
path.addLine(to: center)
self.path = path.cgPath
lineWidth = 1
rasterizationScale = scale
shouldRasterize = true
updateContents()
addSublayer(contentsLayer)
addSublayer(arcLayer)
}
internal required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func updateContents() {
if selected {
contentsLayer.contents = tabBarItem.selectedImage?.cgImage
arcLayer.strokeColor = tintColor.cgColor
} else {
contentsLayer.contents = tabBarItem.image?.cgImage
arcLayer.strokeColor = UIColor.clear.cgColor
}
}
}
| mit | 01fe7970861a9bda9df3d86a95fb8ef0 | 28.126126 | 93 | 0.511599 | 5.681898 | false | false | false | false |
calleerlandsson/Tofu | Tofu/AccountsViewController.swift | 1 | 14471 | import UIKit
private let accountOrderKey = "persistentRefs"
class AccountsViewController: UITableViewController {
@IBOutlet weak var emptyView: UIView!
private let keychain = Keychain()
private var accounts = [Account]()
private lazy var searchController = makeSearchController()
private lazy var addAccountAlertController = makeAddAccountAlertController()
override func viewDidLoad() {
super.viewDidLoad()
accounts = keychain.accounts
let sortedPersistentRefs = UserDefaults.standard.array(forKey: accountOrderKey) as? [Data] ?? []
accounts.sort { a, b in
let aIndex = sortedPersistentRefs.firstIndex(of: a.persistentRef! as Data) ?? 0
let bIndex = sortedPersistentRefs.firstIndex(of: b.persistentRef! as Data) ?? 0
return aIndex < bIndex
}
persistAccountOrder()
navigationItem.searchController = searchController
let updater = AccountsTableViewUpdater(tableView: tableView)
updater.startUpdating()
updateEditing()
NotificationCenter.default.addObserver(
self,
selector: #selector(deselectSelectedTableViewRow),
name: UIMenuController.willHideMenuNotification,
object: nil)
}
@objc func deselectSelectedTableViewRow() {
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
@IBAction func addAccount(_ sender: Any) {
present(addAccountAlertController, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let navigationController = segue.destination as? UINavigationController {
if let accountCreationViewController = navigationController.topViewController
as? AccountCreationViewController {
accountCreationViewController.delegate = self
} else {
let scanningViewController = navigationController.topViewController
as! ScanningViewController
scanningViewController.delegate = self
}
} else {
let accountUpdateViewController = segue.destination
as! AccountUpdateViewController
let cell = sender as! AccountCell
accountUpdateViewController.delegate = self
accountUpdateViewController.account = cell.account
}
}
private func makeSearchController() -> UISearchController {
let searchResultsController = storyboard!.instantiateViewController(withIdentifier: "AccountSearchResultsViewController") as! AccountSearchResultsViewController
let searchController = UISearchController(searchResultsController: searchResultsController)
searchController.searchResultsUpdater = self
return searchController
}
private func makeAddAccountAlertController() -> UIAlertController {
let title = "Add Account"
let message = "Add an account by scanning a QR code, importing a QR image, or entering a secret manually."
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let scanQRCode = UIAlertAction(title: "Scan QR Code", style: .default) { [unowned self] _ in
self.performSegue(withIdentifier: "ScanSegue", sender: self)
}
let importQRCode = UIAlertAction(title: "Import QR Image", style: .default) { [unowned self] _ in
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = false
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
} else {
presentErrorAlert(title: "Photo Library Empty",
message: "The photo library is empty and there are no images to import.")
}
}
let enterManually = UIAlertAction(title: "Enter Manually", style: .default) { [unowned self] _ in
self.performSegue(withIdentifier: "EnterManuallySegue", sender: self)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(scanQRCode)
alertController.addAction(importQRCode)
alertController.addAction(enterManually)
alertController.addAction(cancel)
return alertController
}
private func persistAccountOrder() {
let sortedPersistentRefs = accounts.map { $0.persistentRef! }
UserDefaults.standard.set(sortedPersistentRefs, forKey: accountOrderKey)
}
private func updateEditing() {
if accounts.count == 0 {
tableView.backgroundView = emptyView
tableView.separatorStyle = .none
navigationItem.leftBarButtonItem = nil
setEditing(false, animated: true)
} else {
tableView.backgroundView = nil
tableView.separatorStyle = .singleLine
navigationItem.leftBarButtonItem = editButtonItem
}
}
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) ->
Bool {
return true
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath) {
accounts.insert(accounts.remove(at: sourceIndexPath.row),
at: destinationIndexPath.row)
persistAccountOrder()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return accounts.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AccountCell",
for: indexPath) as! AccountCell
cell.account = accounts[indexPath.row]
cell.delegate = self
return cell
}
override func tableView(
_ tableView: UITableView,
commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let alertController = UIAlertController(
title: "Deleting This Account Will Not Turn Off Two-Factor Authentication",
message: "Please make sure two-factor authentication is turned off in the issuer's sett" +
"ings before deleting this account to prevent being locked out.",
preferredStyle: .actionSheet)
let deleteAccountAction = UIAlertAction(title: "Delete Account", style: .destructive) { _ in
self.deleteAccountForRowAtIndexPath(indexPath)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(deleteAccountAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
}
private func deleteAccountForRowAtIndexPath(_ indexPath: IndexPath) {
let account = self.accounts[indexPath.row]
guard self.keychain.deleteAccount(account) else {
presentTryAgainAlertWithTitle(
"Could Not Delete Account",
message: "An error occurred when deleting the account from the keychain.") {
self.deleteAccountForRowAtIndexPath(indexPath)
}
return
}
accounts.remove(at: indexPath.row)
persistAccountOrder()
tableView.deleteRows(at: [indexPath], with: .automatic)
updateEditing()
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.isEditing {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) as? AccountCell {
performSegue(withIdentifier: "EditAccountSegue", sender: cell)
}
} else { // Not editing
if let cell = tableView.cellForRow(at: indexPath) {
guard let cellSuperview = cell.superview else {
assertionFailure("The cell does not seem to be in the view hierarchy. How is that even possible!?")
return
}
let menuController = UIMenuController.shared
// If you tap the same cell twice, this condition prevents the menu from being
// hidden and then instantly shown again causing an unpleasant flash.
//
// Since the cell could already be the first responder (from previously showing
// its menu and then scrolling the table view) and the menu could already be
// visible for another cell, we make sure to check both values.
if !(cell.isFirstResponder && menuController.isMenuVisible) {
cell.becomeFirstResponder()
menuController.showMenu(from: cellSuperview, rect: cell.frame)
}
}
}
}
override func tableView(_ tableView: UITableView,
shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, canPerformAction action: Selector,
forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return action == #selector(copy(_:))
}
override func tableView(_ tableView: UITableView, performAction action: Selector,
forRowAt indexPath: IndexPath, withSender sender: Any?) {
if action == #selector(copy(_:)) {
let cell = tableView.cellForRow(at: indexPath) as! AccountCell
cell.copy(self)
}
}
}
extension AccountsViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let accountSearchResultsViewController = searchController.searchResultsController
as! AccountSearchResultsViewController
accountSearchResultsViewController.accounts = accounts.filter {
guard let string = searchController.searchBar.text else { return false }
return $0.description.range(of: string, options: .caseInsensitive, range: nil,
locale: nil) != nil
}
}
}
extension AccountsViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
guard let selectedQRCode = info[UIImagePickerController.InfoKey.originalImage] as? UIImage,
let detector = CIDetector(ofType: CIDetectorTypeQRCode,
context: nil,
options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]),
let ciImage = CIImage(image: selectedQRCode),
let features = detector.features(in: ciImage) as? [CIQRCodeFeature],
let messageString = features.first?.messageString else {
presentErrorAlert(title: "Could Not Detect QR Code",
message: "No QR code was detected in the provided image. Please try importing a different image.")
return
}
guard let qrCodeURL = URL(string: messageString),
let account = Account(url: qrCodeURL) else {
presentErrorAlert(title: "Invalid QR Code",
message: "The QR code detected in the provided image is invalid. Please try a different image.")
return
}
self.createAccount(account)
}
}
extension AccountsViewController: AccountCreationDelegate {
func createAccount(_ account: Account) {
guard keychain.insertAccount(account) else {
presentTryAgainAlertWithTitle(
"Could Not Create Account",
message: "An error occurred when inserting the account into the keychain.") {
self.createAccount(account)
}
return
}
accounts.append(account)
persistAccountOrder()
let lastRow = accounts.count - 1
let indexPaths = [IndexPath(row: lastRow, section: 0)]
tableView.insertRows(at: indexPaths, with: .automatic)
updateEditing()
}
}
extension AccountsViewController: AccountUpdateDelegate {
func updateAccount(_ account: Account) {
guard keychain.updateAccount(account) else {
presentTryAgainAlertWithTitle(
"Could Not Update Account",
message: "An error occurred when persisting the account updates to the keychain.") {
self.updateAccount(account)
}
return
}
let row = accounts.firstIndex { $0 === account }!
let indexPath = IndexPath(row: row, section: 0)
guard let cell = tableView.cellForRow(at: indexPath) as? AccountCell else { return }
cell.updateWithDate(Date())
}
private func presentTryAgainAlertWithTitle(_ title: String, message: String, handler: @escaping () -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let tryAgainAccountAction = UIAlertAction(title: "Try again", style: .default) { _ in
handler()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(tryAgainAccountAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
}
| isc | 47c22881d7e85efcd5ac563c0553cd93 | 40.823699 | 168 | 0.636929 | 5.828031 | false | false | false | false |
terhechte/OctoTrend.swift | OctoTrend.swiftTests/OctoTrend_swiftTests.swift | 1 | 3569 | //
// OctoTrend_swiftTests.swift
// OctoTrend.swiftTests
//
// Created by Benedikt Terhechte on 03/08/15.
// Copyright © 2015 Benedikt Terhechte. All rights reserved.
//
import XCTest
@testable import OctoTrend
class OctoTrend_swiftTests: 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 testGotData() {
// Test whether receiving and parsing data from the github server works.
// performs an actual http request
let readyExpectation = expectationWithDescription("got data")
trends(language: "swift", timeline: TrendingTimeline.Today) { (result) -> () in
switch result {
case .Failure(let e):
XCTAssert(false, e.errorString())
case .Success(let s):
//print("result: \(s)")
readyExpectation.fulfill()
}
}
waitForExpectationsWithTimeout(20, handler: { (e) -> Void in
XCTAssertNil(e, "Error")
})
}
func testParseData() {
// uses the trending.html to make sure that the data is parsed correctly
let dataPath = NSBundle(forClass: self.classForCoder).pathForResource("trending", ofType: "html")
if let dataPath = dataPath,
data = NSData(contentsOfFile: dataPath) {
let result = OctoTrend.parseTrendsHTML(data)
switch result {
case .Failure(let e):
XCTAssert(false, e.errorString())
case .Success(let s):
guard let firstRepo = s.first else { XCTAssert(false, "No Items"); return }
XCTAssertEqual(firstRepo.name, "Palleas/NaughtyKeyboard", "Did not parse name correctly")
XCTAssertEqual(firstRepo.developers.count, 2, "Did not parse developers correctly")
guard let firstDeveloper = firstRepo.developers.first else { XCTAssert(false, "No First Developer"); return }
XCTAssertEqual(firstDeveloper.name, "Palleas", "Did not parse developers correctly")
XCTAssertEqual(firstRepo.stars, 173, "Did not parse stars correctly")
XCTAssertEqual(firstRepo.text, "The Big List of Naughty Strings is a list of strings which have a high probability of causing issues when used as user-input data. This is a keyboard to help you test your app from your iOS device.", "Did not parse text correctly")
guard let lastRepo = s.last else { XCTAssert(false, "No Items"); return }
XCTAssertEqual(lastRepo.url.absoluteString, "https://github.com/remaerd/Keys", "Did not parse url correctly")
// The last repo has no "builders" listed, so it should correctly return the empty array here...
XCTAssertEqual(lastRepo.developers.count, 0, "Did not parse developer count correctly")
}
} else {
XCTAssert(false, "Could not find html data")
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit | afaf4f6a07f2db533d34336473a15a22 | 44.164557 | 283 | 0.602859 | 4.90784 | false | true | false | false |
khoren93/SwiftHub | SwiftHub/Managers/AuthManager.swift | 1 | 1471 | //
// AuthManager.swift
// SwiftHub
//
// Created by Sygnoos9 on 9/1/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import Foundation
import KeychainAccess
import ObjectMapper
import RxSwift
import RxCocoa
let loggedIn = BehaviorRelay<Bool>(value: false)
class AuthManager {
/// The default singleton instance.
static let shared = AuthManager()
// MARK: - Properties
fileprivate let tokenKey = "TokenKey"
fileprivate let keychain = Keychain(service: Configs.App.bundleIdentifier)
let tokenChanged = PublishSubject<Token?>()
init() {
loggedIn.accept(hasValidToken)
}
var token: Token? {
get {
guard let jsonString = keychain[tokenKey] else { return nil }
return Mapper<Token>().map(JSONString: jsonString)
}
set {
if let token = newValue, let jsonString = token.toJSONString() {
keychain[tokenKey] = jsonString
} else {
keychain[tokenKey] = nil
}
tokenChanged.onNext(newValue)
loggedIn.accept(hasValidToken)
}
}
var hasValidToken: Bool {
return token?.isValid == true
}
class func setToken(token: Token) {
AuthManager.shared.token = token
}
class func removeToken() {
AuthManager.shared.token = nil
}
class func tokenValidated() {
AuthManager.shared.token?.isValid = true
}
}
| mit | f72a74799307e322dd812ead0d110f70 | 22.333333 | 78 | 0.614966 | 4.565217 | false | false | false | false |
SteerClearWM/Steer-Clear-IOS | Steer ClearTests/SCNetworkTests.swift | 2 | 18067 | //
// SCNetworkTests.swift
// Steer Clear
//
// Created by Ryan Beatty on 8/18/15.
// Copyright (c) 2015 Steer-Clear. All rights reserved.
//
import UIKit
import XCTest
import OHHTTPStubs
/*
SCNetworkBaseTestCase
---------------------
Base test class for network tests
*/
class SCNetworkBaseTestCase: 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()
OHHTTPStubs.removeAllStubs()
}
/*
_stub
-----
Stubs out a network request with the passed in status code
:responseStatusCode: The status code the response should return
*/
func _stub(responseStatusCode: Int32) -> OHHTTPStubsDescriptor {
// stub out network request to server register route
let stub = OHHTTPStubs.stubRequestsPassingTest({
request in
return request.URL!.host == "127.0.0.1"
}, withStubResponse: {
_ in
let stubData = "Hello World".dataUsingEncoding(NSUTF8StringEncoding)
return OHHTTPStubsResponse(data: stubData!, statusCode: responseStatusCode, headers: nil)
})
return stub
}
/*
_stubBadNetwork
---------------
Simulates the network being down
*/
func _stubBadNetwork() {
// stub out the entire network
OHHTTPStubs.stubRequestsPassingTest({
request in
return request.URL!.host == "127.0.0.1"
}, withStubResponse: {
_ in
// NOTE: -1009 actually stands for the constant kCFURLErrorNotConnectedToInternet in CFNetwork
// but I couldn't get swift to recognize the name, so I just used the value
let notConnectedError = NSError(domain:NSURLErrorDomain, code:-1009, userInfo:nil)
return OHHTTPStubsResponse(error:notConnectedError)
})
}
}
/*
RegisterTestCase
----------------
Tests the SCNetwork.register function
*/
class RegisterTestCase: SCNetworkBaseTestCase {
/*
testRegisterFailureBadNetwork
-----------------------------
Tests that the register function can handle the network being down
*/
func testRegisterFailureBadNetwork() {
self._stubBadNetwork()
self._performRegisterTest(false, responseMessage: "There was a network error while registering")
}
/*
testRegisterFailureBadStatusCode
--------------------------------
Tests that registering fails, if the response status code is not 200
*/
func testRegisterFailureBadStatusCode() {
// simulate if the username already exists
self._stub(409)
self._performRegisterTest(false, responseMessage: "The username or phone you specified already exists")
// simulate if user entered register credentials incorrectly
self._stub(400)
self._performRegisterTest(
false,
responseMessage: "The username, password, or phone number were entered incorrectly"
)
// simulate some random internal server error
self._stub(500)
self._performRegisterTest(false, responseMessage: "There was an error while registering")
}
/*
testRegisterSuccess
-------------------
Tests that we can successsfully register a user into the system
*/
func testRegisterSuccess() {
self._stub(200)
self._performRegisterTest(true, responseMessage: "Registered!")
}
/*
_performRegisterTest
--------------------
Perform a test of the register function
:responseSuccess: the success flag the test request should return
:responseMessage: the message string the test request should return
*/
func _performRegisterTest(responseSuccess: Bool, responseMessage: String) {
// create expectation for testing
let expectation = self.expectationWithDescription("response of post request arrived")
// make request
SCNetwork.register(
"foo",
password: "bar",
phone: "baz",
completionHandler: {
success, message in
// assert that register succeeded
XCTAssertEqual(success, responseSuccess)
XCTAssertEqual(message, responseMessage)
expectation.fulfill()
})
// wait for response to finish
waitForExpectationsWithTimeout(10, handler: {
error in
if (error != nil) {
print("Error: \(error!.localizedDescription)")
}
})
}
}
/*
LoginTestCase
-------------
Tests for the SCNetwork.login function
*/
class LoginTestCase: SCNetworkBaseTestCase {
/*
testLoginFailureBadNetwork
--------------------------
Tests that the login function handles the network being down
*/
func testLoginFailureBadNetwork() {
self._stubBadNetwork()
self._performLoginTest(
"foo",
password: "bar",
responseSuccess: false,
responseMessage: "There was a network error while logging in"
)
}
/*
testLoginFailureBadStatusCode
-----------------------------
Tests that login function handles bad status codes correctly
*/
func testLoginFailureBadStatusCode() {
// simulate if the user does not exist
self._stub(400)
self._performLoginTest(
"foo",
password: "bar",
responseSuccess: false,
responseMessage: "Invalid username or password"
)
// simulate if there is an internal server error
self._stub(500)
self._performLoginTest(
"foo",
password: "bar",
responseSuccess: false,
responseMessage: "There was an error while logging in"
)
}
/*
testLoginSuccess
----------------
Tests that a user can successfully login
*/
func testLoginSuccess() {
self._stub(200)
self._performLoginTest(
"foo",
password: "bar",
responseSuccess: true,
responseMessage: "Logged in!"
)
}
/*
_performLoginTest
--------------------
Perform a test of the login function
:responseSuccess: the success flag the test request should return
:responseMessage: the message string the test request should return
*/
func _performLoginTest(username: String, password: String, responseSuccess: Bool, responseMessage: String) {
// create expectation for testing
let expectation = self.expectationWithDescription("response of post request arrived")
// make request
SCNetwork.login(
username,
password: password,
completionHandler: {
success, message in
// assert that register succeeded
XCTAssertEqual(success, responseSuccess)
XCTAssertEqual(message, responseMessage)
expectation.fulfill()
})
// wait for response to finish
waitForExpectationsWithTimeout(10, handler: {
error in
if (error != nil) {
print("Error: \(error!.localizedDescription)")
}
})
}
}
class RequestRideTestCase: SCNetworkBaseTestCase {
/*
testRequestRideFailureBadNetwork
--------------------------------
Tests that the ride request function handles
the network being down
*/
func testRequestRideFailureBadNetwork() {
self._stubBadNetwork()
self._performRideRequestTest(
"1.0",
startLong: "2.0",
endLat: "3.0",
endLong: "4.0",
numPassengers: "4",
responseSuccess: false,
responseNeedLogin: false,
responseMessage: "There was a network error while requesting a ride",
responseRide: nil
)
}
/*
testRequestRideBadStatusCodes
-----------------------------
Tests that request ride function handles bad status codes
*/
func testRequestRideBadStatusCodes() {
// simulate form submission erro
self._stub(400)
self._performRideRequestTest(
"1.0",
startLong: "2.0",
endLat: "3.0",
endLong: "4.0",
numPassengers: "4",
responseSuccess: false,
responseNeedLogin: false,
responseMessage: "You've entered some ride information incorrectly",
responseRide: nil
)
// simulate user not logged in
self._stub(401)
self._performRideRequestTest(
"1.0",
startLong: "2.0",
endLat: "3.0",
endLong: "4.0",
numPassengers: "4",
responseSuccess: false,
responseNeedLogin: true,
responseMessage: "Please Login",
responseRide: nil
)
// simulate internal server error
self._stub(500)
self._performRideRequestTest(
"1.0",
startLong: "2.0",
endLat: "3.0",
endLong: "4.0",
numPassengers: "4",
responseSuccess: false,
responseNeedLogin: false,
responseMessage: "There was an error while requesting a ride",
responseRide: nil
)
}
/*
*/
// func testRequestRideFailureBadResponse() {
// // stub out network request to server register route
// var stub = OHHTTPStubs.stubRequestsPassingTest({
// request in
// return request.URL!.host == "127.0.0.1"
// }, withStubResponse: {
// _ in
// let stubJSON = ["ride": [
// "num_passengers": 3,
// "start_latitude": 37.2735,
// "start_longitude": -76.7196,
// "end_latitude": 37.2809,
// "end_longitude": -76.7197,
// "pickup_time": "pickup_time': u'Sat, 22 Aug 2015 22:05:56 -0000",
// "travel_time": 239,
// "dropoff_time": "Sat, 22 Aug 2015 22:09:55 -0000",
// "pickup_address": "2006 Brooks Street, Williamsburg, VA 23185, USA",
// "dropoff_address": "1234 Richmond Road, Williamsburg, VA 23185, USA",
// "on_campus": true
// ]
// ]
// return OHHTTPStubsResponse(JSONObject: stubJSON, statusCode: 201, headers: nil)
// })
//
// self._performRideRequestTest(
// "1.0",
// startLong: "2.0",
// endLat: "3.0",
// endLong: "4.0",
// numPassengers: "4",
// responseSuccess: false,
// responseNeedLogin: false,
// responseMessage: "There was an error while requesting a ride",
// responseRide: nil
// )
// }
/*
testRequestRideSuccess
----------------------
Test that ride request can succeed
*/
func testRequestRideSuccess() {
// stub out network request to server register route
_ = OHHTTPStubs.stubRequestsPassingTest({
request in
return request.URL!.host == "127.0.0.1"
}, withStubResponse: {
_ in
let stubJSON = ["ride": [
"id": 1,
"num_passengers": 3,
"start_latitude": 37.2735,
"start_longitude": -76.7196,
"end_latitude": 37.2809,
"end_longitude": -76.7197,
"pickup_time": "pickup_time': u'Sat, 22 Aug 2015 22:05:56 -0000",
"travel_time": 239,
"dropoff_time": "Sat, 22 Aug 2015 22:09:55 -0000",
"pickup_address": "2006 Brooks Street, Williamsburg, VA 23185, USA",
"dropoff_address": "1234 Richmond Road, Williamsburg, VA 23185, USA",
"on_campus": true
]
]
return OHHTTPStubsResponse(JSONObject: stubJSON, statusCode: 201, headers: nil)
})
// build correct ride object response
let ride = Ride(id: 1, numPassengers: 3, pickupAddress: "2006 Brooks Street, Williamsburg, VA 23185, USA", dropoffAddress: "1234 Richmond Road, Williamsburg, VA 23185, USA", pickupTime: "pickup_time': u'Sat, 22 Aug 2015 22:05:56 -0000")
self._performRideRequestTest(
"1.0",
startLong: "2.0",
endLat: "3.0",
endLong: "4.0",
numPassengers: "4",
responseSuccess: true,
responseNeedLogin: false,
responseMessage: "Ride requested!",
responseRide: ride
)
}
/*
_performRideRequestTest
-----------------------
Perform a ride request
*/
func _performRideRequestTest(startLat: String, startLong: String, endLat: String, endLong: String, numPassengers: String, responseSuccess: Bool, responseNeedLogin: Bool, responseMessage: String, responseRide: Ride?) {
// create expectation for testing
let expectation = self.expectationWithDescription("response of post request arrived")
// make request
SCNetwork.requestRide(
startLat,
startLong: startLong,
endLat: endLat,
endLong: endLong,
numPassengers: numPassengers,
completionHandler: {
success, needLogin, message, ride in
// assert that ride request succeeded
XCTAssertEqual(success, responseSuccess)
XCTAssertEqual(needLogin, responseNeedLogin)
XCTAssertEqual(message, responseMessage)
if responseRide == nil {
XCTAssertNil(ride)
}
else {
XCTAssertNotNil(ride)
XCTAssertEqual(ride!, responseRide!)
}
expectation.fulfill()
})
// wait for response to finish
waitForExpectationsWithTimeout(10, handler: {
error in
if (error != nil) {
print("Error: \(error!.localizedDescription)")
}
})
}
}
class DeleteTestCase: SCNetworkBaseTestCase {
/*
testLoginFailureBadNetwork
--------------------------
Tests that the delete ride function handles the network being down
*/
func testLoginFailureBadNetwork() {
self._stubBadNetwork()
self._performDeleteTest(
"1",
responseSuccess: false,
responseMessage: "There was a network error while canceling your ride request"
)
}
/*
testDeleteFailureBadStatusCode
-----------------------------
Tests that delete ride function handles bad status codes correctly
*/
func testLoginFailureBadStatusCode() {
// simulate if the user does not exist
self._stub(404)
self._performDeleteTest(
"1",
responseSuccess: false,
responseMessage: "You have no current ride requests"
)
// user doesn't have permission to access resource
self._stub(403)
self._performDeleteTest(
"1",
responseSuccess: false,
responseMessage: "There was an error while canceling your ride request"
)
// simulate if there is an internal server error
self._stub(500)
self._performDeleteTest(
"1",
responseSuccess: false,
responseMessage: "There was an error while canceling your ride request"
)
}
/*
testDeleteSuccess
-----------------
Tests that delete ride function can succeed
*/
func testDeleteSuccess() {
self._stub(204)
self._performDeleteTest("1", responseSuccess: true, responseMessage: "Canceled your ride request!")
}
/*
_performDeleteTest
--------------------
Perform a test of the delete ride function
:responseSuccess: the success flag the test request should return
:responseMessage: the message string the test request should return
*/
func _performDeleteTest(id: String, responseSuccess: Bool, responseMessage: String) {
// create expectation for testing
let expectation = self.expectationWithDescription("response of post request arrived")
// make request
SCNetwork.deleteRideWithId(
id,
completionHandler: {
success, message in
// assert that register succeeded
XCTAssertEqual(success, responseSuccess)
XCTAssertEqual(message, responseMessage)
expectation.fulfill()
})
// wait for response to finish
waitForExpectationsWithTimeout(10, handler: {
error in
if (error != nil) {
print("Error: \(error!.localizedDescription)")
}
})
}
}
| mit | 165dcd92aaee721ea695e0ba157f5da5 | 31.611913 | 244 | 0.537499 | 5.290483 | false | true | false | false |
JohnCoates/Aerial | Resources/MainUI/Infos panels/HelpViewController.swift | 1 | 1143 | //
// HelpViewController.swift
// Aerial
//
// Created by Guillaume Louel on 25/07/2020.
// Copyright © 2020 Guillaume Louel. All rights reserved.
//
import Cocoa
class HelpViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
@IBAction func faqButton(_ sender: Any) {
let workspace = NSWorkspace.shared
let url = URL(string: "https://aerialscreensaver.github.io/faq.html")!
workspace.open(url)
}
@IBAction func troubleshootButton(_ sender: Any) {
let workspace = NSWorkspace.shared
let url = URL(string: "https://aerialscreensaver.github.io/troubleshooting.html")!
workspace.open(url)
}
@IBAction func issuesButton(_ sender: Any) {
let workspace = NSWorkspace.shared
let url = URL(string: "https://github.com/JohnCoates/Aerial/issues")!
workspace.open(url)
}
@IBAction func visitDiscordClick(_ sender: Any) {
let workspace = NSWorkspace.shared
let url = URL(string: "https://discord.gg/TPuA5WG")!
workspace.open(url)
}
}
| mit | ee875245c8620d35a1af541aafa977db | 26.190476 | 90 | 0.641856 | 4.007018 | false | false | false | false |
germc/IBM-Ready-App-for-Retail | iOS/ReadyAppRetail/ReadyAppRetail/Utilities/Utils.swift | 2 | 3764 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import Foundation
/**
* Utility class primarily for formatting data to be sent to a hyrbrid view.
*/
class Utils {
/**
This method creates a short angular script to alter data in a hybrid view
:param: functionCall the function to be called in the javascript with arguments included in the string
:returns: a clean script to inject into the javascript
*/
class func prepareCodeInjectionString(functionCall: String) -> String {
return "var scope = angular.element(document.getElementById('scope')).scope(); scope." + functionCall + ";"
}
/**
function to produce UIColor from hex values
:param: rgbValue
:param: alpha
:returns: UIColor
*/
class func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
/**
This method returns the green summit color
:returns: the green summit UIColor
*/
class func SummitColor()->UIColor{
var hexColor = UInt32(0x005448)
return UIColorFromHex(hexColor, alpha: 1.0)
}
/**
This method shows a progress hud using SVProgressHUD
*/
class func showProgressHud(){
SVProgressHUD.setForegroundColor(SummitColor())
//SVProgressHUD.setBackgroundColor(UIColor.lightGrayColor())
SVProgressHUD.show()
}
/**
This method dismisses the progress hud (SVProgressHUD)
*/
class func dismissProgressHud(){
SVProgressHUD.dismiss()
}
/**
This method shows a server error alert
:param: delegate
:param: tag
*/
class func showServerErrorAlert(delegate : UIViewController, tag : Int){
var alert = UIAlertView()
alert.delegate = delegate
alert.tag = tag
alert.title = NSLocalizedString("Can't Connect To Server", comment:"")
alert.addButtonWithTitle("Retry")
alert.show()
}
/**
This method shows a server error alert with a cancel button option on the alert
:param: delegate
:param: tag
*/
class func showServerErrorAlertWithCancel(delegate : UIViewController, tag : Int){
var alert = UIAlertView()
alert.delegate = delegate
alert.tag = tag
alert.title = NSLocalizedString("Can't Connect To Server", comment:"")
alert.addButtonWithTitle("Cancel")
alert.addButtonWithTitle("Retry")
alert.show()
}
/**
This method reads from info.plist to find out of the app is in development mode or not. This is needed to disable MQA
:returns: whether the app is in development mode or not
*/
class func isDevelopment() -> Bool{
var configurationPath = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")
if((configurationPath) != nil) {
var configuration = NSDictionary(contentsOfFile: configurationPath!)!
if let isDevelopment = configuration["isDevelopment"] as? NSString{
if(isDevelopment == "true"){
return true
}
else{
return false
}
}
else{
return false
}
}
else{
return false
}
}
} | epl-1.0 | 6c12ae810ae3a52546eaf093931e25e1 | 26.079137 | 121 | 0.587563 | 5.085135 | false | false | false | false |
dbsystel/DBNetworkStack | Source/NetworkError.swift | 1 | 4151 | //
// Copyright (C) 2017 DB Systel GmbH.
// DB Systel GmbH; Jürgen-Ponto-Platz 1; D-60329 Frankfurt am Main; Germany; http://www.dbsystel.de/
//
// 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
/// `NetworkError` provides a collection of error types which can occur during execution.
public enum NetworkError: Error {
/// The error is unkonw
case unknownError
/// The request was cancelled before it finished
case cancelled
/// Missing authorization for the request (HTTP Error 401)
case unauthorized(response: HTTPURLResponse, data: Data?)
/// Invalid payload was send to the server (HTTP Error 400...451)
case clientError(response: HTTPURLResponse?, data: Data?)
/// Error on the server (HTTP Error 500...511)
case serverError(response: HTTPURLResponse?, data: Data?)
/// Parsing the body into expected type failed.
case serializationError(error: Error, data: Data?)
/// Complete request failed.
case requestError(error: Error)
public init?(response: HTTPURLResponse?, data: Data?) {
guard let response = response else {
return nil
}
switch response.statusCode {
case 200..<300: return nil
case 401:
self = .unauthorized(response: response, data: data)
case 400...451:
self = .clientError(response: response, data: data)
case 500...511:
self = .serverError(response: response, data: data)
default:
return nil
}
}
}
extension String {
fileprivate func appendingContentsOf(data: Data?) -> String {
if let data = data, let string = String(data: data, encoding: .utf8) {
return self.appending(string)
}
return self
}
}
extension NetworkError: CustomDebugStringConvertible {
/// Details description of the error.
public var debugDescription: String {
switch self {
case .unknownError:
return "Unknown error"
case .cancelled:
return "Request cancelled"
case .unauthorized(let response, let data):
return "Authorization error: \(response), response: ".appendingContentsOf(data: data)
case .clientError(let response, let data):
if let response = response {
return "Client error: \((response)), response: ".appendingContentsOf(data: data)
}
return "Client error, response: ".appendingContentsOf(data: data)
case .serializationError(let description, let data):
return "Serialization error: \(description), response: ".appendingContentsOf(data: data)
case .requestError(let error):
return "Request error: \(error)"
case .serverError(let response, let data):
if let response = response {
return "Server error: \(String(describing: response)), response: ".appendingContentsOf(data: data)
} else {
return "Server error: nil, response: ".appendingContentsOf(data: data)
}
}
}
}
| mit | 882d1dd0a0b3533b99a885244a04e6a7 | 40.5 | 114 | 0.66 | 4.657688 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Category/Views/CategoriesCell.swift | 1 | 3363 | //
// CategoriesCell.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/16/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
class CategoriesCell: UICollectionViewCell {
@IBOutlet weak var topicNameLabel: UILabel!
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.dataSource = self
collectionView.delegate = self
}
override func prepareForReuse() {
topicNameLabel.text = ""
}
var name: String = "" {
didSet {
topicNameLabel.text = name
}
}
var categories: [Category] = [] {
didSet {
collectionView.reloadData()
}
}
var item: Int!
weak var delegate: CategoriesCellDelegate?
func selectAtItem(_ item: Int, animated: Bool = true) {
collectionView.selectItem(at: IndexPath(item: item, section: 0), animated: animated, scrollPosition: [])
}
func deselectAtItem(_ item: Int, animated: Bool = true) {
collectionView.deselectItem(at: IndexPath(item: item, section: 0), animated: animated)
}
}
extension CategoriesCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CategoryCell.self), for: indexPath) as! CategoryCell
let category = categories[indexPath.item]
cell.name = category.name
return cell
}
}
extension CategoriesCell: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.categoriesCell(self, didSelectAtItem: indexPath.item)
}
}
extension CategoriesCell: UICollectionViewDelegateFlowLayout {
private var itemsPerRow: Int { return 3 }
private var itemsPerColumn: Int { return 3 }
private var rowPadding: CGFloat { return 10 }
private var columnPadding: CGFloat { return 10 }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = collectionView.bounds.size
let width = (size.width - CGFloat(itemsPerRow + 1) * rowPadding) / CGFloat(itemsPerRow)
let height = (size.height - CGFloat(itemsPerColumn + 1) * columnPadding) / CGFloat(itemsPerColumn)
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return rowPadding
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return columnPadding
}
}
protocol CategoriesCellDelegate: class {
func categoriesCell(_ cell: CategoriesCell, didSelectAtItem item: Int)
}
| mit | 42bf91b53358829d29d34bcb6b272807 | 30.679245 | 175 | 0.682251 | 5.3728 | false | false | false | false |
falcon283/SwiftMVVMPattern | MVVMKitSample/UserCellPresenter.swift | 1 | 1514 | //
// UserCellPresenter.swift
// MVVMKit
//
// Created by FaLcON2 on 02/08/2017.
// Copyright © 2017 Gabriele Trabucco. All rights reserved.
//
import UIKit
import SwiftMVVMPattern
class UserCellFullNamePresenter : Presenter<UserCell, UserViewModel> {
override func update(view: UserCell, with viewModel: UserViewModel) {
view.nameLabel?.text = viewModel.name
view.nameLabel?.textColor = UIColor.blue
view.surnameLabel?.text = viewModel.surname
view.surnameLabel?.textColor = UIColor.red
}
}
class UserCellNamePresenter : Presenter<UserCell, UserViewModel> {
override func update(view: UserCell, with viewModel: UserViewModel) {
view.nameLabel?.text = "\(viewModel.name) \(viewModel.surname)"
view.nameLabel?.textColor = UIColor.green
}
}
class GenderFullNamePresenter : Presenter<UserCell, UserViewModel> {
override func update(view: UserCell, with viewModel: UserViewModel) {
view.nameLabel?.text = viewModel.name
view.surnameLabel?.text = viewModel.surname
view.contentView.backgroundColor = viewModel.gender.genderCellColor
}
}
extension UserViewModel.Gender {
var genderCellColor: UIColor {
switch self {
case .female:
return #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
case .male:
return #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
}
}
}
| mit | 29b8691ef06a3031ee01af7a12f46d3a | 29.877551 | 102 | 0.684071 | 4.111413 | false | false | false | false |
moritzsternemann/SwipyCell | PlaygroundBook/SwipyCell.playgroundbook/Contents/Chapters/Document1.playgroundchapter/Pages/03.playgroundpage/Contents.swift | 1 | 7569 | //#-hidden-code
import UIKit
import PlaygroundSupport
public class HowToViewController: GradientViewController, UITableViewDataSource, UITableViewDelegate {
private struct AssessmentStatus {
var states: Set<SwipyCellState> = []
var toggle: Bool = false
var exit: Bool = false
}
private var assessmentStatus = AssessmentStatus()
private let tableView = UITableView()
private let initialNumberItems = 1
private var numberItems: Int = 0
private var cellToDelete: SwipyCell? = nil
var checkView: UIView!
var greenColor: UIColor!
var crossView: UIView!
var redColor: UIColor!
var clockView: UIView!
var yellowColor: UIColor!
var listView: UIView!
var brownColor: UIColor!
public override init() {
super.init()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
numberItems = initialNumberItems
setupSubviews()
tableView.dataSource = self
tableView.delegate = self
tableView.allowsSelection = false
tableView.clipsToBounds = true
tableView.layer.shadowColor = UIColor.black.cgColor
tableView.layer.shadowOpacity = 0.2
tableView.layer.shadowOffset = .zero
tableView.layer.shadowRadius = 10
tableView.tableFooterView = UIView()
let backgroundView = UIView(frame: tableView.frame)
backgroundView.backgroundColor = .white
tableView.backgroundView = backgroundView
//#-end-hidden-code
/*:
# So Many Possibilities
Now that you know the basics about SwipyCell, we can focus on the cooler and more advanced stuff.
You can add as many **swipe triggers** as there are *trigger points* set-up (no need to worry about that just now, more info available on [GitHub](https://github.com/moritzsternemann/SwipyCell/tree/3.0.1#trigger-points)), customize all the **icons and colors**, choose from **two different modes** and much more to customzie the look and feel.
First I added some more icons and colors you can use:
*/
checkView = UIImageView(imageNamed: "check")
crossView = UIImageView(imageNamed: "cross")
clockView = UIImageView(imageNamed: "clock")
listView = UIImageView(imageNamed: "list")
greenColor = #colorLiteral(red: 0.3333333333, green: 0.8352941176, blue: 0.3137254902, alpha: 1)
redColor = #colorLiteral(red: 0.9098039216, green: 0.2392156863, blue: 0.05490196078, alpha: 1)
yellowColor = #colorLiteral(red: 0.9960784314, green: 0.8509803922, blue: 0.2196078431, alpha: 1)
brownColor = #colorLiteral(red: 0.8078431373, green: 0.5843137255, blue: 0.3843137255, alpha: 1)
//#-hidden-code
}
private func setupSubviews() {
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
let wc = tableView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.9)
wc.priority = 750
wc.isActive = true
tableView.widthAnchor.constraint(lessThanOrEqualToConstant: 375).isActive = true
tableView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
let hc = tableView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5)
hc.priority = 750
hc.isActive = true
tableView.heightAnchor.constraint(lessThanOrEqualToConstant: 667).isActive = true
tableView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
// MARK: TableView DataSource & Delegate
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberItems
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return Constants.cellHeight
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = SwipyCell()
cell.textLabel?.text = "Swipe me! ✌️"
//#-end-hidden-code
/*:
I've added the same cell you created earlier.
Try out at least four states and all modes you can set triggers for!
As you've see before, the states which refer to existing trigger points, consist of an integer and the enum value `.left` or `.right`.
The integer is the index of the trigger point, counting from the inside to the outside. The second parameter defines the side of the cell on which the trigger will be.
For this lesson I set-up two different trigger points on each side of the cell.
The two modes you can choose from are *toggle* and *exit*. Toggle is useful for marking or adding something, exit is mostly useful for removing items.
*/
//#-hidden-code
cell.selectionStyle = .gray
cell.contentView.backgroundColor = UIColor.white
cell.defaultColor = tableView.backgroundView?.backgroundColor
//#-end-hidden-code
//#-code-completion(everything, hide)
//#-code-completion(identifier, show, SwipyCellMode, exit, toggle, .)
//#-code-completion(identifier, show, SwipyCellState, state())
//#-code-completion(identifier, show, SwipyCellDirection, left, right)
//#-code-completion(identifier, show, checkView, crossView, clockView, listView, greenColor, redColor, yellowColor, brownColor)
//#-code-completion(identifier, show, nil, cell)
//#-editable-code
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .toggle, swipeView: checkView, swipeColor: greenColor, completion: nil)
// Add more swipe triggers using the same syntax as above, alter the states and modes you use...
cell.addSwipeTrigger(forState: .state(<#T##Int##Int#>, .<#Side#>), withMode: .<#SwipyCellMode#>, swipeView: crossView, swipeColor: redColor, completion: nil)
cell.addSwipeTrigger(forState: .state(<#T##Int##Int#>, .<#Side#>), withMode: .<#SwipyCellMode#>, swipeView: clockView, swipeColor: yellowColor, completion: nil)
cell.addSwipeTrigger(forState: .state(<#T##Int##Int#>, .<#Side#>), withMode: .<#SwipyCellMode#>, swipeView: listView, swipeColor: brownColor, completion: nil)
//#-end-editable-code
//#-hidden-code
cell.setCompletionBlocks(completionHandler)
return cell
}
private func completionHandler(cell: SwipyCell, state: SwipyCellState, mode: SwipyCellMode) {
assessmentStatus.states.insert(state)
if mode == .toggle { assessmentStatus.toggle = true }
if mode == .exit {
assessmentStatus.exit = true
deleteCell(cell)
}
checkAssessment()
}
private func checkAssessment() {
if assessmentStatus.states.count >= 4
&& assessmentStatus.toggle == true
&& assessmentStatus.exit == true {
PlaygroundPage.current.assessmentStatus = .pass(message: "### Great work! 👊 \n\n Now you know about the many ways you can use SwipyCell. \n\n To get a short summary and find out where to get SwipyCell,\n see the **[last page](@next)**")
}
}
private func deleteCell(_ cell: SwipyCell) {
numberItems = 0
let indexPath = tableView.indexPath(for: cell)
tableView.deleteRows(at: [indexPath!], with: .fade)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
self.numberItems = 1
self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
}
}
}
extension UIImageView {
convenience init(imageNamed: String) {
let image = UIImage(named: imageNamed)
self.init(image: image)
}
}
PlaygroundPage.current.liveView = HowToViewController()
//#-end-hidden-code
| mit | 10a9029a2e48e0647981c1af38307690 | 38.8 | 344 | 0.7137 | 4.241167 | false | false | false | false |
edragoev1/pdfjet | Sources/Example_22/main.swift | 1 | 2985 | import Foundation
import PDFjet
/**
* Example_22.swift
*
*/
public class Example_22 {
public init() throws {
if let stream = OutputStream(toFileAtPath: "Example_22.pdf", append: false) {
let pdf = PDF(stream)
let f1 = Font(pdf, CoreFont.HELVETICA)
var page = Page(pdf, Letter.PORTRAIT)
var text = TextLine(f1, "Page #1 -> Go to Destination #3.")
text.setGoToAction("dest#3")
text.setLocation(90.0, 50.0)
page.addDestination("dest#0", 0.0)
page.addDestination("dest#1", text.getDestinationY())
text.drawOn(page)
page = Page(pdf, Letter.PORTRAIT)
text = TextLine(f1, "Page #2 -> Go to Destination #3.")
text.setGoToAction("dest#3")
text.setLocation(90.0, 550.0)
page.addDestination("dest#2", text.getDestinationY())
text.drawOn(page)
page = Page(pdf, Letter.PORTRAIT)
text = TextLine(f1, "Page #3 -> Go to Destination #4.")
text.setGoToAction("dest#4")
text.setLocation(90.0, 700.0)
page.addDestination("dest#3", text.getDestinationY())
text.drawOn(page)
page = Page(pdf, Letter.PORTRAIT)
text = TextLine(f1, "Page #4 -> Go to Destination #0.")
text.setGoToAction("dest#0")
text.setLocation(90.0, 100.0)
page.addDestination("dest#4", text.getDestinationY())
text.drawOn(page)
text = TextLine(f1, "Page #4 -> Go to Destination #2.")
text.setGoToAction("dest#2")
text.setLocation(90.0, 200.0)
text.drawOn(page)
// Create a box with invisible borders
let box = Box(20.0, 20.0, 20.0, 20.0)
box.setColor(Color.white)
box.setGoToAction("dest#0")
box.drawOn(page)
// Create an up arrow and place it in the box
let path = Path()
path.add(Point(10.0, 1.0))
path.add(Point(17.0, 9.0))
path.add(Point(13.0, 9.0))
path.add(Point(13.0, 19.0))
path.add(Point( 7.0, 19.0))
path.add(Point( 7.0, 9.0))
path.add(Point( 3.0, 9.0))
path.setClosePath(true)
path.setColor(Color.blue)
path.setFillShape(true)
path.placeIn(box)
path.drawOn(page)
let image = try Image(
pdf,
InputStream(fileAtPath: "images/up-arrow.png")!,
ImageType.PNG)
image.setLocation(40.0, 40.0)
image.setGoToAction("dest#0")
image.drawOn(page)
pdf.complete()
}
}
} // End of Example_22.swift
let time0 = Int64(Date().timeIntervalSince1970 * 1000)
_ = try Example_22()
let time1 = Int64(Date().timeIntervalSince1970 * 1000)
print("Example_22 => \(time1 - time0)")
| mit | 97fabb7451b35c1fa4a904002e2bc9cb | 30.755319 | 85 | 0.528643 | 3.667076 | false | false | false | false |
svtek/SceneKitVideoRecorder | SceneKitVideoRecorder/Classes/SceneKitVideoRecorder.swift | 1 | 12468 | //
// SceneKitVideoRecorder.swift
//
// Created by Omer Karisman on 2017/08/29.
//
import UIKit
import SceneKit
import ARKit
import AVFoundation
import CoreImage
import BrightFutures
public class SceneKitVideoRecorder: NSObject, AVAudioRecorderDelegate {
private var writer: AVAssetWriter!
private var videoInput: AVAssetWriterInput!
var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!
private var pixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor!
private var options: Options
private let frameQueue = DispatchQueue(label: "com.svtek.SceneKitVideoRecorder.frameQueue")
private let bufferQueue = DispatchQueue(label: "com.svtek.SceneKitVideoRecorder.bufferQueue", attributes: .concurrent)
private let audioQueue = DispatchQueue(label: "com.svtek.SceneKitVideoRecorder.audioQueue")
private let errorDomain = "com.svtek.SceneKitVideoRecorder"
private var displayLink: CADisplayLink? = nil
private var initialTime: CMTime = CMTime.invalid
private var currentTime: CMTime = CMTime.invalid
private var sceneView: SCNView
private var audioSettings: [String : Any]?
public var isAudioSetup: Bool = false
private var isPrepared: Bool = false
private var isRecording: Bool = false
private var useAudio: Bool {
return options.useMicrophone && AVAudioSession.sharedInstance().recordPermission == .granted && isAudioSetup
}
private var videoFramesWritten: Bool = false
private var waitingForPermissions: Bool = false
private var renderer: SCNRenderer!
public var updateFrameHandler: ((_ image: UIImage) -> Void)? = nil
private var finishedCompletionHandler: ((_ url: URL) -> Void)? = nil
@available(iOS 11.0, *)
public convenience init(withARSCNView view: ARSCNView, options: Options = .`default`) throws {
try self.init(scene: view, options: options)
}
public init(scene: SCNView, options: Options = .`default`, setupAudio: Bool = true) throws {
self.sceneView = scene
self.options = options
self.isRecording = false
self.videoFramesWritten = false
super.init()
FileController.clearTemporaryDirectory()
self.prepare()
if setupAudio {
self.setupAudio()
}
}
private func prepare() {
self.prepare(with: self.options)
isPrepared = true
}
private func prepare(with options: Options) {
guard let device = MTLCreateSystemDefaultDevice() else { return }
self.renderer = SCNRenderer(device: device, options: nil)
renderer.scene = self.sceneView.scene
initialTime = CMTime.invalid
self.options.videoSize = options.videoSize
writer = try! AVAssetWriter(outputURL: self.options.videoOnlyUrl, fileType: self.options.fileType)
self.setupVideo()
}
@discardableResult public func cleanUp() -> URL {
var output = options.outputUrl
if options.deleteFileIfExists {
let nameOnly = (options.outputUrl.lastPathComponent as NSString).deletingPathExtension
let fileExt = (options.outputUrl.lastPathComponent as NSString).pathExtension
let tempFileName = NSTemporaryDirectory() + nameOnly + "TMP." + fileExt
output = URL(fileURLWithPath: tempFileName)
FileController.move(from: options.outputUrl, to: output)
FileController.delete(file: self.options.audioOnlyUrl)
FileController.delete(file: self.options.videoOnlyUrl)
}
return output
}
public func setupAudio() {
guard self.options.useMicrophone, !self.isAudioSetup else { return }
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(AVAudioSession.Category.playAndRecord, mode: .default)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission() { allowed in
DispatchQueue.main.async {
if allowed {
self.isAudioSetup = true
} else {
self.isAudioSetup = false
}
}
}
} catch {
self.isAudioSetup = false
}
}
private func startRecordingAudio() {
let audioUrl = self.options.audioOnlyUrl
let settings = self.options.assetWriterAudioInputSettings
do {
audioRecorder = try AVAudioRecorder(url: audioUrl, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
} catch {
finishRecordingAudio(success: false)
}
}
private func finishRecordingAudio(success: Bool) {
audioRecorder.stop()
audioRecorder = nil
}
private func setupVideo() {
self.videoInput = AVAssetWriterInput(mediaType: AVMediaType.video,
outputSettings: self.options.assetWriterVideoInputSettings)
self.videoInput.mediaTimeScale = self.options.timeScale
self.pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoInput,sourcePixelBufferAttributes: self.options.sourcePixelBufferAttributes)
writer.add(videoInput)
}
public func startWriting() -> Future<Void, NSError> {
let promise = Promise<Void, NSError>()
guard !isRecording else {
promise.failure(NSError(domain: errorDomain, code: ErrorCode.recorderBusy.rawValue, userInfo: nil))
return promise.future
}
isRecording = true
startDisplayLink()
guard startInputPipeline() else {
stopDisplayLink()
cleanUp()
promise.failure(NSError(domain: errorDomain, code: ErrorCode.unknown.rawValue, userInfo: nil))
return promise.future
}
promise.success(())
return promise.future
}
public func finishWriting() -> Future<URL, NSError> {
let promise = Promise<URL, NSError>()
guard isRecording, writer.status == .writing else {
let error = NSError(domain: errorDomain, code: ErrorCode.notReady.rawValue, userInfo: nil)
promise.failure(error)
return promise.future
}
videoInput.markAsFinished()
if audioRecorder != nil {
finishRecordingAudio(success: true)
}
isRecording = false
isPrepared = false
videoFramesWritten = false
currentTime = CMTime.invalid
writer.finishWriting { [weak self] in
guard let this = self else { return }
this.stopDisplayLink()
if this.useAudio {
this.mergeVideoAndAudio(videoUrl: this.options.videoOnlyUrl, audioUrl: this.options.audioOnlyUrl).onSuccess {
let outputUrl = this.cleanUp()
promise.success(outputUrl)
}
.onFailure { error in
this.cleanUp()
promise.failure(error)
}
} else {
FileController.move(from: this.options.videoOnlyUrl, to: this.options.outputUrl)
let outputUrl = this.cleanUp()
promise.success(outputUrl)
}
this.prepare()
}
return promise.future
}
private func getCurrentCMTime() -> CMTime {
return CMTimeMakeWithSeconds(CACurrentMediaTime(), preferredTimescale: 1000);
}
private func getAppendTime() -> CMTime {
currentTime = getCurrentCMTime() - initialTime
return currentTime
}
private func startDisplayLink() {
displayLink = CADisplayLink(target: self, selector: #selector(updateDisplayLink))
displayLink?.preferredFramesPerSecond = options.fps
displayLink?.add(to: .main, forMode: RunLoop.Mode.common)
}
@objc private func updateDisplayLink() {
frameQueue.async { [weak self] in
if self?.writer.status == .unknown { return }
if self?.writer.status == .failed { return }
guard let input = self?.videoInput, input.isReadyForMoreMediaData else { return }
self?.renderSnapshot()
}
}
private func startInputPipeline() -> Bool {
guard writer.status == .unknown else { return false }
guard writer.startWriting() else { return false }
writer.startSession(atSourceTime: CMTime.zero)
videoInput.requestMediaDataWhenReady(on: frameQueue, using: {})
return true
}
private func renderSnapshot() {
autoreleasepool {
let time = CACurrentMediaTime()
let image = renderer.snapshot(atTime: time, with: self.options.videoSize, antialiasingMode: self.options.antialiasingMode)
updateFrameHandler?(image)
guard let pool = self.pixelBufferAdaptor.pixelBufferPool else { print("No pool"); return }
let pixelBufferTemp = PixelBufferFactory.make(with: image, usingBuffer: pool)
guard let pixelBuffer = pixelBufferTemp else { print("No buffer"); return }
guard videoInput.isReadyForMoreMediaData else { print("No ready for media data"); return }
if videoFramesWritten == false {
videoFramesWritten = true
startRecordingAudio()
initialTime = getCurrentCMTime()
}
let currentTime = getCurrentCMTime()
guard CMTIME_IS_VALID(currentTime) else { print("No current time"); return }
let appendTime = getAppendTime()
guard CMTIME_IS_VALID(appendTime) else { print("No append time"); return }
bufferQueue.async { [weak self] in
self?.pixelBufferAdaptor.append(pixelBuffer, withPresentationTime: appendTime)
}
}
}
private func stopDisplayLink() {
displayLink?.invalidate()
displayLink = nil
}
private func mergeVideoAndAudio(videoUrl:URL, audioUrl:URL) -> Future<Void, NSError>
{
let promise = Promise<Void, NSError>()
let mixComposition : AVMutableComposition = AVMutableComposition()
var mutableCompositionVideoTrack : [AVMutableCompositionTrack] = []
var mutableCompositionAudioTrack : [AVMutableCompositionTrack] = []
let totalVideoCompositionInstruction : AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
let aVideoAsset : AVAsset = AVAsset(url: videoUrl)
let aAudioAsset : AVAsset = AVAsset(url: audioUrl)
mutableCompositionVideoTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!)
mutableCompositionAudioTrack.append(mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!)
guard !aVideoAsset.tracks.isEmpty, !aAudioAsset.tracks.isEmpty else {
let error = NSError(domain: errorDomain, code: ErrorCode.zeroFrames.rawValue, userInfo: nil)
promise.failure(error)
return promise.future
}
let aVideoAssetTrack : AVAssetTrack = aVideoAsset.tracks(withMediaType: AVMediaType.video)[0]
let aAudioAssetTrack : AVAssetTrack = aAudioAsset.tracks(withMediaType: AVMediaType.audio)[0]
do {
try mutableCompositionVideoTrack[0].insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: aVideoAssetTrack.timeRange.duration), of: aVideoAssetTrack, at: CMTime.zero)
try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: aVideoAssetTrack.timeRange.duration), of: aAudioAssetTrack, at: CMTime.zero)
} catch {
}
totalVideoCompositionInstruction.timeRange = CMTimeRangeMake(start: CMTime.zero,duration: aVideoAssetTrack.timeRange.duration )
let mutableVideoComposition : AVMutableVideoComposition = AVMutableVideoComposition()
mutableVideoComposition.frameDuration = CMTimeMake(value: 1, timescale: Int32(self.options.fps))
mutableVideoComposition.renderSize = self.options.videoSize
let savePathUrl : URL = self.options.outputUrl
let assetExport: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
assetExport.outputFileType = AVFileType.mp4
assetExport.outputURL = savePathUrl
assetExport.shouldOptimizeForNetworkUse = true
assetExport.exportAsynchronously { () -> Void in
switch assetExport.status {
case AVAssetExportSession.Status.completed:
promise.success(())
case AVAssetExportSession.Status.failed:
let assetExportErrorMessage = "failed \(String(describing: assetExport.error))"
let error = NSError(domain: self.errorDomain, code: ErrorCode.assetExport.rawValue, userInfo: ["Reason": assetExportErrorMessage])
promise.failure(error)
case AVAssetExportSession.Status.cancelled:
let assetExportErrorMessage = "cancelled \(String(describing: assetExport.error))"
let error = NSError(domain: self.errorDomain, code: ErrorCode.assetExport.rawValue, userInfo: ["Reason": assetExportErrorMessage])
promise.failure(error)
default:
promise.success(())
}
}
return promise.future
}
}
| mit | 76505715e88be4faa7f4155938fc35c9 | 30.969231 | 180 | 0.717036 | 4.85325 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/environment/OWSAudioSession.swift | 1 | 8845 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import WebRTC
@objc(OWSAudioActivity)
public class AudioActivity: NSObject {
let audioDescription: String
let behavior: OWSAudioBehavior
@objc public var supportsBackgroundPlayback: Bool {
// Currently, only audio messages support background playback
return behavior == .audioMessagePlayback
}
@objc public var backgroundPlaybackName: String {
switch behavior {
case .audioMessagePlayback:
return NSLocalizedString("AUDIO_ACTIVITY_PLAYBACK_NAME_AUDIO_MESSAGE",
comment: "A string indicating that an audio message is playing.")
default:
owsFailDebug("unexpectedly fetched background name for type that doesn't support background playback")
return ""
}
}
@objc
public init(audioDescription: String, behavior: OWSAudioBehavior) {
self.audioDescription = audioDescription
self.behavior = behavior
}
deinit {
audioSession.ensureAudioState()
}
// MARK: Dependencies
var audioSession: OWSAudioSession {
return Environment.shared.audioSession
}
// MARK:
override public var description: String {
return "<\(self.logTag) audioDescription: \"\(audioDescription)\">"
}
}
@objc
public class OWSAudioSession: NSObject {
@objc
public func setup() {
NotificationCenter.default.addObserver(self, selector: #selector(proximitySensorStateDidChange(notification:)), name: UIDevice.proximityStateDidChangeNotification, object: nil)
}
// MARK: Dependencies
var proximityMonitoringManager: OWSProximityMonitoringManager {
return Environment.shared.proximityMonitoringManager
}
private let avAudioSession = AVAudioSession.sharedInstance()
private let device = UIDevice.current
// MARK:
public private(set) var currentActivities: [Weak<AudioActivity>] = []
var aggregateBehaviors: Set<OWSAudioBehavior> {
return Set(self.currentActivities.compactMap { $0.value?.behavior })
}
@objc
public var wantsBackgroundPlayback: Bool {
return currentActivities.lazy.compactMap { $0.value?.supportsBackgroundPlayback }.contains(true)
}
@objc
public func startAudioActivity(_ audioActivity: AudioActivity) -> Bool {
Logger.debug("with \(audioActivity)")
objc_sync_enter(self)
defer { objc_sync_exit(self) }
self.currentActivities.append(Weak(value: audioActivity))
do {
try reconcileAudioCategory()
return true
} catch {
owsFailDebug("failed with error: \(error)")
return false
}
}
@objc
public func endAudioActivity(_ audioActivity: AudioActivity) {
Logger.debug("with audioActivity: \(audioActivity)")
objc_sync_enter(self)
defer { objc_sync_exit(self) }
currentActivities = currentActivities.filter { return $0.value != audioActivity }
do {
try reconcileAudioCategory()
} catch {
owsFailDebug("error in reconcileAudioCategory: \(error)")
}
}
@objc
public func ensureAudioState() {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
do {
try reconcileAudioCategory()
} catch {
owsFailDebug("error in ensureAudioState: \(error)")
}
}
@objc
func proximitySensorStateDidChange(notification: Notification) {
ensureAudioState()
}
private func reconcileAudioCategory() throws {
if aggregateBehaviors.contains(.audioMessagePlayback) {
self.proximityMonitoringManager.add(lifetime: self)
} else {
self.proximityMonitoringManager.remove(lifetime: self)
}
if aggregateBehaviors.contains(.call) {
// Do nothing while on a call.
// WebRTC/CallAudioService manages call audio
// Eventually it would be nice to consolidate more of the audio
// session handling.
} else if aggregateBehaviors.contains(.playAndRecord) {
assert(avAudioSession.recordPermission == .granted)
try avAudioSession.setCategory(.record)
} else if aggregateBehaviors.contains(.audioMessagePlayback) {
if self.device.proximityState {
Logger.debug("proximityState: true")
try avAudioSession.setCategory(.playAndRecord)
try avAudioSession.overrideOutputAudioPort(.none)
} else {
Logger.debug("proximityState: false")
try avAudioSession.setCategory(.playback)
}
} else if aggregateBehaviors.contains(.playback) {
try avAudioSession.setCategory(.playback)
} else {
if avAudioSession.category != AVAudioSession.Category.soloAmbient {
Logger.debug("reverting to default audio category: soloAmbient")
try avAudioSession.setCategory(.soloAmbient)
}
ensureAudioSessionActivationState()
}
}
func ensureAudioSessionActivationState(remainingRetries: UInt = 3) {
guard remainingRetries > 0 else {
owsFailDebug("ensureAudioSessionActivationState has no remaining retries")
return
}
objc_sync_enter(self)
defer { objc_sync_exit(self) }
// Cull any stale activities
currentActivities = currentActivities.compactMap { oldActivity in
guard oldActivity.value != nil else {
// Normally we should be explicitly stopping an audio activity, but this allows
// for recovery if the owner of the AudioAcivity was GC'd without ending it's
// audio activity
Logger.warn("an old activity has been gc'd")
return nil
}
// return any still-active activities
return oldActivity
}
guard currentActivities.isEmpty else {
Logger.debug("not deactivating due to currentActivities: \(currentActivities)")
return
}
do {
// When playing audio in Signal, other apps audio (e.g. Music) is paused.
// By notifying when we deactivate, the other app can resume playback.
try avAudioSession.setActive(false, options: [.notifyOthersOnDeactivation])
} catch let error as NSError {
if error.code == AVAudioSession.ErrorCode.isBusy.rawValue {
// Occasionally when trying to deactivate the audio session, we get a "busy" error.
// In that case we should retry after a delay.
//
// Error Domain=NSOSStatusErrorDomain Code=560030580 “The operation couldn’t be completed. (OSStatus error 560030580.)”
// aka "AVAudioSessionErrorCodeIsBusy"
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
self.ensureAudioSessionActivationState(remainingRetries: remainingRetries - 1)
}
return
} else {
owsFailDebug("failed with error: \(error)")
}
}
}
// MARK: - WebRTC Audio
/**
* By default WebRTC starts the audio session (PlayAndRecord) immediately upon creating the peer connection
* but we want to create the peer connection and set up all the signaling channels before we prompt the user
* for an incoming call. Without manually handling the session, this would result in the user seeing a recording
* permission requested (and recording banner) before they even know they have an incoming call.
*
* By using the `useManualAudio` and `isAudioEnabled` attributes of the RTCAudioSession we can delay recording until
* it makes sense.
*/
/**
* The private class that manages AVAudioSession for WebRTC
*/
private let rtcAudioSession = RTCAudioSession.sharedInstance()
/**
* This must be called before any audio tracks are added to the peerConnection, else we'll start recording before all
* our signaling is set up.
*/
@objc
public func configureRTCAudio() {
Logger.info("")
rtcAudioSession.useManualAudio = true
}
/**
* Because we useManualAudio with our RTCAudioSession, we have to start/stop the recording audio session ourselves.
* See header for details on manual audio.
*/
@objc
public var isRTCAudioEnabled: Bool {
get {
return rtcAudioSession.isAudioEnabled
}
set {
rtcAudioSession.isAudioEnabled = newValue
}
}
}
| gpl-3.0 | a73405735561892f9b0c9224f1d28d2d | 33.25969 | 184 | 0.633103 | 5.156943 | false | false | false | false |
carousell/pickle | UITests/UITests.swift | 1 | 3482 | //
// This source file is part of the carousell/pickle open source project
//
// Copyright © 2017 Carousell and the project authors
// Licensed under Apache License v2.0
//
// See https://github.com/carousell/pickle/blob/master/LICENSE for license information
// See https://github.com/carousell/pickle/graphs/contributors for the list of project authors
//
import XCTest
class UITests: XCTestCase {
private lazy var app: XCUIApplication = XCUIApplication()
private var cancelButton: XCUIElement {
return app.navigationBars.buttons["Cancel"]
}
private var doneButton: XCUIElement {
return app.navigationBars.buttons["Done"]
}
// MARK: -
override func setUp() {
super.setUp()
continueAfterFailure = false
app.launch()
}
private func showImagePicker(named name: String) {
app.tables.cells.staticTexts[name].tap()
addUIInterruptionMonitor(withDescription: "Photos Permission") { alert -> Bool in
let button = alert.buttons["OK"]
if button.exists {
button.tap()
return true
}
return false
}
// Need to interact with the app for the handler to fire
app.tap()
// Workaround to tap the permission alert button found via the springboard
let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
let button = springboard.buttons["OK"]
if button.exists {
button.tap()
}
}
func testDefaultStates() {
showImagePicker(named: "Default appearance")
XCTAssert(cancelButton.isEnabled)
XCTAssertFalse(doneButton.isEnabled)
cancelButton.tap()
}
func testImageSelections() {
showImagePicker(named: "Default appearance")
let cells = app.collectionViews.children(matching: .cell)
let first = cells.element(boundBy: 0)
let second = cells.element(boundBy: 1)
let third = cells.element(boundBy: 2)
let forth = cells.element(boundBy: 3)
let fifth = cells.element(boundBy: 4)
// Select and deselect an image
first.tap()
XCTAssert(first.isSelected)
XCTAssert(doneButton.isEnabled)
XCTAssert(first.identifier == "1")
first.tap()
XCTAssertFalse(first.isSelected)
XCTAssertFalse(doneButton.isEnabled)
XCTAssert(first.identifier.isEmpty)
// Select images in sequence
second.tap()
XCTAssert(second.identifier == "1")
third.tap()
XCTAssert(third.identifier == "2")
forth.tap()
XCTAssert(forth.identifier == "3")
// Reorder selections
third.tap()
XCTAssert(second.identifier == "1")
XCTAssert(forth.identifier == "2")
third.tap()
XCTAssert(third.identifier == "3")
fifth.tap()
XCTAssert(fifth.identifier == "4")
doneButton.tap()
}
func testSwitchingAlbums() {
showImagePicker(named: "Default appearance")
app.navigationBars.staticTexts["Camera Roll"].tap()
app.tables.cells.staticTexts["Favorites"].tap()
XCTAssert(app.collectionViews.cells.count == 0)
app.navigationBars["Favorites"].staticTexts["Favorites"].tap()
app.tables.cells.staticTexts["Camera Roll"].tap()
XCTAssert(app.collectionViews.cells.count > 0)
cancelButton.tap()
}
}
| apache-2.0 | d3f292f387449c94d7f5019df4b252ac | 27.532787 | 95 | 0.624246 | 4.64753 | false | false | false | false |
fitpay/fitpay-ios-sdk | FitpaySDK/PaymentDevice/EventListeners/FitpayEventsSubscriber.swift | 1 | 9366 | import Foundation
open class FitpayEventsSubscriber {
public static var sharedInstance = FitpayEventsSubscriber()
private let eventsDispatcher = FitpayEventDispatcher()
private var subscribersWithBindings: [SubscriberWithBinding] = []
public typealias EventCallback = (FitpayEvent) -> Void
// MARK: - Lifecycle
private init() {
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardAdded) { event in
self.executeCallbacksForEvent(event: .cardCreated)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardActivated) { event in
self.executeCallbacksForEvent(event: .cardActivated)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardDeactivated) { event in
self.executeCallbacksForEvent(event: .cardDeactivated)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardReactivated) { event in
self.executeCallbacksForEvent(event: .cardReactivated)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardDeleted) { event in
self.executeCallbacksForEvent(event: .cardDeleted)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .setDefaultCard) { event in
self.executeCallbacksForEvent(event: .setDefaultCard)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .resetDefaultCard) { event in
self.executeCallbacksForEvent(event: .resetDefaultCard)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardMetadataUpdated) { event in
self.executeCallbacksForEvent(event: .cardMetadataUpdated)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .cardProvisionFailed) { event in
self.executeCallbacksForEvent(event: .cardProvisionFailed)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .syncCompleted) { event in
self.executeCallbacksForEvent(event: .syncCompleted)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .syncFailed) { event in
var error: Error?
if let nserror = (event.eventData as? [String: NSError])?["error"] {
error = SyncManager.ErrorCode(rawValue: nserror.code)
}
self.executeCallbacksForEvent(event: .syncCompleted, status: .failed, reason: error)
}
_ = SyncManager.sharedInstance.bindToSyncEvent(eventType: .apduPackageComplete) { event in
var status = EventStatus.success
var error: Error?
if let nserror = (event.eventData as? [String: NSError])?["error"] {
error = SyncManager.ErrorCode(rawValue: nserror.code)
status = .failed
}
self.executeCallbacksForEvent(event: .apduPackageProcessed, status: status, reason: error, eventData: event.eventData)
}
}
// MARK: - Public Functions
open func subscribeTo(event: EventType, subscriber: AnyObject, callback: @escaping EventCallback) {
guard let binding = eventsDispatcher.addListenerToEvent(FitpayBlockEventListener(completion: callback), eventId: event) else {
log.error("EVENTS_SUBSCRIBER: can't create event binding for event: \(event.eventDescription())")
return
}
if var subscriberWithBindings = findSubscriberWithBindingsFor(subscriber: subscriber) {
subscriberWithBindings.bindings.append(binding)
} else {
subscribersWithBindings.append(SubscriberWithBinding(subscriber: subscriber, bindings: [binding]))
}
}
open func unsubscribe(subscriber: AnyObject) {
var subscriberWithBindings: SubscriberWithBinding?
for (i, subscriberItr) in subscribersWithBindings.enumerated() {
if subscriberItr.subscriber === subscriber {
subscriberWithBindings = subscriberItr
subscribersWithBindings.remove(at: i)
break
}
}
if let subscriberWithBindings = subscriberWithBindings {
for binding in subscriberWithBindings.bindings {
self.unbind(binding)
}
}
}
open func unsubscribe(subscriber: AnyObject, event: EventType) {
guard var subscriberWithBindings = findSubscriberWithBindingsFor(subscriber: subscriber) else { return }
subscriberWithBindings.removeAllBindingsFor(event: event) { (binding) in
self.unbind(binding)
}
removeSubscriberIfBindingsEmpty(subscriberWithBindings)
}
open func unsubscribe(subscriber: AnyObject, binding: FitpayEventBinding) {
guard var subscriberWithBindings = findSubscriberWithBindingsFor(subscriber: subscriber) else { return }
subscriberWithBindings.remove(binding: binding) { (binding) in
self.unbind(binding)
}
removeSubscriberIfBindingsEmpty(subscriberWithBindings)
}
// MARK: - Internal Functions
func executeCallbacksForEvent(event: EventType, status: EventStatus = .success, reason: Error? = nil, eventData: Any = "") {
eventsDispatcher.dispatchEvent(FitpayEvent(eventId: event, eventData: eventData, status: status, reason: reason))
}
// MARK: - Private Functions
private func removeSubscriberIfBindingsEmpty(_ subscriberWithBinding: SubscriberWithBinding) {
if subscriberWithBinding.bindings.count == 0 {
for (i, subscriberItr) in subscribersWithBindings.enumerated() {
if subscriberItr.subscriber === subscriberWithBinding.subscriber {
subscribersWithBindings.remove(at: i)
break
}
}
}
}
private func unbind(_ binding: FitpayEventBinding) {
eventsDispatcher.removeBinding(binding)
}
private func findSubscriberWithBindingsFor(subscriber: AnyObject) -> SubscriberWithBinding? {
for subscriberItr in subscribersWithBindings {
if subscriberItr.subscriber === subscriber {
return subscriberItr
}
}
return nil
}
}
// MARK: - Nested Objects
extension FitpayEventsSubscriber {
public enum EventType: Int, FitpayEventTypeProtocol {
case cardCreated = 0
case cardActivated
case cardDeactivated
case cardReactivated
case cardDeleted
case setDefaultCard
case resetDefaultCard
case cardProvisionFailed
case cardMetadataUpdated
case userCreated
case getUserAndDevice
case apduPackageProcessed
case syncCompleted
public func eventId() -> Int {
return rawValue
}
public func eventDescription() -> String {
switch self {
case .cardCreated:
return "Card created event."
case .cardActivated:
return "Card activated event."
case .cardDeactivated:
return "Card deactivated event."
case .cardReactivated:
return "Card reactivated event."
case .cardDeleted:
return "Card deleted event."
case .setDefaultCard:
return "Set default card event."
case .resetDefaultCard:
return "Reset default card event."
case .cardProvisionFailed:
return "Card provision failed event."
case .cardMetadataUpdated:
return "Card metadata updated event."
case .userCreated:
return "User created event."
case .getUserAndDevice:
return "Get user and device event."
case .apduPackageProcessed:
return "Apdu package processed event."
case .syncCompleted:
return "Sync completed event."
}
}
}
struct SubscriberWithBinding {
weak var subscriber: AnyObject?
var bindings: [FitpayEventBinding] = []
mutating func removeAllBindingsFor(event: EventType, unBindBlock: (FitpayEventBinding) -> Void) {
var eventsIndexForDelete: [Int] = []
for (i, binding) in bindings.enumerated() {
if binding.eventId.eventId() == event.eventId() {
unBindBlock(binding)
eventsIndexForDelete.append(i)
}
}
for index in eventsIndexForDelete {
bindings.remove(at: index)
}
}
mutating func remove(binding: FitpayEventBinding, unBindBlock: (FitpayEventBinding) -> Void) {
for (i, bindingItr) in bindings.enumerated() {
if binding.eventId.eventId() == bindingItr.eventId.eventId() {
unBindBlock(binding)
bindings.remove(at: i)
}
}
}
}
}
| mit | 4378e2d39444af8bff9d3428b6faf894 | 36.019763 | 134 | 0.606876 | 5.27662 | false | false | false | false |
FTChinese/iPhoneApp | FT Academy/FileManagerHelper.swift | 1 | 1420 | //
// FileManagerHelper.swift
// FT中文网
//
// Created by Oliver Zhang on 2017/4/17.
// Copyright © 2017年 Financial Times Ltd. All rights reserved.
//
import Foundation
struct FileManagerHelper {
public func removeFiles(_ fileTypes: [String]){
if let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
// print(directoryContents)
// if you want to filter the directory contents you can do like this:
let creativeTypes = fileTypes
let creativeFiles = directoryContents.filter{ creativeTypes.contains($0.pathExtension) }
for creativeFile in creativeFiles {
// print(creativeFile.lastPathComponent)
let creativeFileString = creativeFile.lastPathComponent
try FileManager.default.removeItem(at: creativeFile)
print("remove file from documents folder: \(creativeFileString)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
}
| mit | d1d80e1a7017f1dff689bd511cfe94d5 | 41.757576 | 147 | 0.608079 | 5.447876 | false | false | false | false |
TobacoMosaicVirus/MemorialDay | MemorialDay/MemorialDay/AppDelegate.swift | 1 | 4224 | //
// AppDelegate.swift
// MemorialDay
//
// Created by apple on 16/4/28.
// Copyright © 2016年 virus. All rights reserved.
//
import UIKit
import LocalAuthentication
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.registerNoti()
self.window = UIWindow.init(frame: SBounds)
self.window?.makeKeyAndVisible();
self.window?.rootViewController = UIViewController()
self.changeRootVC()
return true
}
func registerNoti(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.changeRootVC), name: "changeVC", object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@objc private func changeRootVC(){
let useFingerprint = VRSAccount.sharedAccount.useFingerprint ?? false
if useFingerprint {
let context = LAContext()
var error : NSError?
context.localizedFallbackTitle = "请通过指纹进入纪念日"
if (context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error)){
print("touch ID is available")
context.evaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "Use Touch ID to log in.", reply: { (success,error) in
if success {
}else{
if error?.code == kLAErrorUserFallback as? Int {
print("用户返回")
}else if error?.code == kLAErrorUserCancel as? Int{
print("用户取消")
}else{
print("验证失败")
}
}
})
}else{
print(error)
}
}
let isLogin = VRSAccount.sharedAccount.isLogin ?? false
if !isLogin{
let sb = UIStoryboard(name: "LoginStoryboard", bundle: nil)
let vc = sb.instantiateInitialViewController()
self.window?.rootViewController = vc
}else{
self.window?.rootViewController = VRSHomeTabBarController()
}
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | e7f302d053c2e37a40ca026211db6435 | 39.163462 | 285 | 0.631793 | 5.729767 | false | false | false | false |
seem-sky/WeatherMap | WeatherAroundUs/WeatherAroundUs/CityDetailViewController.swift | 3 | 8464 | //
// CityDetailViewController.swift
// WeatherAroundUs
//
// Created by Wang Yu on 4/23/15.
// Copyright (c) 2015 Kedan Li. All rights reserved.
//
import UIKit
import Spring
import Shimmer
class CityDetailViewController: UIViewController, UIScrollViewDelegate, InternetConnectionDelegate {
@IBOutlet var backgroundImageView: ImageScrollerView!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var mainTemperatureShimmerView: FBShimmeringView!
@IBOutlet var switchWeatherUnitButton: UIButton!
@IBOutlet var mainTemperatureDisplay: UILabel!
@IBOutlet var dateDisplayLabel: UILabel!
@IBOutlet var mainTempatureToTopHeightConstraint: NSLayoutConstraint!
@IBOutlet var basicForecastViewHeight: NSLayoutConstraint!
@IBOutlet var detailWeatherView: DetailWeatherView!
@IBOutlet var digestWeatherView: DigestWeatherView!
@IBOutlet var forecastView: BasicWeatherView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
var unit: TUnit!
var tempImage: UIImage!
var cityID = String()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
forecastView.parentController = self
digestWeatherView.parentController = self
detailWeatherView.parentController = self
mainTempatureToTopHeightConstraint.constant = view.frame.height / 3
mainTemperatureShimmerView.contentView = mainTemperatureDisplay
mainTemperatureShimmerView.shimmering = true
forecastView.clipsToBounds = true
digestWeatherView.clipsToBounds = true
detailWeatherView.clipsToBounds = true
if NSUserDefaults.standardUserDefaults().objectForKey("temperatureDisplay")!.boolValue! {
unit = .Fahrenheit
} else {
unit = .Celcius
}
mainTemperatureDisplay.text = "\(unit.stringValue)°"
}
// have to override function to manipulate status bar
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
// backgroundImageView = tempImage
switchWeatherUnitButton.addTarget(self, action: "switchWeatherUnitButtonDidPressed", forControlEvents: UIControlEvents.TouchUpInside)
loadingIndicator.startAnimating()
backgroundImageView.setup(tempImage)
setBackgroundImage()
}
override func viewDidAppear(animated: Bool) {
scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height / 3 + basicForecastViewHeight.constant + digestWeatherView.frame.height + detailWeatherView.frame.height + 250)
setUpBasicViews();
var panEdgeReco = UIScreenEdgePanGestureRecognizer(target: self, action: "swipeFromScreenEdge:")
panEdgeReco.edges = UIRectEdge.Left
self.view.addGestureRecognizer(panEdgeReco)
UIView.animateWithDuration(1, animations: { () -> Void in
self.mainTempatureToTopHeightConstraint.constant = self.view.frame.height - self.digestWeatherView.frame.height - self.mainTemperatureShimmerView.frame.height - 110
// self.mainTempatureToTopHeightConstraint.constant = self.view.frame.height / 2
self.view.layoutIfNeeded()
}) { (finished) -> Void in
self.scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.mainTempatureToTopHeightConstraint.constant + self.basicForecastViewHeight.constant + self.digestWeatherView.frame.height + self.detailWeatherView.frame.height + 140)
}
var currDate = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd"
let dateStr = dateFormatter.stringFromDate(currDate)
dateDisplayLabel.text = dateStr
//handle chinese
if dateDisplayLabel.text!.rangeOfString("月") != nil {
dateDisplayLabel.text = dateDisplayLabel.text! + "日"
}
switchWeatherUnitButtonDidPressed()
}
func setUpBasicViews() {
if WeatherInfo.citiesForcast[cityID] != nil{
let nineDayWeatherForcast = WeatherInfo.citiesForcast[cityID] as! [[String: AnyObject]]
forecastView.setup(nineDayWeatherForcast)
digestWeatherView.setup(nineDayWeatherForcast)
detailWeatherView.setup(nineDayWeatherForcast)
} else {
var connection = InternetConnection()
connection.delegate = self
connection.getWeatherForcast(cityID)
}
}
func swipeFromScreenEdge(sender: UIScreenEdgePanGestureRecognizer) {
let point = sender.translationInView(self.view)
if sender.state == UIGestureRecognizerState.Began {
scrollView.setContentOffset(CGPointZero, animated: true)
} else if sender.state == UIGestureRecognizerState.Changed {
scrollView.contentOffset.y = -point.x * CGFloat(1.5)
} else if sender.state == UIGestureRecognizerState.Ended || sender.state == UIGestureRecognizerState.Cancelled || sender.state == UIGestureRecognizerState.Failed {
scrollView.setContentOffset(CGPointZero, animated: true)
}
}
// if doesn't have forcast data
func gotWeatherForcastData(cityID: String, forcast: [AnyObject]) {
let userDefault = NSUserDefaults.standardUserDefaults()
// get currentDate
var currDate = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd.MM.YY"
let dateStr = dateFormatter.stringFromDate(currDate)
WeatherInfo.citiesForcast.updateValue(forcast, forKey: cityID)
let nineDayWeatherForcast = WeatherInfo.citiesForcast[cityID] as! [[String: AnyObject]]
forecastView.setup(nineDayWeatherForcast)
digestWeatherView.setup(nineDayWeatherForcast)
detailWeatherView.setup(nineDayWeatherForcast)
//display new icon
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.y < -90 {
UserMotion.stop()
self.performSegueWithIdentifier("backToMain", sender: self)
}
}
func switchWeatherUnitButtonDidPressed() {
NSUserDefaults.standardUserDefaults().setBool(unit.boolValue, forKey: "temperatureDisplay")
NSUserDefaults.standardUserDefaults().synchronize()
unit = unit.inverse
let todayDegree = Int(round(((WeatherInfo.citiesAroundDict[cityID] as! [String: AnyObject])["main"] as! [String: AnyObject])["temp"] as! Double))
mainTemperatureDisplay.text = unit.format(todayDegree)
if let nineDayWeatherForcast = WeatherInfo.citiesForcast[cityID] as? [[String: AnyObject]] {
digestWeatherView.reloadTemperature(nineDayWeatherForcast)
forecastView.reloadTempatureContent()
detailWeatherView.reloadTempatureContent(nineDayWeatherForcast)
}
}
func setBackgroundImage() {
let imageDict = ImageCache.imagesUrl
let imageUrl = imageDict[cityID]
if imageUrl != nil {
var cache = ImageCache()
cache.delegate = backgroundImageView
cache.getImageFromCache(imageUrl!, cityID: cityID)
}else{
// search if image not found
var connection = InternetConnection()
connection.delegate = self
//get image url
connection.searchForCityPhotos(CLLocationCoordinate2DMake(((WeatherInfo.citiesAroundDict[cityID] as! [String : AnyObject]) ["coord"] as! [String: AnyObject])["lat"]! as! Double, ((WeatherInfo.citiesAroundDict[cityID] as! [String : AnyObject]) ["coord"] as! [String: AnyObject])["lon"]! as! Double), name: ((WeatherInfo.citiesAroundDict[cityID] as! [String: AnyObject])["name"] as? String)!, cityID: WeatherInfo.currentCityID)
}
}
func gotImageUrls(btUrl: String, imageURL: String, cityID: String) {
var cache = ImageCache()
cache.delegate = backgroundImageView
cache.getImageFromCache(imageURL, cityID: cityID)
}
}
| apache-2.0 | 57da536d837febdb1571f73079814023 | 40.263415 | 437 | 0.678331 | 5.189571 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/Extensions/UIViewController+DisplayType.swift | 1 | 1718 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
/// Describes the display type for the view controller.
///
/// - compact: A compact display type, taller than wide.
/// - compactWide: A compact display type, wider than tall.
/// - regular: A regular display type, taller than wide.
/// - regularWide: A regular display type, wider than tall.
enum DisplayType {
case compact
case compactWide
case regular
case regularWide
}
extension UITraitCollection {
/// Returns the display type for the trait collection and view size.
func displayType(with viewSize: CGSize) -> DisplayType {
let regular = horizontalSizeClass == .regular && verticalSizeClass == .regular
if !regular {
if viewSize.isWiderThanTall {
return .compactWide
} else {
return .compact
}
} else if viewSize.isWiderThanTall {
return .regularWide
} else {
return .regular
}
}
}
extension UIViewController {
/// Returns the display type for the trait collection and view size.
var displayType: DisplayType {
return traitCollection.displayType(with: view.bounds.size)
}
}
| apache-2.0 | 84c9caf0efc6dea0f02545fe30dc1b1f | 28.118644 | 82 | 0.703725 | 4.252475 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/ExploreViewController.swift | 1 | 41759 | import UIKit
import WMF
class ExploreViewController: ColumnarCollectionViewController, ExploreCardViewControllerDelegate, UISearchBarDelegate, CollectionViewUpdaterDelegate, WMFSearchButtonProviding, ImageScaleTransitionProviding, DetailTransitionSourceProviding, EventLoggingEventValuesProviding {
// MARK - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
layoutManager.register(ExploreCardCollectionViewCell.self, forCellWithReuseIdentifier: ExploreCardCollectionViewCell.identifier, addPlaceholder: true)
navigationItem.titleView = titleView
navigationBar.addUnderNavigationBarView(searchBarContainerView)
navigationBar.isUnderBarViewHidingEnabled = true
navigationBar.displayType = .largeTitle
navigationBar.shouldTransformUnderBarViewWithBar = true
navigationBar.isShadowHidingEnabled = true
isRefreshControlEnabled = true
collectionView.refreshControl?.layer.zPosition = 0
title = CommonStrings.exploreTabTitle
NotificationCenter.default.addObserver(self, selector: #selector(exploreFeedPreferencesDidSave(_:)), name: NSNotification.Name.WMFExploreFeedPreferencesDidSave, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(articleDidChange(_:)), name: NSNotification.Name.WMFArticleUpdated, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(articleDeleted(_:)), name: NSNotification.Name.WMFArticleDeleted, object: nil)
#if UI_TEST
if UserDefaults.standard.wmf_isFastlaneSnapshotInProgress() {
collectionView.decelerationRate = .fast
}
#endif
}
deinit {
NotificationCenter.default.removeObserver(self)
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startMonitoringReachabilityIfNeeded()
showOfflineEmptyViewIfNeeded()
imageScaleTransitionView = nil
detailTransitionSourceRect = nil
logFeedImpressionAfterDelay()
}
override func viewWillHaveFirstAppearance(_ animated: Bool) {
super.viewWillHaveFirstAppearance(animated)
setupFetchedResultsController()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionViewUpdater?.isGranularUpdatingEnabled = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
dataStore.feedContentController.dismissCollapsedContentGroups()
stopMonitoringReachability()
collectionViewUpdater?.isGranularUpdatingEnabled = false
}
// MARK - NavBar
@objc func titleBarButtonPressed(_ sender: UIButton?) {
scrollToTop()
}
@objc public var titleButton: UIView {
return titleView
}
lazy var longTitleButton: UIButton = {
let longTitleButton = UIButton(type: .custom)
longTitleButton.adjustsImageWhenHighlighted = true
longTitleButton.setImage(UIImage(named: "wikipedia"), for: .normal)
longTitleButton.sizeToFit()
longTitleButton.addTarget(self, action: #selector(titleBarButtonPressed), for: .touchUpInside)
longTitleButton.isAccessibilityElement = false
return longTitleButton
}()
lazy var titleView: UIView = {
let titleView = UIView(frame: longTitleButton.bounds)
titleView.addSubview(longTitleButton)
titleView.isAccessibilityElement = false
return titleView
}()
// MARK - Refresh
open override func refresh() {
FeedFunnel.shared.logFeedRefreshed()
updateFeedSources(with: nil, userInitiated: true) {
}
}
// MARK - Scroll
var isLoadingOlderContent: Bool = false
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
guard !isLoadingOlderContent else {
return
}
let ratio: CGFloat = scrollView.contentOffset.y / (scrollView.contentSize.height - scrollView.bounds.size.height)
if ratio < 0.8 {
return
}
let lastSectionIndex = numberOfSectionsInExploreFeed - 1
guard lastSectionIndex >= 0 else {
return
}
let lastItemIndex = numberOfItemsInSection(lastSectionIndex) - 1
guard lastItemIndex >= 0 else {
return
}
guard let lastGroup = group(at: IndexPath(item: lastItemIndex, section: lastSectionIndex)) else {
return
}
let now = Date()
let midnightUTC: Date = (now as NSDate).wmf_midnightUTCDateFromLocal
guard let lastGroupMidnightUTC = lastGroup.midnightUTCDate else {
return
}
let calendar = NSCalendar.wmf_gregorian()
let days: Int = calendar?.wmf_days(from: lastGroupMidnightUTC, to: midnightUTC) ?? 0
guard days < Int(WMFExploreFeedMaximumNumberOfDays) else {
return
}
guard let nextOldestDate: Date = calendar?.date(byAdding: .day, value: -1, to: lastGroupMidnightUTC, options: .matchStrictly) else {
return
}
isLoadingOlderContent = true
FeedFunnel.shared.logFeedRefreshed()
updateFeedSources(with: (nextOldestDate as NSDate).wmf_midnightLocalDateForEquivalentUTC, userInitiated: false) {
self.isLoadingOlderContent = false
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
logFeedImpressionAfterDelay()
}
// MARK: - Event logging
private func logFeedImpressionAfterDelay() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(logFeedImpression), object: nil)
perform(#selector(logFeedImpression), with: self, afterDelay: 3)
}
@objc private func logFeedImpression() {
for indexPath in collectionView.indexPathsForVisibleItems {
guard let group = group(at: indexPath), group.undoType == .none, let itemFrame = collectionView.layoutAttributesForItem(at: indexPath)?.frame else {
continue
}
let visibleRectOrigin = CGPoint(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y + navigationBar.visibleHeight)
let visibleRectSize = view.layoutMarginsGuide.layoutFrame.size
let itemCenter = CGPoint(x: itemFrame.midX, y: itemFrame.midY)
let visibleRect = CGRect(origin: visibleRectOrigin, size: visibleRectSize)
let isUnobstructed = visibleRect.contains(itemCenter)
guard isUnobstructed else {
continue
}
FeedFunnel.shared.logFeedImpression(for: FeedFunnelContext(group))
}
}
// MARK - Search
public var wantsCustomSearchTransition: Bool {
return true
}
lazy var searchBarContainerView: UIView = {
let searchContainerView = UIView()
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchContainerView.addSubview(searchBar)
let leading = searchContainerView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: searchBar.leadingAnchor)
let trailing = searchContainerView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: searchBar.trailingAnchor)
let top = searchContainerView.topAnchor.constraint(equalTo: searchBar.topAnchor)
let bottom = searchContainerView.bottomAnchor.constraint(equalTo: searchBar.bottomAnchor)
searchContainerView.addConstraints([leading, trailing, top, bottom])
return searchContainerView
}()
lazy var searchBar: UISearchBar = {
let searchBar = UISearchBar()
searchBar.delegate = self
searchBar.returnKeyType = .search
searchBar.searchBarStyle = .minimal
searchBar.placeholder = WMFLocalizedString("search-field-placeholder-text", value: "Search Wikipedia", comment: "Search field placeholder text")
return searchBar
}()
@objc func ensureWikipediaSearchIsShowing() {
if self.navigationBar.underBarViewPercentHidden > 0 {
self.navigationBar.setNavigationBarPercentHidden(0, underBarViewPercentHidden: 0, extendedViewPercentHidden: 0, topSpacingPercentHidden: 1, animated: true)
}
}
// MARK - UISearchBarDelegate
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
let searchActivity = NSUserActivity.wmf_searchView()
NotificationCenter.default.post(name: .WMFNavigateToActivity, object: searchActivity)
return false
}
// MARK - State
@objc var dataStore: MWKDataStore!
private var fetchedResultsController: NSFetchedResultsController<WMFContentGroup>?
private var collectionViewUpdater: CollectionViewUpdater<WMFContentGroup>?
private var wantsDeleteInsertOnNextItemUpdate: Bool = false
private func setupFetchedResultsController() {
let fetchRequest: NSFetchRequest<WMFContentGroup> = WMFContentGroup.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "isVisible == YES")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "midnightUTCDate", ascending: false), NSSortDescriptor(key: "dailySortPriority", ascending: true), NSSortDescriptor(key: "date", ascending: false)]
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: "midnightUTCDate", cacheName: nil)
fetchedResultsController = frc
let updater = CollectionViewUpdater(fetchedResultsController: frc, collectionView: collectionView)
collectionViewUpdater = updater
updater.delegate = self
updater.isSlidingNewContentInFromTheTopEnabled = true
updater.performFetch()
}
private func group(at indexPath: IndexPath) -> WMFContentGroup? {
guard let frc = fetchedResultsController, frc.isValidIndexPath(indexPath) else {
return nil
}
return frc.object(at: indexPath)
}
private func groupKey(at indexPath: IndexPath) -> String? {
return group(at: indexPath)?.key
}
lazy var saveButtonsController: SaveButtonsController = {
let sbc = SaveButtonsController(dataStore: dataStore)
sbc.delegate = self
return sbc
}()
var numberOfSectionsInExploreFeed: Int {
guard let sections = fetchedResultsController?.sections else {
return 0
}
return sections.count
}
func numberOfItemsInSection(_ section: Int) -> Int {
guard let sections = fetchedResultsController?.sections, sections.count > section else {
return 0
}
return sections[section].numberOfObjects
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return numberOfSectionsInExploreFeed
}
private func resetRefreshControl() {
guard let refreshControl = collectionView.refreshControl,
refreshControl.isRefreshing else {
return
}
refreshControl.endRefreshing()
}
lazy var reachabilityNotifier: ReachabilityNotifier = {
let notifier = ReachabilityNotifier(Configuration.current.defaultSiteDomain) { [weak self] (reachable, flags) in
if reachable {
DispatchQueue.main.async {
self?.updateFeedSources(userInitiated: false)
}
} else {
DispatchQueue.main.async {
self?.showOfflineEmptyViewIfNeeded()
}
}
}
return notifier
}()
private func stopMonitoringReachability() {
reachabilityNotifier.stop()
}
private func startMonitoringReachabilityIfNeeded() {
guard numberOfSectionsInExploreFeed == 0 else {
stopMonitoringReachability()
return
}
reachabilityNotifier.start()
}
private func showOfflineEmptyViewIfNeeded() {
guard isViewLoaded && fetchedResultsController != nil else {
return
}
guard numberOfSectionsInExploreFeed == 0 else {
wmf_hideEmptyView()
return
}
guard !wmf_isShowingEmptyView() else {
return
}
guard !reachabilityNotifier.isReachable else {
return
}
resetRefreshControl()
wmf_showEmptyView(of: .noFeed, action: nil, theme: theme, frame: view.bounds)
}
var isLoadingNewContent = false
@objc(updateFeedSourcesWithDate:userInitiated:completion:)
public func updateFeedSources(with date: Date? = nil, userInitiated: Bool, completion: @escaping () -> Void = { }) {
assert(Thread.isMainThread)
guard !isLoadingNewContent else {
completion()
return
}
isLoadingNewContent = true
if date == nil, let refreshControl = collectionView.refreshControl, !refreshControl.isRefreshing {
#if UI_TEST
#else
refreshControl.beginRefreshing()
#endif
if numberOfSectionsInExploreFeed == 0 {
scrollToTop()
}
}
self.dataStore.feedContentController.updateFeedSources(with: date, userInitiated: userInitiated) {
DispatchQueue.main.async {
self.isLoadingNewContent = false
self.resetRefreshControl()
if date == nil {
self.startMonitoringReachabilityIfNeeded()
self.showOfflineEmptyViewIfNeeded()
}
completion()
}
}
}
override func contentSizeCategoryDidChange(_ notification: Notification?) {
layoutCache.reset()
super.contentSizeCategoryDidChange(notification)
}
// MARK - ImageScaleTransitionProviding
var imageScaleTransitionView: UIImageView?
// MARK - DetailTransitionSourceProviding
var detailTransitionSourceRect: CGRect?
// MARK - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItemsInSection(section)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let maybeCell = collectionView.dequeueReusableCell(withReuseIdentifier: ExploreCardCollectionViewCell.identifier, for: indexPath)
guard let cell = maybeCell as? ExploreCardCollectionViewCell else {
return maybeCell
}
cell.apply(theme: theme)
configure(cell: cell, forItemAt: indexPath, layoutOnly: false)
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard kind == UICollectionView.elementKindSectionHeader else {
abort()
}
guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionViewHeader.identifier, for: indexPath) as? CollectionViewHeader else {
abort()
}
configureHeader(header, for: indexPath.section)
return header
}
// MARK - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let group = group(at: indexPath) else {
return false
}
return group.isSelectable
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell {
detailTransitionSourceRect = view.convert(cell.frame, from: collectionView)
if
let vc = cell.cardContent as? ExploreCardViewController,
vc.collectionView.numberOfSections > 0, vc.collectionView.numberOfItems(inSection: 0) > 0,
let cell = vc.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ArticleCollectionViewCell
{
imageScaleTransitionView = cell.imageView.isHidden ? nil : cell.imageView
} else {
imageScaleTransitionView = nil
}
}
guard let group = group(at: indexPath) else {
return
}
if let vc = group.detailViewControllerWithDataStore(dataStore, theme: theme) {
wmf_push(vc, context: FeedFunnelContext(group), index: indexPath.item, animated: true)
return
}
if let vc = group.detailViewControllerForPreviewItemAtIndex(0, dataStore: dataStore, theme: theme) {
if vc is WMFImageGalleryViewController {
present(vc, animated: true)
FeedFunnel.shared.logFeedCardOpened(for: FeedFunnelContext(group))
} else {
wmf_push(vc, context: FeedFunnelContext(group), index: indexPath.item, animated: true)
}
return
}
}
func configureHeader(_ header: CollectionViewHeader, for sectionIndex: Int) {
guard collectionView(collectionView, numberOfItemsInSection: sectionIndex) > 0 else {
return
}
guard let group = group(at: IndexPath(item: 0, section: sectionIndex)) else {
return
}
header.title = (group.midnightUTCDate as NSDate?)?.wmf_localizedRelativeDateFromMidnightUTCDate()
header.apply(theme: theme)
}
func createNewCardVCFor(_ cell: ExploreCardCollectionViewCell) -> ExploreCardViewController {
let cardVC = ExploreCardViewController()
cardVC.delegate = self
cardVC.dataStore = dataStore
cardVC.view.autoresizingMask = []
addChild(cardVC)
cell.cardContent = cardVC
cardVC.didMove(toParent: self)
return cardVC
}
func configure(cell: ExploreCardCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) {
let cardVC = cell.cardContent as? ExploreCardViewController ?? createNewCardVCFor(cell)
guard let group = group(at: indexPath) else {
return
}
cardVC.contentGroup = group
cell.title = group.headerTitle
cell.subtitle = group.headerSubTitle
cell.footerTitle = cardVC.footerText
cell.isCustomizationButtonHidden = !(group.contentGroupKind.isCustomizable || group.contentGroupKind.isGlobal)
cell.undoType = group.undoType
cell.apply(theme: theme)
cell.delegate = self
if group.undoType == .contentGroupKind {
indexPathsForCollapsedCellsThatCanReappear.insert(indexPath)
}
}
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
searchBar.apply(theme: theme)
searchBarContainerView.backgroundColor = theme.colors.paperBackground
collectionView.backgroundColor = .clear
view.backgroundColor = theme.colors.paperBackground
for cell in collectionView.visibleCells {
guard let themeable = cell as? Themeable else {
continue
}
themeable.apply(theme: theme)
}
for header in collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader) {
guard let themeable = header as? Themeable else {
continue
}
themeable.apply(theme: theme)
}
}
// MARK: - ColumnarCollectionViewLayoutDelegate
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
guard let group = group(at: indexPath) else {
return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0)
}
let identifier = ExploreCardCollectionViewCell.identifier
let userInfo = "evc-cell-\(group.key ?? "")"
if let cachedHeight = layoutCache.cachedHeightForCellWithIdentifier(identifier, columnWidth: columnWidth, userInfo: userInfo) {
return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: cachedHeight)
}
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 100)
guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: ExploreCardCollectionViewCell.identifier) as? ExploreCardCollectionViewCell else {
return estimate
}
configure(cell: placeholderCell, forItemAt: indexPath, layoutOnly: true)
estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
layoutCache.setHeight(estimate.height, forCellWithIdentifier: identifier, columnWidth: columnWidth, groupKey: group.key, userInfo: userInfo)
return estimate
}
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
guard let group = self.group(at: IndexPath(item: 0, section: section)), let date = group.midnightUTCDate, date < Date() else {
return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0)
}
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 100)
guard let header = layoutManager.placeholder(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionViewHeader.identifier) as? CollectionViewHeader else {
return estimate
}
configureHeader(header, for: section)
estimate.height = header.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
return estimate
}
override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
return ColumnarCollectionViewLayoutMetrics.exploreViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins)
}
override func collectionView(_ collectionView: UICollectionView, shouldShowFooterForSection section: Int) -> Bool {
return false
}
// MARK - ExploreCardViewControllerDelegate
func exploreCardViewController(_ exploreCardViewController: ExploreCardViewController, didSelectItemAtIndexPath indexPath: IndexPath) {
guard
let contentGroup = exploreCardViewController.contentGroup,
let vc = contentGroup.detailViewControllerForPreviewItemAtIndex(indexPath.row, dataStore: dataStore, theme: theme) else {
return
}
if let cell = exploreCardViewController.collectionView.cellForItem(at: indexPath) {
detailTransitionSourceRect = view.convert(cell.frame, from: exploreCardViewController.collectionView)
if let articleCell = cell as? ArticleCollectionViewCell, !articleCell.imageView.isHidden {
imageScaleTransitionView = articleCell.imageView
} else {
imageScaleTransitionView = nil
}
}
if let otdvc = vc as? OnThisDayViewController {
otdvc.initialEvent = (contentGroup.contentPreview as? [Any])?[indexPath.item] as? WMFFeedOnThisDayEvent
}
let context = FeedFunnelContext(contentGroup)
switch contentGroup.detailType {
case .gallery:
present(vc, animated: true)
FeedFunnel.shared.logFeedCardOpened(for: context)
default:
wmf_push(vc, context: context, index: indexPath.item, animated: true)
}
}
// MARK - Prefetching
override func imageURLsForItemAt(_ indexPath: IndexPath) -> Set<URL>? {
guard let contentGroup = group(at: indexPath) else {
return nil
}
return contentGroup.imageURLsCompatibleWithTraitCollection(traitCollection, dataStore: dataStore)
}
#if DEBUG
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
guard motion == .motionShake else {
return
}
dataStore.feedContentController.debugChaos()
}
#endif
// MARK - CollectionViewUpdaterDelegate
var needsReloadVisibleCells = false
var indexPathsForCollapsedCellsThatCanReappear = Set<IndexPath>()
private func reloadVisibleCells() {
for indexPath in collectionView.indexPathsForVisibleItems {
guard let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell else {
continue
}
configure(cell: cell, forItemAt: indexPath, layoutOnly: false)
}
}
func collectionViewUpdater<T: NSFetchRequestResult>(_ updater: CollectionViewUpdater<T>, didUpdate collectionView: UICollectionView) {
guard needsReloadVisibleCells else {
return
}
reloadVisibleCells()
needsReloadVisibleCells = false
layout.currentSection = nil
}
func collectionViewUpdater<T: NSFetchRequestResult>(_ updater: CollectionViewUpdater<T>, updateItemAtIndexPath indexPath: IndexPath, in collectionView: UICollectionView) {
layoutCache.invalidateGroupKey(groupKey(at: indexPath))
collectionView.collectionViewLayout.invalidateLayout()
if wantsDeleteInsertOnNextItemUpdate {
layout.currentSection = indexPath.section
collectionView.deleteItems(at: [indexPath])
collectionView.insertItems(at: [indexPath])
} else {
needsReloadVisibleCells = true
}
}
// MARK: Event logging
var eventLoggingCategory: EventLoggingCategory {
return .feed
}
var eventLoggingLabel: EventLoggingLabel? {
return previewed.context?.label
}
// MARK: Peek & Pop
private var previewed: (context: FeedFunnelContext?, indexPath: IndexPath?)
override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard
let indexPath = collectionViewIndexPathForPreviewingContext(previewingContext, location: location),
let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell,
let vc = cell.cardContent as? ExploreCardViewController,
let contentGroup = vc.contentGroup
else {
return nil
}
previewed.context = FeedFunnelContext(contentGroup)
let convertedLocation = view.convert(location, to: vc.collectionView)
if let indexPath = vc.collectionView.indexPathForItem(at: convertedLocation), let cell = vc.collectionView.cellForItem(at: indexPath), let viewControllerToCommit = contentGroup.detailViewControllerForPreviewItemAtIndex(indexPath.row, dataStore: dataStore, theme: theme) {
previewingContext.sourceRect = view.convert(cell.bounds, from: cell)
if let potd = viewControllerToCommit as? WMFImageGalleryViewController {
potd.setOverlayViewTopBarHidden(true)
} else if let avc = viewControllerToCommit as? WMFArticleViewController {
avc.articlePreviewingActionsDelegate = self
avc.wmf_addPeekableChildViewController(for: avc.articleURL, dataStore: dataStore, theme: theme)
}
previewed.indexPath = indexPath
FeedFunnel.shared.logFeedCardPreviewed(for: previewed.context, index: indexPath.item)
return viewControllerToCommit
} else if contentGroup.contentGroupKind != .random {
return contentGroup.detailViewControllerWithDataStore(dataStore, theme: theme)
} else {
return nil
}
}
open override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if let potd = viewControllerToCommit as? WMFImageGalleryViewController {
potd.setOverlayViewTopBarHidden(false)
present(potd, animated: false)
FeedFunnel.shared.logFeedCardOpened(for: previewed.context)
} else if let avc = viewControllerToCommit as? WMFArticleViewController {
avc.wmf_removePeekableChildViewControllers()
wmf_push(avc, context: previewed.context, index: previewed.indexPath?.item, animated: false)
} else {
wmf_push(viewControllerToCommit, context: previewed.context, index: previewed.indexPath?.item, animated: true)
}
}
// MARK:
var addArticlesToReadingListVCDidDisappear: (() -> Void)? = nil
}
// MARK - Analytics
extension ExploreViewController {
private func logArticleSavedStateChange(_ wasArticleSaved: Bool, saveButton: SaveButton?, article: WMFArticle, userInfo: Any?) {
guard let articleURL = article.url else {
assert(false, "Article missing url: \(article)")
return
}
guard
let userInfo = userInfo as? ExploreSaveButtonUserInfo,
let midnightUTCDate = userInfo.midnightUTCDate,
let kind = userInfo.kind
else {
assert(false, "Article missing user info: \(article)")
return
}
let index = userInfo.indexPath.item
if wasArticleSaved {
ReadingListsFunnel.shared.logSaveInFeed(saveButton: saveButton, articleURL: articleURL, kind: kind, index: index, date: midnightUTCDate)
} else {
ReadingListsFunnel.shared.logUnsaveInFeed(saveButton: saveButton, articleURL: articleURL, kind: kind, index: index, date: midnightUTCDate)
}
}
}
extension ExploreViewController: SaveButtonsControllerDelegate {
func didSaveArticle(_ saveButton: SaveButton?, didSave: Bool, article: WMFArticle, userInfo: Any?) {
let logSavedEvent = {
self.logArticleSavedStateChange(didSave, saveButton: saveButton, article: article, userInfo: userInfo)
}
if isPresentingAddArticlesToReadingListVC() {
addArticlesToReadingListVCDidDisappear = logSavedEvent
} else {
logSavedEvent()
}
}
func willUnsaveArticle(_ article: WMFArticle, userInfo: Any?) {
if article.userCreatedReadingListsCount > 0 {
let alertController = ReadingListsAlertController()
alertController.showAlert(presenter: self, article: article)
} else {
saveButtonsController.updateSavedState()
}
}
func showAddArticlesToReadingListViewController(for article: WMFArticle) {
let addArticlesToReadingListViewController = AddArticlesToReadingListViewController(with: dataStore, articles: [article], moveFromReadingList: nil, theme: theme)
addArticlesToReadingListViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: addArticlesToReadingListViewController, theme: self.theme)
navigationController.isNavigationBarHidden = true
present(navigationController, animated: true)
}
private func isPresentingAddArticlesToReadingListVC() -> Bool {
guard let navigationController = presentedViewController as? UINavigationController else {
return false
}
return navigationController.viewControllers.contains { $0 is AddArticlesToReadingListViewController }
}
}
extension ExploreViewController: AddArticlesToReadingListDelegate {
func addArticlesToReadingListWillClose(_ addArticlesToReadingList: AddArticlesToReadingListViewController) {
}
func addArticlesToReadingListDidDisappear(_ addArticlesToReadingList: AddArticlesToReadingListViewController) {
addArticlesToReadingListVCDidDisappear?()
addArticlesToReadingListVCDidDisappear = nil
}
func addArticlesToReadingList(_ addArticlesToReadingList: AddArticlesToReadingListViewController, didAddArticles articles: [WMFArticle], to readingList: ReadingList) {
}
}
extension ExploreViewController: ReadingListsAlertControllerDelegate {
func readingListsAlertController(_ readingListsAlertController: ReadingListsAlertController, didSelectUnsaveForArticle: WMFArticle) {
saveButtonsController.updateSavedState()
}
}
extension ExploreViewController: ExploreCardCollectionViewCellDelegate {
func exploreCardCollectionViewCellWantsCustomization(_ cell: ExploreCardCollectionViewCell) {
guard let vc = cell.cardContent as? ExploreCardViewController,
let group = vc.contentGroup else {
return
}
guard let sheet = menuActionSheetForGroup(group) else {
return
}
sheet.popoverPresentationController?.sourceView = cell.customizationButton
sheet.popoverPresentationController?.sourceRect = cell.customizationButton.bounds
present(sheet, animated: true)
}
private func save() {
do {
try self.dataStore.save()
} catch let error {
DDLogError("Error saving after cell customization update: \(error)")
}
}
@objc func exploreFeedPreferencesDidSave(_ note: Notification) {
DispatchQueue.main.async {
for indexPath in self.indexPathsForCollapsedCellsThatCanReappear {
guard self.fetchedResultsController?.isValidIndexPath(indexPath) ?? false else {
continue
}
self.layoutCache.invalidateGroupKey(self.groupKey(at: indexPath))
self.collectionView.collectionViewLayout.invalidateLayout()
}
self.indexPathsForCollapsedCellsThatCanReappear = []
}
}
@objc func articleDidChange(_ note: Notification) {
guard
let article = note.object as? WMFArticle,
let articleKey = article.key
else {
return
}
var needsReload = false
if article.hasChangedValuesForCurrentEventThatAffectPreviews, layoutCache.invalidateArticleKey(articleKey) {
needsReload = true
collectionView.collectionViewLayout.invalidateLayout()
} else if !article.hasChangedValuesForCurrentEventThatAffectSavedState {
return
}
let visibleIndexPathsWithChanges = collectionView.indexPathsForVisibleItems.filter { (indexPath) -> Bool in
guard let contentGroup = group(at: indexPath) else {
return false
}
return contentGroup.previewArticleKeys.contains(articleKey)
}
guard !visibleIndexPathsWithChanges.isEmpty else {
return
}
for indexPath in visibleIndexPathsWithChanges {
guard let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell else {
continue
}
if needsReload {
configure(cell: cell, forItemAt: indexPath, layoutOnly: false)
} else if let cardVC = cell.cardContent as? ExploreCardViewController {
cardVC.savedStateDidChangeForArticleWithKey(articleKey)
}
}
}
@objc func articleDeleted(_ note: Notification) {
guard let articleKey = note.userInfo?[WMFArticleDeletedNotificationUserInfoArticleKeyKey] as? String else {
return
}
layoutCache.invalidateArticleKey(articleKey)
}
private func menuActionSheetForGroup(_ group: WMFContentGroup) -> UIAlertController? {
guard group.contentGroupKind.isCustomizable || group.contentGroupKind.isGlobal else {
return nil
}
let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let customizeExploreFeed = UIAlertAction(title: CommonStrings.customizeExploreFeedTitle, style: .default) { (_) in
let exploreFeedSettingsViewController = ExploreFeedSettingsViewController()
exploreFeedSettingsViewController.showCloseButton = true
exploreFeedSettingsViewController.dataStore = self.dataStore
exploreFeedSettingsViewController.apply(theme: self.theme)
let themeableNavigationController = WMFThemeableNavigationController(rootViewController: exploreFeedSettingsViewController, theme: self.theme)
self.present(themeableNavigationController, animated: true)
}
let hideThisCard = UIAlertAction(title: WMFLocalizedString("explore-feed-preferences-hide-card-action-title", value: "Hide this card", comment: "Title for action that allows users to hide a feed card"), style: .default) { (_) in
FeedFunnel.shared.logFeedCardDismissed(for: FeedFunnelContext(group))
group.undoType = .contentGroup
self.wantsDeleteInsertOnNextItemUpdate = true
self.save()
}
guard let title = group.headerTitle else {
assertionFailure("Expected header title for group \(group.contentGroupKind)")
return nil
}
let hideAllCards = UIAlertAction(title: String.localizedStringWithFormat(WMFLocalizedString("explore-feed-preferences-hide-feed-cards-action-title", value: "Hide all “%@” cards", comment: "Title for action that allows users to hide all feed cards of given type - %@ is replaced with feed card type"), title), style: .default) { (_) in
let feedContentController = self.dataStore.feedContentController
// If there's only one group left it means that we're about to show an alert about turning off the Explore tab. In those cases, we don't want to provide the option to undo.
if feedContentController.countOfVisibleContentGroupKinds > 1 {
group.undoType = .contentGroupKind
self.wantsDeleteInsertOnNextItemUpdate = true
}
feedContentController.toggleContentGroup(of: group.contentGroupKind, isOn: false, waitForCallbackFromCoordinator: true, apply: true, updateFeed: false)
FeedFunnel.shared.logFeedCardDismissed(for: FeedFunnelContext(group))
}
let cancel = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel)
sheet.addAction(hideThisCard)
sheet.addAction(hideAllCards)
sheet.addAction(customizeExploreFeed)
sheet.addAction(cancel)
return sheet
}
func exploreCardCollectionViewCellWantsToUndoCustomization(_ cell: ExploreCardCollectionViewCell) {
guard let vc = cell.cardContent as? ExploreCardViewController,
let group = vc.contentGroup else {
return
}
FeedFunnel.shared.logFeedCardRetained(for: FeedFunnelContext(group))
if group.undoType == .contentGroupKind {
dataStore.feedContentController.toggleContentGroup(of: group.contentGroupKind, isOn: true, waitForCallbackFromCoordinator: false, apply: true, updateFeed: false)
}
group.undoType = .none
wantsDeleteInsertOnNextItemUpdate = true
if let indexPath = fetchedResultsController?.indexPath(forObject: group) {
indexPathsForCollapsedCellsThatCanReappear.remove(indexPath)
}
save()
}
}
// MARK: - WMFArticlePreviewingActionsDelegate
extension ExploreViewController {
override func shareArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, shareActivityController: UIActivityViewController) {
super.shareArticlePreviewActionSelected(withArticleController: articleController, shareActivityController: shareActivityController)
FeedFunnel.shared.logFeedShareTapped(for: previewed.context, index: previewed.indexPath?.item)
}
override func readMoreArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController) {
articleController.wmf_removePeekableChildViewControllers()
wmf_push(articleController, context: previewed.context, index: previewed.indexPath?.item, animated: true)
}
override func saveArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, didSave: Bool, articleURL: URL) {
if didSave {
ReadingListsFunnel.shared.logSaveInFeed(context: previewed.context, articleURL: articleURL, index: previewed.indexPath?.item)
} else {
ReadingListsFunnel.shared.logUnsaveInFeed(context: previewed.context, articleURL: articleURL, index: previewed.indexPath?.item)
}
}
}
// MARK: - EventLoggingSearchSourceProviding
extension ExploreViewController: EventLoggingSearchSourceProviding {
var searchSource: String {
return "top_of_feed"
}
}
| mit | b089122b5b7a932eaa5d238f2306180c | 42.676778 | 342 | 0.682457 | 5.722215 | false | false | false | false |
LiuSky/XBDialog | XBDialog/ViewController.swift | 1 | 4532 | //
// ViewController.swift
// XBDialog
//
// Created by xiaobin liu on 2017/6/7.
// Copyright © 2017年 Sky. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
private let button = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
self.button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
self.button.backgroundColor = .red
self.button.setTitle("添加", for: .normal)
self.button.addTarget(self, action: #selector(ViewController.pre), for: .touchUpInside)
self.view.addSubview(self.button)
}
@objc public func pre() {
let vc = DemoViewController()
self.present(vc, animated: true, completion: nil)
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class DemoViewController: UIViewController {
private let button = UIButton(type: .custom)
private var de: XBPresentAnimator!
init() {
super.init(nibName: nil, bundle: nil)
self.de = XBPresentAnimator(self)
// self.de.menu {
// $0.duration = 0.3
// $0.isShowMask = true
// $0.menuType = MenuType.leftWidthFromViewRate(rate: 0.8)
// let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapGestureRecognizer))
// tap.numberOfTapsRequired = 1
// $0.gestureRecognizer = tap
// }
// self.xb.present.menu {
// $0.duration = 0.3
// $0.isShowMask = true
// $0.menuType = MenuType.leftWidthFromViewRate(rate: 0.8)
// let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapGestureRecognizer))
// tap.numberOfTapsRequired = 1
// $0.gestureRecognizer = tap
// }
//
// self.xb.present.dialog {
// $0.duration = 0.3
// $0.isShowMask = false
// $0.animateType = DialogAnimateType.direction(type: .right)
// let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapGestureRecognizer))
// tap.numberOfTapsRequired = 1
// $0.gestureRecognizer = tap
// }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .red
self.button.backgroundColor = UIColor.blue
self.button.setTitle("隐藏", for: .normal)
self.button.addTarget(self, action: #selector(DemoViewController.dis), for: .touchUpInside)
self.view.addSubview(self.button)
self.button.snp.makeConstraints { (make) in
make.center.equalTo(self.view)
make.size.equalTo(CGSize(width: 100, height: 100))
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscapeLeft
}
@objc public func dis() {
self.dismiss(animated: true, completion: nil)
}
// 手势点击
@objc public func tapGestureRecognizer() {
self.dismiss(animated: true, completion: nil)
}
// override var shouldAutorotate: Bool {
// return true
// }
//
// override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// return .landscapeRight
// }
//
// override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
// return UIInterfaceOrientation.landscapeLeft
// }
// // 大小自定义(这边自定义不影响上面用autolayout来布局)
// override var preferredContentSize: CGSize {
// get {
// return CGSize(width: 300, height: 500)
// }
// set { super.preferredContentSize = newValue }
// }
deinit {
// UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
debugPrint("页面释放")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 3e24011fe7dce57dbee78381941ba094 | 28.979866 | 106 | 0.616297 | 4.480441 | false | false | false | false |
BanyaKrylov/Learn-Swift | Skill/Homework 14/Pods/Alamofire/Source/Response.swift | 7 | 19584 | //
// Response.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type.
public typealias AFDataResponse<Success> = DataResponse<Success, AFError>
/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type.
public typealias AFDownloadResponse<Success> = DownloadResponse<Success, AFError>
/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`.
public struct DataResponse<Success, Failure: Error> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The final metrics of the response.
public let metrics: URLSessionTaskMetrics?
/// The time taken to serialize the response.
public let serializationDuration: TimeInterval
/// The result of response serialization.
public let result: Result<Success, Failure>
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Success? { return result.success }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Failure? { return result.failure }
/// Creates a `DataResponse` instance with the specified parameters derived from the response serialization.
///
/// - Parameters:
/// - request: The `URLRequest` sent to the server.
/// - response: The `HTTPURLResponse` from the server.
/// - data: The `Data` returned by the server.
/// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`.
/// - serializationDuration: The duration taken by serialization.
/// - result: The `Result` of response serialization.
public init(request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
metrics: URLSessionTaskMetrics?,
serializationDuration: TimeInterval,
result: Result<Success, Failure>) {
self.request = request
self.response = response
self.data = data
self.metrics = metrics
self.serializationDuration = serializationDuration
self.result = result
}
}
// MARK: -
extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
return "\(result)"
}
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the server data, the duration of the network and serialization actions, and the response serialization
/// result.
public var debugDescription: String {
let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None"
let responseDescription = response.map { response in
let sortedHeaders = response.headers.sorted()
return """
[Status Code]: \(response.statusCode)
[Headers]:
\(sortedHeaders)
"""
} ?? "nil"
let responseBody = data.map { String(decoding: $0, as: UTF8.self) } ?? "None"
let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
return """
[Request]: \(requestDescription)
[Request Body]: \n\(requestBody)
[Response]: \n\(responseDescription)
[Response Body]: \n\(responseBody)
[Data]: \(data?.description ?? "None")
[Network Duration]: \(metricsDescription)
[Serialization Duration]: \(serializationDuration)s
[Result]: \(result)
"""
}
}
// MARK: -
extension DataResponse {
/// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleInt = possibleData.map { $0.count }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's
/// result is a failure, returns a response wrapping the same failure.
public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DataResponse<NewSuccess, Failure> {
return DataResponse<NewSuccess, Failure>(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.map(transform))
}
/// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
/// value as a parameter.
///
/// Use the `tryMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleObject = possibleData.tryMap {
/// try JSONSerialization.jsonObject(with: $0)
/// }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
/// result is a failure, returns the same failure.
public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DataResponse<NewSuccess, Error> {
return DataResponse<NewSuccess, Error>(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMap(transform))
}
/// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `mapError` function with a closure that does not throw. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let withMyError = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A closure that takes the error of the instance.
///
/// - Returns: A `DataResponse` instance containing the result of the transform.
public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DataResponse<Success, NewFailure> {
return DataResponse<Success, NewFailure>(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.mapError(transform))
}
/// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `tryMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse<Data> = ...
/// let possibleObject = possibleData.tryMapError {
/// try someFailableFunction(taking: $0)
/// }
///
/// - Parameter transform: A throwing closure that takes the error of the instance.
///
/// - Returns: A `DataResponse` instance containing the result of the transform.
public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DataResponse<Success, Error> {
return DataResponse<Success, Error>(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMapError(transform))
}
}
// MARK: -
/// Used to store all data associated with a serialized response of a download request.
public struct DownloadResponse<Success, Failure: Error> {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The final destination URL of the data returned from the server after it is moved.
public let fileURL: URL?
/// The resume data generated if the request was cancelled.
public let resumeData: Data?
/// The final metrics of the response.
public let metrics: URLSessionTaskMetrics?
/// The time taken to serialize the response.
public let serializationDuration: TimeInterval
/// The result of response serialization.
public let result: Result<Success, Failure>
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Success? { return result.success }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Failure? { return result.failure }
/// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
///
/// - Parameters:
/// - request: The `URLRequest` sent to the server.
/// - response: The `HTTPURLResponse` from the server.
/// - temporaryURL: The temporary destination `URL` of the data returned from the server.
/// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
/// - resumeData: The resume `Data` generated if the request was cancelled.
/// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`.
/// - serializationDuration: The duration taken by serialization.
/// - result: The `Result` of response serialization.
public init(request: URLRequest?,
response: HTTPURLResponse?,
fileURL: URL?,
resumeData: Data?,
metrics: URLSessionTaskMetrics?,
serializationDuration: TimeInterval,
result: Result<Success, Failure>) {
self.request = request
self.response = response
self.fileURL = fileURL
self.resumeData = resumeData
self.metrics = metrics
self.serializationDuration = serializationDuration
self.result = result
}
}
// MARK: -
extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
return "\(result)"
}
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
/// actions, and the response serialization result.
public var debugDescription: String {
let requestDescription = request.map { "\($0.httpMethod!) \($0)" } ?? "nil"
let requestBody = request?.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? "None"
let responseDescription = response.map { response in
let sortedHeaders = response.headers.sorted()
return """
[Status Code]: \(response.statusCode)
[Headers]:
\(sortedHeaders)
"""
} ?? "nil"
let metricsDescription = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
return """
[Request]: \(requestDescription)
[Request Body]: \n\(requestBody)
[Response]: \n\(responseDescription)
[File URL]: \(fileURL?.path ?? "nil")
[ResumeData]: \(resumeDataDescription)
[Network Duration]: \(metricsDescription)
[Serialization Duration]: \(serializationDuration)s
[Result]: \(result)
"""
}
}
// MARK: -
extension DownloadResponse {
/// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleInt = possibleData.map { $0.count }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
/// result is a failure, returns a response wrapping the same failure.
public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DownloadResponse<NewSuccess, Failure> {
return DownloadResponse<NewSuccess, Failure>(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.map(transform))
}
/// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `tryMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleObject = possibleData.tryMap {
/// try JSONSerialization.jsonObject(with: $0)
/// }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
/// instance's result is a failure, returns the same failure.
public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error> {
return DownloadResponse<NewSuccess, Error>(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMap(transform))
}
/// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `mapError` function with a closure that does not throw. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let withMyError = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A closure that takes the error of the instance.
///
/// - Returns: A `DownloadResponse` instance containing the result of the transform.
public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> {
return DownloadResponse<Success, NewFailure>(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.mapError(transform))
}
/// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `tryMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse<Data> = ...
/// let possibleObject = possibleData.tryMapError {
/// try someFailableFunction(taking: $0)
/// }
///
/// - Parameter transform: A throwing closure that takes the error of the instance.
///
/// - Returns: A `DownloadResponse` instance containing the result of the transform.
public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> {
return DownloadResponse<Success, Error>(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMapError(transform))
}
}
| apache-2.0 | 49f25d19b4b41e3d9a9b077e4d640d91 | 48.082707 | 129 | 0.595078 | 5.43547 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/XCTEurofurenceModel/Entity Test Doubles/FakeAnnouncement.swift | 1 | 1885 | import EurofurenceModel
import Foundation
import TestUtilities
public final class FakeAnnouncement: Announcement {
public enum ReadStatus: Equatable {
case unread
case read
}
public var identifier: AnnouncementIdentifier
public var title: String
public var content: String
public var date: Date
public var isRead: Bool {
readStatus == .read
}
public var imagePNGData: Data?
public private(set) var readStatus: ReadStatus = .unread {
didSet {
for observer in observers {
if isRead {
observer.announcementEnteredReadState(self)
} else {
observer.announcementEnteredUnreadState(self)
}
}
}
}
public init(
identifier: AnnouncementIdentifier,
title: String,
content: String,
date: Date
) {
self.identifier = identifier
self.title = title
self.content = content
self.date = date
}
private var observers = [AnnouncementObserver]()
public func add(_ observer: AnnouncementObserver) {
observers.append(observer)
if isRead {
observer.announcementEnteredReadState(self)
} else {
observer.announcementEnteredUnreadState(self)
}
}
public func fetchAnnouncementImagePNGData(completionHandler: @escaping (Data?) -> Void) {
completionHandler(imagePNGData)
}
public func markRead() {
readStatus = .read
}
}
extension FakeAnnouncement: RandomValueProviding {
public static var random: FakeAnnouncement {
return FakeAnnouncement(
identifier: .random,
title: .random,
content: .random,
date: .random
)
}
}
| mit | 8d8a991b2932db8a50f3056726f64138 | 22.860759 | 93 | 0.583024 | 5.447977 | false | false | false | false |
banxi1988/Staff | Pods/BXForm/Pod/Classes/Controller/MultipleSelectViewController.swift | 1 | 3595 | //
// MultipleSelectViewController.swift
// Youjia
//
// Created by Haizhen Lee on 15/11/12.
//
import UIKit
import SwiftyJSON
import BXModel
public class MultipleSelectViewController<T:BXBasicItemAware where T:Hashable>: UITableViewController {
public private(set) var options:[T] = []
var adapter : SimpleTableViewAdapter<T>!
var selectedItems :Set<T> = []
public var completionHandler : ( (Set<T>) -> Void )?
public var onSelectOption:(T -> Void)?
public var multiple = true
public var showSelectToolbar = true
public init(){
super.init(style: .Grouped)
}
public func updateOptions(options:[T]){
self.options.removeAll()
self.options.appendContentsOf(options)
if isViewLoaded(){
adapter.updateItems(options)
}
}
public var selectAllButton:UIBarButtonItem?
public override func loadView() {
super.loadView()
if showSelectToolbar{
navigationController?.toolbarHidden = false
navigationController?.toolbar.tintColor = FormColors.primaryColor
let leftSpaceItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let selectAllButton = UIBarButtonItem(title:isSelectAll ? "全不选": "全选", style: .Plain, target: self, action: "selectAllButtonPressed:")
selectAllButton.tintColor = UIColor.blueColor()
toolbarItems = [leftSpaceItem,selectAllButton]
self.selectAllButton = selectAllButton
}
}
var isSelectAll = false
func selectAllButtonPressed(sender:AnyObject){
isSelectAll = !isSelectAll
selectAllButton?.title = isSelectAll ? "全不选": "全选"
if isSelectAll{
selectedItems.unionInPlace(options)
}else{
selectedItems.removeAll()
}
tableView.reloadData()
}
public override func viewDidLoad() {
super.viewDidLoad()
adapter = SimpleTableViewAdapter(tableView: tableView, items:options, cellStyle: .Default)
adapter.configureCellBlock = { (cell,indexPath) in
let item = self.adapter.itemAtIndexPath(indexPath)
cell.accessoryType = self.selectedItems.contains(item) ? .Checkmark: .None
}
tableView.tableFooterView = UIView()
if multiple{
let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "selectDone:")
self.navigationItem.rightBarButtonItem = doneButton
}
adapter.didSelectedItem = { (item,indexPath) in
self.onSelectItem(item,atIndexPath:indexPath)
}
}
func selectDone(sender:AnyObject){
self.completionHandler?(selectedItems)
#if DEBUG
NSLog("selectDone")
#endif
let poped = navigationController?.popViewControllerAnimated(true)
if poped == nil{
dismissViewControllerAnimated(true, completion: nil)
}
}
func onSelectItem(item:T,atIndexPath indexPath:NSIndexPath){
guard let cell = tableView.cellForRowAtIndexPath(indexPath) else{
return
}
if selectedItems.contains(item){
selectedItems.remove(item)
}else{
selectedItems.insert(item)
}
let isChecked = selectedItems.contains(item)
cell.accessoryType = isChecked ? .Checkmark : .None
if !multiple{
self.onSelectOption?(item)
selectDone(cell)
}
}
public override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.min
}
}
| mit | ba0f5aa4a9fc2c145a83be15ef268d1b | 29.555556 | 140 | 0.660979 | 4.88388 | false | false | false | false |
coderzzz/dyzbs | idyzb/idyzb/Home/View/ZZScorllTitleView.swift | 1 | 3106 | //
// ZZScorllTitleView.swift
// idyzb
//
// Created by Interest on 2017/1/19.
// Copyright © 2017年 Interest. All rights reserved.
//
import UIKit
//MARK:- 定义协议
protocol ZZScorllTitleViewDelegate : class {
func zzTitleView(titleView : ZZScorllTitleView, selectIndex : Int)
}
// MARK:- 定义类
class ZZScorllTitleView: UIView {
//MARK:-定义属性
private var titles :[String]
weak var delegate : ZZScorllTitleViewDelegate?
//MARK:-定义懒加载属性
private lazy var titleLables :[UILabel] = [UILabel]()
private lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.bounces = false
scrollView.backgroundColor = UIColor.clearColor()
scrollView.scrollsToTop = false
return scrollView
}()
private lazy var scrollviewline :UIView = {
let line = UIView()
line.backgroundColor = UIColor.orangeColor()
return line
}()
//MARK:-自定义构造函数
init(frame: CGRect ,titles:[String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:-设置界面
extension ZZScorllTitleView{
private func setupUI(){
addSubview(scrollView)
scrollView.frame = bounds
scrollView.contentSize = bounds.size
setupTitleLabels()
setupButtomLine()
setupScrollLine()
}
private func setupTitleLabels(){
let labelW :CGFloat = frame.width / CGFloat(titles.count)
let labelH :CGFloat = frame.height - 2
let labelY :CGFloat = 0
for (index, title) in titles.enumerate(){
let label = UILabel()
label.text = title
label.tag = index
label.font = UIFont.systemFontOfSize(14)
label.textColor = UIColor.darkGrayColor()
label.textAlignment = .Center
label.frame = CGRect(x: labelW * CGFloat(index), y: labelY, width: labelW, height: labelH)
scrollView.tag = 99;
scrollView.addSubview(label)
titleLables.append(label)
}
}
private func setupButtomLine(){
let buttomLine = UIView()
buttomLine.frame = CGRect(x: 0, y: frame.height - 0.5, width: frame.width, height: 0.5)
buttomLine.backgroundColor = UIColor.lightGrayColor()
addSubview(buttomLine)
}
private func setupScrollLine(){
let labelW :CGFloat = frame.width / CGFloat(titles.count)
scrollviewline.frame = CGRect(x: 0, y: frame.height - 2, width: labelW, height: 4)
scrollView.addSubview(scrollviewline)
}
}
//MARK:-对外方法
extension ZZScorllTitleView{
func setTitleWithProgess(progess : CGFloat){
}
}
| mit | 1a17015bf4d371e070938dbb4456d8d1 | 23.893443 | 102 | 0.592032 | 4.665131 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/MIDI/AKMIDISampler.swift | 2 | 3749 | //
// AKMIDISampler.swift
// AudioKit
//
// Created by Jeff Cooper, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AVFoundation
import CoreAudio
/// MIDI receiving Sampler
///
/// be sure to enableMIDI if you want to receive messages
///
public class AKMIDISampler: AKSampler {
// MARK: - Properties
/// MIDI Input
public var midiIn = MIDIEndpointRef()
/// Name of the instrument
public var name = "AKMIDISampler"
/// Enable MIDI input from a given MIDI client
/// This is not in the init function because it must be called AFTER you start AudioKit
///
/// - parameter midiClient: A refernce to the MIDI client
/// - parameter name: Name to connect with
///
public func enableMIDI(midiClient: MIDIClientRef, name: String) {
var result: OSStatus
result = MIDIDestinationCreateWithBlock(midiClient, name, &midiIn, MyMIDIReadBlock)
CheckError(result)
}
// MARK: - Handling MIDI Data
// Send MIDI data to the audio unit
func handleMIDI(data1: UInt32, data2: UInt32, data3: UInt32) {
let status = data1 >> 4
let channel = data1 & 0xF
if Int(status) == AKMIDIStatus.NoteOn.rawValue && data3 > 0 {
startNote(Int(data2), withVelocity: Int(data3), onChannel: Int(channel))
} else if Int(status) == AKMIDIStatus.NoteOn.rawValue && data3 == 0 {
stopNote(Int(data2), onChannel: Int(channel))
} else if Int(status) == AKMIDIStatus.ControllerChange.rawValue {
midiCC(Int(data2), value: Int(data3), channel: Int(channel))
}
}
/// Handle MIDI commands that come in externally
///
/// - parameter note: MIDI Note number
/// - parameter velocity: MIDI velocity
/// - parameter channel: MIDI channel
///
public func receivedMIDINoteOn(note: Int, velocity: Int, channel: Int) {
if velocity > 0 {
startNote(note, withVelocity: velocity, onChannel: channel)
} else {
stopNote(note, onChannel: channel)
}
}
/// Handle MIDI CC that come in externally
///
/// - parameter cc: MIDI cc number
/// - parameter value: MIDI cc value
/// - parameter channel: MIDI cc channel
///
public func midiCC(cc: Int, value: Int, channel: Int) {
samplerUnit.sendController(UInt8(cc), withValue: UInt8(value), onChannel: UInt8(channel))
}
// MARK: - MIDI Note Start/Stop
/// Start a note
public func startNote(note: Int, withVelocity velocity: Int, onChannel channel: Int) {
samplerUnit.startNote(UInt8(note), withVelocity: UInt8(velocity), onChannel: UInt8(channel))
}
/// Stop a note
public func stopNote(note: Int, onChannel channel: Int) {
samplerUnit.stopNote(UInt8(note), onChannel: UInt8(channel))
}
private func MyMIDIReadBlock(
packetList: UnsafePointer<MIDIPacketList>,
srcConnRefCon: UnsafeMutablePointer<Void>) -> Void {
let packetCount = Int(packetList.memory.numPackets)
let packet = packetList.memory.packet as MIDIPacket
var packetPointer: UnsafeMutablePointer<MIDIPacket> = UnsafeMutablePointer.alloc(1)
packetPointer.initialize(packet)
for _ in 0 ..< packetCount {
let event = AKMIDIEvent(packet: packetPointer.memory)
//the next line is unique for midiInstruments - otherwise this function is the same as AKMIDI
handleMIDI(UInt32(event.internalData[0]), data2: UInt32(event.internalData[1]), data3: UInt32(event.internalData[2]))
packetPointer = MIDIPacketNext(packetPointer)
}
}
}
| apache-2.0 | 79a3aec09f041b7b84b4a8cff6b9f523 | 34.695238 | 129 | 0.638474 | 4.293242 | false | false | false | false |
cxpyear/SPDBDemo | spdbapp/spdbapp/Classes/Controller/Builder.swift | 1 | 6596 | //
// Builder.swift
// spdbapp
//
// Created by GBTouchG3 on 15/5/14.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
import Foundation
import Alamofire
class Builder: NSObject {
var current = GBMeeting()
func loadOffLineMeeting() -> GBMeeting {
current.sources.removeAll(keepCapacity: false)
current.agendas.removeAll(keepCapacity: false)
var localJSONPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/jsondata.txt")
var filemanager = NSFileManager.defaultManager()
var jsonLocal = filemanager.contentsAtPath(localJSONPath)
var result: AnyObject = NSJSONSerialization.JSONObjectWithData(jsonLocal!, options: NSJSONReadingOptions.AllowFragments, error: nil)!
// println("localcreatemeeting json ======local====== \(result)")
var json = JSON(result)
self.getMeetingInfo(json)
return current
}
//Create Meeting offline
func LocalCreateMeeting() -> GBMeeting {
println("bneedrefresh = \(bNeedRefresh)")
current.sources.removeAll(keepCapacity: false)
current.agendas.removeAll(keepCapacity: false)
var localJSONPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/jsondata.txt")
var filemanager = NSFileManager.defaultManager()
println("localcreatemeeting appmanaer = \(appManager.netConnect)")
if appManager.netConnect == true && appManager.wifiConnect == true {
var url = NSURL(string: server.meetingServiceUrl)
println("localcreatemeeting url = \(url)")
var data = NSData(contentsOfURL: url!)
if(data != nil){
var result: AnyObject = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: nil)!
println("localcreatemeeting json ======net====== ")
var json = JSON(result)
self.getMeetingInfo(json)
}
}
else{
if filemanager.fileExistsAtPath(localJSONPath){
var jsonLocal = filemanager.contentsAtPath(localJSONPath)
var result: AnyObject = NSJSONSerialization.JSONObjectWithData(jsonLocal!, options: NSJSONReadingOptions.AllowFragments, error: nil)!
println("localcreatemeeting json ======local======= ")
var json = JSON(result)
self.getMeetingInfo(json)
}else{
}
}
appManager.current = current
return current
}
func getMeetingInfo(json: JSON) -> GBMeeting{
current.id = json["id"].stringValue
current.name = json["name"].stringValue
println("current meetinginfo = \(current.name)")
if let sources = json["source"].array{
var count = sources.count
for var i = 0 ; i < count ; i++ {
var source = GBSource()
var sourceRowValue = sources[i]
source.id = sourceRowValue["id"].stringValue
source.name = sourceRowValue["name"].stringValue
source.meetingtype = sourceRowValue["meetingtype"].stringValue
source.memberrole = sourceRowValue["memberrole"].stringValue
source.type = sourceRowValue["type"].stringValue
source.sourextension = sourceRowValue["extension"].stringValue
source.sourpublic = sourceRowValue["public"].stringValue
source.link = sourceRowValue["link"].stringValue
source.aidlink = sourceRowValue["aid-link"].stringValue
var type : String?
var role : String?
if bNeedRefresh == true{
type = appManager.appGBUser.type
role = appManager.appGBUser.role
}else{
var userInfoPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/UserInfo.txt")
var userinfo = NSDictionary(contentsOfFile: userInfoPath)
type = userinfo?.objectForKey("type") as? String
role = userinfo?.objectForKey("role") as? String
}
// println("source.type = \(source.meetingtype)===== source.role = \(source.memberrole)")
// println("type = \(type)====role = \(role)")
//当满足人员类型等于会议类型 && 人员角色==文件分配权限/全员时,将该文件加载入对应的议程中
if ((type == source.meetingtype) && ((role == source.memberrole) || (source.memberrole == "全员"))){
current.sources.append(source)
}
}
// println("source.count = \(current.sources.count)")
}
if let agendas = json["agenda"].array{
var count = agendas.count
for var i = 0 ; i < count ; i++ {
var agenda = GBAgenda()
var agendaRowValue = agendas[i]
agenda.id = agendaRowValue["id"].stringValue
agenda.name = agendaRowValue["name"].stringValue
agenda.starttime = agendaRowValue["starttime"].stringValue
agenda.endtime = agendaRowValue["endtime"].stringValue
agenda.reporter = agendaRowValue["reporter"].stringValue
agenda.index = agendaRowValue["index"].stringValue
if let sourceLists = agendaRowValue["source"].array{
var sourceCount = sourceLists.count
for var j = 0 ; j < sourceCount ; j++ {
var source = GBSource()
var sourceId = agendaRowValue["source"][j].stringValue
for var k = 0 ; k < current.sources.count ; k++ {
if current.sources[k].id == sourceId {
agenda.source.append(current.sources[k])
}
}
}
}
current.agendas.append(agenda)
println("agenda\(i).source.count======\(current.agendas[i].source.count)")
}
}
return current
}
}
| bsd-3-clause | e1718aceadbccd908523cf5abffcd10c | 39.90566 | 145 | 0.541667 | 5.257882 | false | false | false | false |
apple/swift | test/ModuleInterface/if-configs.swift | 7 | 3383 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t/Test~partial.swiftmodule -module-name Test -primary-file %s
// RUN: %target-swift-frontend -merge-modules -emit-module -o %t/Test.swiftmodule %t/Test~partial.swiftmodule
// RUN: %target-swift-ide-test -print-module -module-to-print=Test -source-filename=x -I %t -prefer-type-repr=false -fully-qualified-types=true | %FileCheck %s
// RUN: %target-swift-emit-module-interface(%t.swiftinterface) %s
// RUN: %target-swift-typecheck-module-from-interface(%t.swiftinterface)
// RUN: %FileCheck %s < %t.swiftinterface
// CHECK: func hasClosureDefaultArgWithComplexNestedPoundIfs(_ x: () -> Swift.Void = {
// CHECK-NOT: #if NOT_PROVIDED
// CHECK-NOT: print("should not exist")
// CHECK-NOT: #elseif !NOT_PROVIDED
// CHECK: let innerClosure = {
// CHECK-NOT: #if false
// CHECK-NOT: print("should also not exist")
// CHECK-NOT: #else
// CHECK: print("should exist")
// CHECK-NOT: #endif
// CHECK: }
// CHECK-NOT: #endif
// CHECK: })
public func hasClosureDefaultArgWithComplexNestedPoundIfs(_ x: () -> Void = {
#if NOT_PROVIDED
print("should not exist")
#elseif !NOT_PROVIDED
let innerClosure = {
#if false
print("should also not exist")
#else
print("should exist")
#endif
}
#endif
}) {
}
// CHECK: func hasClosureDefaultArgWithComplexPoundIf(_ x: () -> Swift.Void = {
// CHECK-NOT: #if NOT_PROVIDED
// CHECK-NOT: print("should not exist")
// CHECK-NOT: #else
// CHECK-NOT: #if NOT_PROVIDED
// CHECK-NOT: print("should also not exist")
// CHECK-NOT: #else
// CHECK: print("should exist"){{$}}
// CHECK-NOT: #if !second
// CHECK: print("should also exist"){{$}}
// CHECK-NOT: #endif
// CHECK-NEXT: })
public func hasClosureDefaultArgWithComplexPoundIf(_ x: () -> Void = {
#if NOT_PROVIDED
print("should not exist")
#else
#if NOT_PROVIDED
print("should also not exist")
#else
print("should exist")
#endif
#endif
#if !second
print("should also exist")
#endif
}) {
}
// CHECK: func hasClosureDefaultArgWithMultilinePoundIfCondition(_ x: () -> Swift.Void = {
// CHECK-NOT: #if (
// CHECK-NOT: !false && true
// CHECK-NOT: )
// CHECK: print("should appear")
// CHECK-NOT: #endif
// CHECK-NOT: #if (
// CHECK-NOT: !true
// CHECK-NOT: )
// CHECK-NOT: print("should not appear")
// CHECK-NOT: #else
// CHECK: print("also should appear")
// CHECK-NOT: #endif
// CHECK-NEXT: })
public func hasClosureDefaultArgWithMultilinePoundIfCondition(_ x: () -> Void = {
#if (
!false && true
)
print("should appear")
#endif
#if (
!true
)
print("should not appear")
#else
print("also should appear")
#endif
}) {
}
// CHECK: func hasClosureDefaultArgWithSinglePoundIf(_ x: () -> Swift.Void = {
// CHECK-NOT: #if true
// CHECK: print("true")
// CHECK-NOT: #else
// CHECK-NOT: print("false")
// CHECK-NOT: #endif
// CHECK-NEXT: })
public func hasClosureDefaultArgWithSinglePoundIf(_ x: () -> Void = {
#if true
print("true")
#else
print("false")
#endif
}) {
}
// CHECK: func hasIfCompilerCheck
// CHECK: #if compiler(>=5.3)
// CHECK-NEXT: return true
// CHECK-NEXT: #else
// CHECK-NEXT: return false
// CHECK-NEXT: #endif
@_alwaysEmitIntoClient
public func hasIfCompilerCheck(_ x: () -> Bool = {
#if compiler(>=5.3)
return true
#else
return false
#endif
}) {
}
| apache-2.0 | 936b41b0f3b53b0445f1d6ca7d00b264 | 25.429688 | 159 | 0.644694 | 3.209677 | false | false | false | false |
CanBeMyQueen/DouYuZB | DouYu/DouYu/Classes/Home/View/RecommendGameView.swift | 1 | 1546 | //
// RecommendGameView.swift
// DouYu
//
// Created by 张萌 on 2017/10/25.
// Copyright © 2017年 JiaYin. All rights reserved.
//
import UIKit
private let kGameViewCellID = "kGameViewCellID"
class RecommendGameView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
var groups : [BaseGameModel]? {
didSet {
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = .flexibleLeftMargin
collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kGameViewCellID)
}
}
// 提供一个快速创建 View 的类方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameViewCellID, for: indexPath) as! CollectionViewGameCell
cell.group = self.groups?[indexPath.item]
// cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.brown : UIColor.gray
return cell
}
}
| mit | 9042642662792b90e7ff5a935cb96445 | 30.5625 | 134 | 0.709571 | 5.10101 | false | false | false | false |
DaiYue/HAMLeetcodeSwiftSolutions | solutions/4_Median_of_two_sorted_arrays.playground/Contents.swift | 1 | 6766 | // #4 Median of Two Sorted Arrays https://leetcode.com/problems/median-of-two-sorted-arrays/
// 下面列出了两个解法,其中 Solution2 是自己想出来的,也过了全部测试数据,但方法非常不简洁。思路是从两边逼近中位数,取两个数列的中点,可证明总有一个不能满足第 k 大的条件。然后就调整这个数列。问题在于,有些情况可能会调整过头。另外,还有这个数列已经到头、调整不了的情况,此时就需要去调另一个数列。总的来说仍然是 log(m + n) 的,但代码非常长,原理也不够清晰。
// Solution1 参考了别人的题解,每次两个数列各取 k/2 处,小者在这个位置之前全都截断。
// 为啥 Solution1 就非常简洁呢?最主要的问题在于,Solution1 是从一侧逼近问题的,每次迭代都更靠近答案。Solution2 是从两侧往中间逼近,然而两个数列并没有二分查找那么好的特性,有可能两个指针都在答案的同侧,还要回头找。
// 另外,Solution1 利用了一个技巧,保证每次迭代时 nums1 都更短,不然交换。可以避免很多对称的重复代码。
// 在语言方面,可以看出 swift 里 if(...) {return ...} 这种基本都用 guard 代替。
// 时间复杂度:log(m+n) 空间复杂度:O(m+n)
class Solution {
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
if (nums1.count + nums2.count) % 2 == 0 {
let lowerMedian = findKthInSortedArrays(k: (nums1.count + nums2.count) / 2, nums1: nums1, nums2: nums2)
let higherMedian = findKthInSortedArrays(k: (nums1.count + nums2.count) / 2 + 1, nums1: nums1, nums2: nums2)
return (Double(lowerMedian) + Double(higherMedian)) / 2;
} else {
return Double(findKthInSortedArrays(k: (nums1.count + nums2.count + 1) / 2, nums1: nums1, nums2: nums2))
}
}
func findKthInSortedArrays(k: Int, nums1: [Int], nums2: [Int]) -> Int {
guard nums1.count <= nums2.count else {
return findKthInSortedArrays(k: k, nums1: nums2, nums2: nums1)
}
guard nums1.count > 0 else {
return nums2[k - 1]
}
guard k > 1 else {
return min(nums1[0], nums2[0])
}
let num1Index = min(k / 2 - 1, nums1.count - 1)
let num2Index = min(k / 2 - 1, nums2.count - 1)
if nums1[num1Index] < nums2[num2Index] {
return findKthInSortedArrays(k: k - (num1Index + 1), nums1: Array(nums1[num1Index + 1 ..< nums1.count]), nums2: nums2)
} else {
return findKthInSortedArrays(k: k - (num2Index + 1), nums1: nums1, nums2: Array(nums2[num2Index + 1 ..< nums2.count]))
}
}
}
class Solution2 {
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
if nums1.count == 0 {
return findMedianInSortedArray(nums2)
}
if nums2.count == 0 {
return findMedianInSortedArray(nums1)
}
if (nums1.count + nums2.count) % 2 == 0 {
let lowerMedian = findKthInSortedArrays(k: (nums1.count + nums2.count) / 2, nums1: nums1, range1: 0 ... nums1.count - 1, nums2: nums2, range2: 0 ... nums2.count - 1)
let higherMedian = findKthInSortedArrays(k: (nums1.count + nums2.count) / 2 + 1, nums1: nums1, range1: 0 ... nums1.count - 1, nums2: nums2, range2: 0 ... nums2.count - 1)
return (Double(lowerMedian) + Double(higherMedian)) / 2;
} else {
return Double(findKthInSortedArrays(k: (nums1.count + nums2.count + 1) / 2, nums1: nums1, range1: 0 ... nums1.count - 1, nums2: nums2, range2: 0 ... nums2.count - 1))
}
}
func findMedianInSortedArray(_ nums: [Int]) -> Double {
if nums.count % 2 == 0 {
let lowerMedian = nums[nums.count / 2 - 1]
let higherMedian = nums[nums.count / 2]
return (Double(lowerMedian) + Double(higherMedian)) / 2
} else {
return Double(nums[nums.count / 2])
}
}
func findKthInSortedArrays(k: Int, nums1: [Int], range1: CountableClosedRange<Int>, nums2: [Int], range2: CountableClosedRange<Int>) -> Int {
let index1 = (range1.lowerBound + range1.upperBound) / 2
let index2 = (range2.lowerBound + range2.upperBound) / 2
let num1 = nums1[index1]
let num2 = nums2[index2]
if num1 < num2 {
return findKthInSortedArrays(k: k, lowerNums: nums1, lowerRange: range1, higherNums: nums2, higherRange: range2)
} else {
return findKthInSortedArrays(k: k, lowerNums: nums2, lowerRange: range2, higherNums: nums1, higherRange: range1)
}
}
func findKthInSortedArrays(k: Int, lowerNums: [Int], lowerRange: CountableClosedRange<Int>, higherNums: [Int], higherRange: CountableClosedRange<Int>) -> Int {
let lowerIndex = (lowerRange.lowerBound + lowerRange.upperBound) / 2
let higherIndex = (higherRange.lowerBound + higherRange.upperBound) / 2
let lowerMaxSortedIndex = lowerIndex + higherIndex + 1
let higherMinSortedIndex = lowerIndex + 1 + higherIndex + 1
if lowerMaxSortedIndex == k && higherIndex == higherRange.lowerBound {
return lowerNums[lowerIndex]
}
if higherMinSortedIndex == k && lowerIndex == lowerRange.upperBound {
return higherNums[higherIndex]
}
if lowerMaxSortedIndex < k {
if lowerIndex < lowerRange.upperBound {
let nextRange = lowerIndex + 1...lowerRange.upperBound
return findKthInSortedArrays(k: k, nums1: lowerNums, range1: nextRange, nums2: higherNums, range2: higherRange)
} else {
let nextRange = higherIndex + 1...higherRange.upperBound
return findKthInSortedArrays(k: k, nums1: lowerNums, range1: lowerRange, nums2: higherNums, range2: nextRange)
}
} else { // must have num2MinSortedIndex > k
if higherIndex > higherRange.lowerBound {
let nextRange = higherRange.lowerBound...higherIndex - 1
return findKthInSortedArrays(k: k, nums1: lowerNums, range1: lowerRange, nums2: higherNums, range2: nextRange)
} else {
let nextRange = lowerRange.lowerBound...lowerIndex - 1
return findKthInSortedArrays(k: k, nums1: lowerNums, range1: nextRange, nums2: higherNums, range2: higherRange)
}
}
}
}
Solution().findMedianSortedArrays([1,3], [2])
| mit | d1043c263c9b9e78435d7d7a1fbc3d5f | 45.167939 | 192 | 0.60334 | 3.378771 | false | false | false | false |
sstanic/Shopfred | Shopfred/Shopfred/DataBase/DbProviderFirebase.swift | 1 | 12813 | //
// DbProviderFirebase.swift
// Shopfred
//
// Created by Sascha Stanic on 7/22/17.
// Copyright © 2017 Sascha Stanic. All rights reserved.
//
import Foundation
import Firebase
import FirebaseDatabase
import CoreData
import Groot
/**
Database specific access provider for a Firebase DB.
The provider manages the database access and
encapsulates the vendor specific functionality.
- attention: This class is used by the **DbConnector**, do
not use it directly.
*/
class DbProviderFirebase : DbProvider {
// MARK: - Private Attributes
private let rootPath = "/sf-data/collection/active/"
private var dbReference: DatabaseReference?
private var rootReference: DatabaseReference?
private var syncHandle: UInt?
private var ignoreNextSyncFromDb: Bool!
// MARK: - Initializer
init() {
self.rootReference = nil
self.syncHandle = nil
self.ignoreNextSyncFromDb = false
}
// MARK: - Initialize Provider
func initialize() {
FirebaseApp.configure()
self.dbReference = Database.database().reference()
}
// MARK: - DbSync
func syncFromExternalDb(withId: String) {
if self.syncHandle == nil {
self.rootReference = self.dbReference!.child("\(rootPath)\(withId)")
self.syncHandle = self.rootReference!.observe(.value, with: { snapshot in
do {
print("Firebase db provider: sync from external db.")
if self.ignoreNextSyncFromDb {
// remark: Firebase triggers the sync always twice - the intention here is to skip the sync completely, but currently it will only skip the second one
print("Firebase db provider: 'ignore next sync'-flag set. Sync is skipped.")
self.ignoreNextSyncFromDb = false
return
}
let jsonDictionary = snapshot.value as! [String : Any]
let _: ShoppingSpace = try object(withEntityName: "ShoppingSpace", fromJSONDictionary: jsonDictionary, inContext: DataStore.sharedInstance().stack.context) as! ShoppingSpace
DataStore.sharedInstance().saveContextWithoutSync() { success, error in
// completion parameters not used
}
}
catch let error as NSError {
print("Firebase db provider: error in reading firebase tree: \(error)")
}
})
}
else {
print("Firebase db provider: Sync handle already set. Skipping setup to observe db.")
}
}
func syncToExternalDb(withId: String) {
print("Firebase db provider: sync to external db.")
self.ignoreNextSyncFromDb = true
var shoppingSpace: ShoppingSpace?
let fetchRequest = NSFetchRequest<ShoppingSpace>(entityName:"ShoppingSpace")
let predicate = NSPredicate(format: "id == %@", withId)
fetchRequest.predicate = predicate
fetchRequest.relationshipKeyPathsForPrefetching = ["users"]
fetchRequest.relationshipKeyPathsForPrefetching = ["users.userPreferences"]
fetchRequest.relationshipKeyPathsForPrefetching = ["shoppingContexts"]
fetchRequest.relationshipKeyPathsForPrefetching = ["shoppingContexts.shoppingLists"]
fetchRequest.relationshipKeyPathsForPrefetching = ["shoppingContexts.shoppingLists.items"]
fetchRequest.relationshipKeyPathsForPrefetching = ["units"]
fetchRequest.relationshipKeyPathsForPrefetching = ["categories"]
do {
let result = try DataStore.sharedInstance().stack.context.fetch(fetchRequest)
shoppingSpace = result[0]
}
catch {
let fetchError = error as NSError
print(fetchError)
}
let result = json(fromObject: shoppingSpace!)
self.dbReference!.child("\(rootPath)\(shoppingSpace!.id!)").setValue(result)
}
func stopSyncFromExternalDb() {
print("Firebase db provider: stop sync from external db.")
if let syncHandle = syncHandle {
if let rootRef = self.rootReference {
rootRef.removeObserver(withHandle: syncHandle)
self.syncHandle = nil
}
else {
print("Firebase db provider: Root reference not set, skipping stop.")
}
}
else {
print("Firebase db provider: SyncHandle not set, skipping stop.")
}
}
func getLastSyncDateFromExternalDb(forShoppingSpaceId id: String, completion: @escaping (_ success: Bool?, _ error: Error?, _ lastChange: String?) -> Void) {
let ref = self.dbReference!.child("\(rootPath)\(id)")
ref.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
completion(false, nil, nil)
return
}
if let lastChange = snapshot.childSnapshot(forPath: "lastChange").value as? String? {
completion(true, nil, lastChange)
}
else {
completion(false, nil, nil)
}
})
}
func getAllShoppingSpaces(forUser user: User, completion: @escaping (_ spaces: [String : Bool], _ error: Error?) -> Void) {
self.dbReference!.child("users/\(user.id!)").observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
completion([:], nil)
return
}
if let spaces = snapshot.childSnapshot(forPath: "shoppingSpaceIds").value as? [String : Bool] {
completion(spaces, nil)
}
else {
completion([:], nil)
}
})
}
func getShoppingSpace(withId: String, completion: @escaping (_ space: ShoppingSpace?, _ error: Error?) -> Void) {
let ref: DatabaseReference? = self.dbReference!.child("\(rootPath)\(withId)")
guard ref != nil
else {
let userInfo = [NSLocalizedDescriptionKey : "Root reference for path \(rootPath)\(withId) not found in DB. Please contact the Shopfred helpdesk."]
print(userInfo)
completion(nil, NSError(domain: "getShoppingSpace", code: 1, userInfo: userInfo))
return
}
ref!.observeSingleEvent(of: .value, with: { snapshot in
do {
print("Firebase db provider: get shopping space with id <\(withId)>")
let jsonDictionary = snapshot.value as! [String : Any]
let space: ShoppingSpace = try object(withEntityName: "ShoppingSpace", fromJSONDictionary: jsonDictionary, inContext: DataStore.sharedInstance().stack.context) as! ShoppingSpace
DataStore.sharedInstance().saveContextWithoutSync() { success, error in
completion(space, nil)
}
}
catch let error as NSError {
print("Firebase db provider: error in reading firebase tree: \(error)")
completion(nil, error)
}
})
}
// MARK: - DbAuth
func createUserAccount(email: String, password: String, completion: @escaping (_ uid: String?, _ error: Error?) -> Void) {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if error != nil {
completion(nil, error)
}
else {
completion(user!.uid, nil)
}
}
}
func deleteUser(id: String) {
// not implemented in this version
}
func setUserPassword(userId: String, oldPassword: String, newPassword: String) {
// not implemented in this version
}
func authenticateUser(email: String, password: String, completion: @escaping (_ uid: String?, _ error: Error?) -> Void) {
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
if error != nil {
completion(nil, error)
}
else {
completion(user!.uid, nil)
}
}
}
func addDbUser(dbUser: DbUser) {
let encoder = JSONEncoder()
let data = try! encoder.encode(dbUser)
do {
let d = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
self.dbReference!.child("users/\(dbUser.id)").setValue(nil)
self.dbReference!.child("users/\(dbUser.id)/").setValue(d)
}
catch {
print("Firebase db provider: error converting db user to json object")
}
}
func signOut(completion: @escaping (_ success: Bool, _ error: Error?) -> Void) {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
completion(true, nil)
}
catch let signOutError as NSError {
print ("Firebase db provider: error signing out: %@", signOutError)
completion(false, signOutError)
}
}
func getDbUser(withId: String, completion: @escaping (_ user: DbUser?, _ error: Error?) -> Void) {
self.dbReference!.child("users/\(withId)").observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
let userInfo = [NSLocalizedDescriptionKey : "User not found in DB. Please contact the Shopfred helpdesk."]
print(userInfo)
completion(nil, NSError(domain: "getUserFromDb", code: 1, userInfo: userInfo))
return
}
do {
let jsonDictionary = snapshot.value as! [String : Any]
let jsonData = try JSONSerialization.data(withJSONObject: jsonDictionary, options: .prettyPrinted)
let decoder = JSONDecoder()
let u = try decoder.decode(DbUser.self, from: jsonData)
completion(u, nil)
}
catch let error as NSError {
print("Firebase db provider: error decoding DbUser data: \(error)")
completion(nil, error)
}
})
}
func updateDbUser(forDbUser dbUser: DbUser, completion: @escaping (_ success: Bool?, _ error: Error?) -> Void) {
let encoder = JSONEncoder()
let data = try! encoder.encode(dbUser)
do {
let d = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
self.dbReference!.child("users/\(dbUser.id)/").setValue(d)
completion(true, nil)
}
catch {
let userInfo = [NSLocalizedDescriptionKey : "Firebase db provider: error converting db user to json object."]
print(userInfo)
completion(nil, NSError(domain: "updateDbUser", code: 1, userInfo: userInfo))
}
}
func addShoppingSpaceToDbUser(for user: User, with shoppingSpace: ShoppingSpace, completion: @escaping (_ success: Bool, _ error: Error?) -> Void) {
self.dbReference!.child("users/\(user.id!)/shoppingSpaceIds/").setValue([shoppingSpace.id! : true])
completion(true, nil)
}
// MARK: - Private Functions / Helper
private func jsonToString(json: AnyObject){
do {
let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
let convertedString = String(data: data1, encoding: String.Encoding.utf8)
print(convertedString!)
}
catch let myJSONError {
print(myJSONError)
}
}
}
| mit | e04f0ce802a172cf48addce0033daecd | 33.720867 | 193 | 0.537543 | 5.387721 | false | false | false | false |
brentdax/swift | test/DebugInfo/vector.swift | 20 | 681 | // RUN: %target-swift-frontend -emit-ir -g %s -o - -parse-stdlib | %FileCheck %s
// REQUIRES: OS=macosx
// CHECK: !DICompositeType(tag: DW_TAG_array_type, baseType: ![[FLOAT:[0-9]+]], size: 64, flags: DIFlagVector, elements: ![[ELTS:[0-9]+]])
// CHECK: ![[FLOAT]] = !DIBasicType(name: "$sBf32_D", size: 32, encoding: DW_ATE_float)
// CHECK: ![[ELTS]] = !{![[SR:[0-9]+]]}
// CHECK: ![[SR]] = !DISubrange(count: 2)
import Swift
public struct float2 {
public var _vector: Builtin.Vec2xFPIEEE32
public subscript(index: Int) -> Float {
get {
let elt = Builtin.extractelement_Vec2xFPIEEE32_Int32(_vector,
Int32(index)._value)
return Float(elt)
}
}
}
| apache-2.0 | dab2fafc3a40ad5200ec77dc4b882017 | 33.05 | 138 | 0.621145 | 3 | false | false | false | false |
fengzhihao123/FZHProjectInitializer | FZHProjectInitializer/FZHTabBarController/FZHNavigationController.swift | 1 | 3307 | //
// FZHNavigationController.swift
// 03-FZHTabBarController(swift)
//
// Created by 冯志浩 on 16/8/12.
// Copyright © 2016年 FZH. All rights reserved.
//
import UIKit
public enum TabbarHideStyle {
// animation
case animation
// normal
case normal
}
public class FZHNavigationController: UINavigationController, UINavigationControllerDelegate {
var tabbarHideStyle = TabbarHideStyle.normal
override public func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//pushViewController
override public func pushViewController(_ viewController: UIViewController, animated: Bool) {
if self.viewControllers.count > 0 {
let rootVC = self.viewControllers[0]
if tabbarHideStyle == TabbarHideStyle.animation {
UIView.animate(withDuration: 0.35, animations: {
rootVC.tabBarController?.tabBar.transform = CGAffineTransform(translationX: 0, y: 64)
})
} else {
viewController.hidesBottomBarWhenPushed = true
}
}
super.pushViewController(viewController, animated: animated)
}
//popToRootViewController
public override func popToRootViewController(animated: Bool) -> [UIViewController]? {
super.popToRootViewController(animated: animated)
tabBarHandler()
return nil
}
// popViewController
public override func popViewController(animated: Bool) -> UIViewController? {
super.popViewController(animated: animated)
tabBarHandler()
return self.viewControllers[0]
}
//popToViewController
public override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
super.popToViewController(viewController, animated: true)
tabBarHandler()
return nil
}
//MARK: UINavigationControllerDelegate - 解决TabBar重影
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
for tabBar in (tabBarController?.tabBar.subviews)! {
if tabBar.isKind(of: NSClassFromString("UITabBarButton")!) {
tabBar.removeFromSuperview()
}
}
}
//handler tabbar
func tabBarHandler() {
if self.viewControllers.count == 1 {
let rootVC = self.viewControllers[0]
if tabbarHideStyle == TabbarHideStyle.animation {
UIView.animate(withDuration: 0.35, animations: {
rootVC.tabBarController?.tabBar.transform = CGAffineTransform.identity
})
} else {
let rootVC = self.viewControllers[0]
rootVC.hidesBottomBarWhenPushed = false
}
}
}
}
| mit | 92e92be826373dc287d6a392506650cc | 33.631579 | 145 | 0.644985 | 5.529412 | false | false | false | false |
jonatassaraiva/learn-ios9-stanford | Calculator/Calculator/Model/Brain.swift | 1 | 3005 | //
// Brain.swift
// Calculator
//
// Created by Jonatas Saraiva on 06/02/17.
// Copyright © 2017 jonatas saraiva. All rights reserved.
//
import Foundation
struct PendingBinaryOperationInfo {
var binaryFunction: (Double, Double) -> Double
var firstOperand: Double
}
class Brain {
typealias PropertyList = AnyObject
private var accumulator = 0.0
private var internalProgram = [AnyObject]()
private var pending: PendingBinaryOperationInfo?
private enum Operatin {
case Constant(Double)
case Unary((Double) -> Double)
case Binary((Double, Double) -> Double)
case Equals
}
private var operations: Dictionary<String, Operatin> = [
"π" : Operatin.Constant(M_PI),
"e" : Operatin.Constant(M_E),
"√" : Operatin.Unary(sqrt),
"cos" : Operatin.Unary(cos),
"×" : Operatin.Binary({ $0 * $1 }),
"÷" : Operatin.Binary({ $0 / $1 }),
"+" : Operatin.Binary({ $0 + $1 }),
"−" : Operatin.Binary({ $0 - $1 }),
"=" : Operatin.Equals
]
private func executePendingBinarayOperation() {
if pending != nil {
self.accumulator = self.pending!.binaryFunction(self.pending!.firstOperand, self.accumulator)
self.pending = nil
}
}
private func clear() {
self.accumulator = 0.0
self.pending = nil
self.internalProgram.removeAll()
}
var result: Double {
get {
return self.accumulator
}
}
var program: PropertyList {
get {
return self.internalProgram as Brain.PropertyList
}
set {
self.clear()
if let arrayOfOps = newValue as? [AnyObject] {
for op in arrayOfOps {
if let operand = op as? Double {
self.setOperand(operand: operand)
} else if let operantion = op as? String {
self.performOperation(symblo: operantion)
}
}
}
}
}
func setOperand(operand: Double) {
self.accumulator = operand
self.internalProgram.append(operand as AnyObject)
}
func performOperation(symblo: String) {
self.internalProgram.append(symblo as AnyObject)
if let operation = self.operations[symblo] {
switch operation {
case .Binary(let function):
self.executePendingBinarayOperation()
self.pending = PendingBinaryOperationInfo(binaryFunction: function, firstOperand: self.accumulator)
case .Constant(let value):
self.accumulator = value
case .Equals:
self.executePendingBinarayOperation()
case .Unary(let function):
self.accumulator = function(self.accumulator)
}
}
}
}
| apache-2.0 | a203099dd8be50e4c39569658615e006 | 27.542857 | 115 | 0.545879 | 4.534039 | false | false | false | false |
zhuhaow/SpechtLite | SpechtLite/Manager/LoggerManager.swift | 1 | 506 | import Foundation
import CocoaLumberjack
import NEKit
class LoggerManager {
static var logger: DDLogger!
static func setUp() {
DDLog.add(DDTTYLogger.sharedInstance, with: .info)
let logger = DDFileLogger()!
logger.rollingFrequency = TimeInterval(60*60*3)
logger.logFileManager.maximumNumberOfLogFiles = 1
DDLog.add(logger, with: .info)
self.logger = logger
ObserverFactory.currentFactory = SPObserverFactory()
}
}
| gpl-3.0 | 0d4e15017f6315a8b870dec127e982c6 | 25.631579 | 60 | 0.658103 | 4.558559 | false | false | false | false |
denissimon/prediction-builder-swift | Sources/PredictionBuilder.swift | 1 | 4952 | //
// PredictionBuilder.swift
// https://github.com/denissimon/prediction-builder-swift
//
// Created by Denis Simon on 12/27/2016
// Copyright © 2016 PredictionBuilder. All rights reserved.
//
import Foundation
public enum ArgumentError: Error, Equatable {
case general(msg: String)
}
public struct PredictionResult {
public let lnModel: String
public let cor, x, y: Double
public init(lnModel: String, cor: Double, x: Double, y: Double) {
self.lnModel = lnModel
self.cor = cor
self.x = x
self.y = y
}
}
open class PredictionBuilder {
public private(set) var x = Double()
public private(set) var count = Int()
public private(set) var xVector = [Double]()
public private(set) var yVector = [Double]()
public private(set) var data = [[Double]]()
public init() {}
public init(x: Double, data: [[Double]]) {
set(x: x, data: data)
}
/**
Sets / overrides instance properties
*/
public func set(x: Double, data: [[Double]]? = nil) {
self.x = x
if let data = data {
self.count = data.count
self.xVector = []
self.yVector = []
self.data = data
.map ({
if $0.indices.contains(0) && $0.indices.contains(1) {
self.xVector.append($0[0])
self.yVector.append($0[1])
}
return $0
})
}
}
private func square(v: Double) -> Double {
return v * v
}
/**
Sum of the vector values
*/
private func sum(vector: [Double]) -> Double {
return vector
.reduce(0, +)
}
/**
Sum of the vector squared values
*/
private func sumSquared(vector: [Double]) -> Double {
return vector
.map({
square(v: $0)
})
.reduce(0, +)
}
/**
Sum of the product of x and y
*/
private func sumXY(data: [[Double]]) -> Double {
return data
.map({
$0[0] * $0[1]
})
.reduce(0, +)
}
/**
The dispersion
Dv = (Σv² / N) - (Σv / N)²
*/
private func dispersion(v: String) -> Double {
let sumSquared = [
"x": { self.sumSquared(vector: self.xVector) },
"y": { self.sumSquared(vector: self.yVector) }
]
let sum = [
"x": { self.sum(vector: self.xVector) },
"y": { self.sum(vector: self.yVector) }
]
return (sumSquared[v]!() / Double(count)) -
square(v: sum[v]!() / Double(count))
}
/**
The intercept
a = (ΣY - b(ΣX)) / N
*/
private func aIntercept(b: Double) -> Double {
return (sum(vector: yVector) / Double(count)) -
(b * (sum(vector: xVector) / Double(count)))
}
/**
The slope, or the regression coefficient
b = ((ΣXY / N) - (ΣX / N)(ΣY / N)) / (Σv² / N) - (Σv / N)²
*/
private func bSlope() -> Double {
return ((sumXY(data: data) / Double(count)) -
((sum(vector: xVector) / Double(count)) *
(sum(vector: yVector) / Double(count)))) /
dispersion(v: "x")
}
/**
The Pearson's correlation coefficient
Rxy = b * (√Dx / √Dy)
*/
private func corCoefficient(b: Double) -> Double {
return b * (sqrt(dispersion(v: "x")) / sqrt(dispersion(v: "y")))
}
/**
Creats a linear model that fits the data.
The resulting equation has the form: h(x) = a + bx
*/
private func createModel(a: Double, b: Double) -> (_ x: Double)->Double {
return { (x: Double)->Double in
return a + b*x
}
}
private func round_(number: Double) -> Double {
return round(100000 * number) / 100000
}
/**
Builds a prediction of the expected value of y for a given x, based on a linear regression model.
*/
public func build() throws -> PredictionResult {
// Check the number of observations
guard count >= 3 else {
throw ArgumentError.general(msg: "The dataset should contain a minimum of 3 observations.")
}
// Check the number of x and y
guard count == xVector.count else {
throw ArgumentError.general(msg: "Mismatch in the number of x and y in the dataset.")
}
let b = round_(number: bSlope())
let a = round_(number: aIntercept(b: b))
let model = createModel(a: a, b: b)
let y = round_(number: model(x))
return PredictionResult(
lnModel: "\(a)+\(b)x",
cor: round_(number: corCoefficient(b: b)),
x: x,
y: y
)
}
}
| mit | 8057faf228f275676fe1b257e55d469d | 26.10989 | 103 | 0.497163 | 3.869804 | false | false | false | false |
edx/edx-app-ios | Source/OEXMicrosoftAuthProvider.swift | 1 | 2059 | //
// OEXMicrosoftAuthProvider.swift
// edX
//
// Created by Salman on 07/08/2018.
// Copyright © 2018 edX. All rights reserved.
//
import UIKit
class OEXMicrosoftAuthProvider: NSObject, OEXExternalAuthProvider {
override init() {
super.init()
}
var displayName: String {
return Strings.microsoft
}
var backendName: String {
return "azuread-oauth2"
}
func freshAuthButton() -> UIButton {
let button = OEXExternalAuthProviderButton()
button.provider = self
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 3, bottom: 0, right: -3)
button.setImage(UIImage(named: "icon_microsoft_white"), for: .normal)
button.useBackgroundImage(of: UIColor(red: 47.0/255.0, green: 47.0/255.0, blue: 47.0/255.0, alpha: 1.0))
return button
}
func authorizeService(from controller: UIViewController, requestingUserDetails loadUserDetails: Bool, withCompletion completion: @escaping (String?, OEXRegisteringUserDetails?, Error?) -> Void) {
MicrosoftSocial.shared.loginFromController(controller: controller) { (account, token, error) in
if let error = error {
completion(token, nil, error)
} else if loadUserDetails {
// load user details
MicrosoftSocial.shared.getUser(completion: { (user) in
let profile = OEXRegisteringUserDetails()
guard let account = user.accountClaims,
let name = account["name"] as? String,
let email = account["email"] as? String else {
completion(token, nil, error)
return
}
profile.name = name
profile.email = email
completion(token, profile, error)
})
} else {
completion(token, nil, error)
}
}
}
}
| apache-2.0 | 8e13941a206333ac4eb7cbde7cd23757 | 33.3 | 199 | 0.552964 | 4.830986 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/ViewRelated/Plans/PlanComparisonViewController.swift | 2 | 2965 | import UIKit
import Gridicons
import WordPressShared
class PlanComparisonViewController: PagedViewController {
lazy fileprivate var cancelXButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: Gridicon.iconOfType(.cross), style: .plain, target: self, action: #selector(PlanComparisonViewController.closeTapped))
button.accessibilityLabel = NSLocalizedString("Close", comment: "Dismiss the current view")
return button
}()
@IBAction func closeTapped() {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = cancelXButton
fetchFeatures()
}
let siteID: Int
let pricedPlans: [PricedPlan]
let activePlan: Plan
let initialPlan: Plan
let service: PlanService<StoreKitStore>
// Keep a more specific reference to the view controllers rather than force
// downcast viewControllers.
fileprivate let detailViewControllers: [PlanDetailViewController]
init(sitePricedPlans: SitePricedPlans, initialPlan: Plan, service: PlanService<StoreKitStore>) {
self.siteID = sitePricedPlans.siteID
self.pricedPlans = sitePricedPlans.availablePlans
self.activePlan = sitePricedPlans.activePlan
self.initialPlan = initialPlan
self.service = service
let viewControllers: [PlanDetailViewController] = pricedPlans.map({ (plan, price) in
let controller = PlanDetailViewController.controllerWithPlan(plan, siteID: sitePricedPlans.siteID, activePlan: sitePricedPlans.activePlan, price: price)
return controller
})
self.detailViewControllers = viewControllers
let initialIndex = pricedPlans.index { plan, _ in
return plan == initialPlan
}
super.init(viewControllers: viewControllers, initialIndex: initialIndex!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func fetchFeatures() {
service.updateAllPlanFeatures(
success: { [weak self, service] features in
self?.detailViewControllers.forEach { controller in
let plan = controller.viewModel.plan
do {
let groups = try service.featureGroupsForPlan(plan, features: features)
controller.viewModel = controller.viewModel.withFeatures(.ready(groups))
} catch {
controller.viewModel = controller.viewModel.withFeatures(.error(String(describing: error)))
}
}
}, failure: { [weak self] error in
self?.detailViewControllers.forEach { controller in
controller.viewModel = controller.viewModel.withFeatures(.error(String(describing: error)))
}
})
}
}
| gpl-2.0 | e572c2e8fbe7fcc4ea50d9263efa83e0 | 38.013158 | 164 | 0.656661 | 5.165505 | false | false | false | false |
zitao0322/ShopCar | Shoping_Car/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift | 10 | 6470 | //
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents an object that is both an observable sequence as well as an observer.
Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
/**
Indicates whether the subject has any observers
*/
public var hasObservers: Bool {
_lock.lock(); defer { _lock.unlock() }
return _observers.count > 0
}
private var _lock = NSRecursiveLock()
// state
private var _disposed = false
private var _stoppedEvent = nil as Event<Element>?
private var _observers = Bag<AnyObserver<Element>>()
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
func unsubscribe(key: DisposeKey) {
abstractMethod()
}
/**
Notifies all subscribed observers about next event.
- parameter event: Event to send to the observers.
*/
public func on(event: Event<E>) {
abstractMethod()
}
/**
Returns observer interface for subject.
*/
public func asObserver() -> SubjectObserverType {
return self
}
/**
Unsubscribe all observers and release resources.
*/
public func dispose() {
}
/**
Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
- parameter bufferSize: Maximal number of elements to replay to observer after subscription.
- returns: New instance of replay subject.
*/
public static func create(bufferSize bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
/**
Creates a new instance of `ReplaySubject` that buffers all the elements of a sequence.
To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable'
number of elements.
*/
public static func createUnbounded() -> ReplaySubject<Element> {
return ReplayAll()
}
}
class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
func trim() {
abstractMethod()
}
func addValueToBuffer(value: Element) {
abstractMethod()
}
func replayBuffer(observer: AnyObserver<Element>) {
abstractMethod()
}
override func on(event: Event<Element>) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_on(event)
}
func _synchronized_on(event: Event<E>) {
if _disposed {
return
}
if _stoppedEvent != nil {
return
}
switch event {
case .Next(let value):
addValueToBuffer(value)
trim()
_observers.on(event)
case .Error, .Completed:
_stoppedEvent = event
trim()
_observers.on(event)
_observers.removeAll()
}
}
override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
_lock.lock(); defer { _lock.unlock() }
return _synchronized_subscribe(observer)
}
func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable {
if _disposed {
observer.on(.Error(RxError.Disposed(object: self)))
return NopDisposable.instance
}
let AnyObserver = observer.asObserver()
replayBuffer(AnyObserver)
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return NopDisposable.instance
}
else {
let key = _observers.insert(AnyObserver)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(disposeKey: DisposeKey) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_unsubscribe(disposeKey)
}
func _synchronized_unsubscribe(disposeKey: DisposeKey) {
if _disposed {
return
}
_ = _observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
synchronizedDispose()
}
func synchronizedDispose() {
_lock.lock(); defer { _lock.unlock() }
_synchronized_dispose()
}
func _synchronized_dispose() {
_disposed = true
_stoppedEvent = nil
_observers.removeAll()
}
}
final class ReplayOne<Element> : ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(value: Element) {
_value = value
}
override func replayBuffer(observer: AnyObserver<Element>) {
if let value = _value {
observer.on(.Next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_value = nil
}
}
class ReplayManyBase<Element> : ReplayBufferBase<Element> {
private var _queue: Queue<Element>
init(queueSize: Int) {
_queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(value: Element) {
_queue.enqueue(value)
}
override func replayBuffer(observer: AnyObserver<E>) {
for item in _queue {
observer.on(.Next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_queue = Queue(capacity: 0)
}
}
final class ReplayMany<Element> : ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
_bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while _queue.count > _bufferSize {
_queue.dequeue()
}
}
}
final class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
} | mit | 8703c92e3030da7f713fcbda7db2d306 | 23.60076 | 114 | 0.589736 | 4.831217 | false | false | false | false |
AlexMoffat/timecalc | TimeCalc/MillisFormatter.swift | 1 | 2930 | /*
* Copyright (c) 2017 Alex Moffat
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of mosquitto nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
/**
* Format a value in milliseconds as a number of days, hours, minutes, seconds and milliseconds. You can choose the larges unit to
* use, for example you can have a format with a largest unit of minutes. Zero values are not output, so 2d 10m not 2d 0h 10m.
*/
class MillisFormatter {
typealias Unit = (millis: Int, suffix: String)
static let units = [
(millis: 24 * 60 * 60 * 1000, suffix: "d"),
(millis: 60 * 60 * 1000, suffix: "h"),
(millis: 60 * 1000, suffix: "m"),
(millis: 1000, suffix: "s"),
(millis: 1, suffix: "ms")
]
func format(ms: Int, withLargestUnit: String = "d") -> String {
let sign = ms < 0 ? "-" : ""
var remainingValue = abs(ms)
var values = [String]()
var format = false
for unit in MillisFormatter.units {
if !format && withLargestUnit == unit.suffix {
format = true
}
if format && remainingValue >= unit.millis {
values.append(sign + String(remainingValue / unit.millis) + unit.suffix)
remainingValue = remainingValue % unit.millis
}
}
assert(remainingValue == 0)
return values.joined(separator: " ")
}
}
| bsd-3-clause | 38a99524980b61c1c688bdc827e3b4a7 | 41.463768 | 130 | 0.657338 | 4.486983 | false | false | false | false |
alblue/swift | stdlib/public/SDK/Foundation/URL.swift | 6 | 68244 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
fileprivate var _values: [URLResourceKey: Any]
fileprivate var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
fileprivate init(keys: Set<URLResourceKey>, values: [URLResourceKey: Any]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : __owned Any?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue as NSString?
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue as NSObject?
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue as NSDate?
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue as NSURL?
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : Any] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
@available(macOS 10.11, iOS 9.0, *)
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(macOS)
/// True if the resource is scriptable. Only applies to applications.
@available(macOS 10.11, *)
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The file system object's security information encapsulated in a FileSecurity object.
public var fileSecurity: NSFileSecurity? {
get { return _get(.fileSecurityKey) }
set { _set(.fileSecurityKey, newValue: newValue) }
}
/// True if resource should be excluded from backups, false otherwise.
///
/// This property is only useful for excluding cache and other application support files which are not needed in a backup. Some operations commonly made to user documents will cause this property to be reset to false and so this property should not be used on user documents.
public var isExcludedFromBackup: Bool? {
get { return _get(.isExcludedFromBackupKey) }
set { _set(.isExcludedFromBackupKey, newValue: newValue) }
}
#if os(macOS)
/// The array of Tag names.
public var tagNames: [String]? { return _get(.tagNamesKey) }
#endif
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The URL's path as a canonical absolute file system path.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var canonicalPath: String? { return _get(.canonicalPathKey) }
/// True if this URL is a file system trigger directory. Traversing or opening a file system trigger will cause an attempt to mount a file system on the trigger directory.
public var isMountTrigger: Bool? { return _get(.isMountTriggerKey) }
/// An opaque generation identifier which can be compared using `==` to determine if the data in a document has been modified.
///
/// For URLs which refer to the same file inode, the generation identifier will change when the data in the file's data fork is changed (changes to extended attributes or other file system metadata do not change the generation identifier). For URLs which refer to the same directory inode, the generation identifier will change when direct children of that directory are added, removed or renamed (changes to the data of the direct children of that directory will not change the generation identifier). The generation identifier is persistent across system restarts. The generation identifier is tied to a specific document on a specific volume and is not transferred when the document is copied to another volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var generationIdentifier: (NSCopying & NSCoding & NSSecureCoding & NSObjectProtocol)? { return _get(.generationIdentifierKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save" operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
@available(macOS 10.10, iOS 8.0, *)
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
#if os(macOS)
/// The quarantine properties as defined in LSQuarantine.h. To remove quarantine information from a file, pass `nil` as the value when setting this property.
@available(macOS 10.10, *)
public var quarantineProperties: [String : Any]? {
get {
let value = _values[.quarantinePropertiesKey]
// If a caller has caused us to stash NSNull in the dictionary (via set), make sure to return nil instead of NSNull
if value is NSNull {
return nil
} else {
return value as? [String : Any]
}
}
set {
// Use NSNull for nil, a special case for deleting quarantine
// properties
_set(.quarantinePropertiesKey, newValue: newValue ?? NSNull())
}
}
#endif
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// The user-visible volume format.
public var volumeLocalizedFormatDescription : String? { return _get(.volumeLocalizedFormatDescriptionKey) }
/// Total volume capacity in bytes.
public var volumeTotalCapacity : Int? { return _get(.volumeTotalCapacityKey) }
/// Total free space in bytes.
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
#if os(macOS) || os(iOS)
/// Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources. "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
/// Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
/// This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForImportantUsage: Int64? { return _get(.volumeAvailableCapacityForImportantUsageKey) }
/// Total available capacity in bytes for "Opportunistic" resources, including space expected to be cleared by purging non-essential and cached resources. "Opportunistic" means something that the user is likely to want but does not expect to be present on the local system, but is ultimately non-essential and replaceable. This would include items that will be created or downloaded without an explicit request from the user on the current device.
/// Examples: A background download of a newly available episode of a TV series that a user has been recently watching, a piece of content explicitly requested on another device, and a new document saved to a network server by the current user from another device.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var volumeAvailableCapacityForOpportunisticUsage: Int64? { return _get(.volumeAvailableCapacityForOpportunisticUsageKey) }
#endif
/// Total number of resources on the volume.
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
/// true if the volume format supports persistent object identifiers and can look up file system objects by their IDs.
public var volumeSupportsPersistentIDs : Bool? { return _get(.volumeSupportsPersistentIDsKey) }
/// true if the volume format supports symbolic links.
public var volumeSupportsSymbolicLinks : Bool? { return _get(.volumeSupportsSymbolicLinksKey) }
/// true if the volume format supports hard links.
public var volumeSupportsHardLinks : Bool? { return _get(.volumeSupportsHardLinksKey) }
/// true if the volume format supports a journal used to speed recovery in case of unplanned restart (such as a power outage or crash). This does not necessarily mean the volume is actively using a journal.
public var volumeSupportsJournaling : Bool? { return _get(.volumeSupportsJournalingKey) }
/// true if the volume is currently using a journal for speedy recovery after an unplanned restart.
public var volumeIsJournaling : Bool? { return _get(.volumeIsJournalingKey) }
/// true if the volume format supports sparse files, that is, files which can have 'holes' that have never been written to, and thus do not consume space on disk. A sparse file may have an allocated size on disk that is less than its logical length.
public var volumeSupportsSparseFiles : Bool? { return _get(.volumeSupportsSparseFilesKey) }
/// For security reasons, parts of a file (runs) that have never been written to must appear to contain zeroes. true if the volume keeps track of allocated but unwritten runs of a file so that it can substitute zeroes without actually writing zeroes to the media.
public var volumeSupportsZeroRuns : Bool? { return _get(.volumeSupportsZeroRunsKey) }
/// true if the volume format treats upper and lower case characters in file and directory names as different. Otherwise an upper case character is equivalent to a lower case character, and you can't have two names that differ solely in the case of the characters.
public var volumeSupportsCaseSensitiveNames : Bool? { return _get(.volumeSupportsCaseSensitiveNamesKey) }
/// true if the volume format preserves the case of file and directory names. Otherwise the volume may change the case of some characters (typically making them all upper or all lower case).
public var volumeSupportsCasePreservedNames : Bool? { return _get(.volumeSupportsCasePreservedNamesKey) }
/// true if the volume supports reliable storage of times for the root directory.
public var volumeSupportsRootDirectoryDates : Bool? { return _get(.volumeSupportsRootDirectoryDatesKey) }
/// true if the volume supports returning volume size values (`volumeTotalCapacity` and `volumeAvailableCapacity`).
public var volumeSupportsVolumeSizes : Bool? { return _get(.volumeSupportsVolumeSizesKey) }
/// true if the volume can be renamed.
public var volumeSupportsRenaming : Bool? { return _get(.volumeSupportsRenamingKey) }
/// true if the volume implements whole-file flock(2) style advisory locks, and the O_EXLOCK and O_SHLOCK flags of the open(2) call.
public var volumeSupportsAdvisoryFileLocking : Bool? { return _get(.volumeSupportsAdvisoryFileLockingKey) }
/// true if the volume implements extended security (ACLs).
public var volumeSupportsExtendedSecurity : Bool? { return _get(.volumeSupportsExtendedSecurityKey) }
/// true if the volume should be visible via the GUI (i.e., appear on the Desktop as a separate volume).
public var volumeIsBrowsable : Bool? { return _get(.volumeIsBrowsableKey) }
/// The largest file size (in bytes) supported by this file system, or nil if this cannot be determined.
public var volumeMaximumFileSize : Int? { return _get(.volumeMaximumFileSizeKey) }
/// true if the volume's media is ejectable from the drive mechanism under software control.
public var volumeIsEjectable : Bool? { return _get(.volumeIsEjectableKey) }
/// true if the volume's media is removable from the drive mechanism.
public var volumeIsRemovable : Bool? { return _get(.volumeIsRemovableKey) }
/// true if the volume's device is connected to an internal bus, false if connected to an external bus, or nil if not available.
public var volumeIsInternal : Bool? { return _get(.volumeIsInternalKey) }
/// true if the volume is automounted. Note: do not mistake this with the functionality provided by kCFURLVolumeSupportsBrowsingKey.
public var volumeIsAutomounted : Bool? { return _get(.volumeIsAutomountedKey) }
/// true if the volume is stored on a local device.
public var volumeIsLocal : Bool? { return _get(.volumeIsLocalKey) }
/// true if the volume is read-only.
public var volumeIsReadOnly : Bool? { return _get(.volumeIsReadOnlyKey) }
/// The volume's creation date, or nil if this cannot be determined.
public var volumeCreationDate : Date? { return _get(.volumeCreationDateKey) }
/// The `URL` needed to remount a network volume, or nil if not available.
public var volumeURLForRemounting : URL? { return _get(.volumeURLForRemountingKey) }
/// The volume's persistent `UUID` as a string, or nil if a persistent `UUID` is not available for the volume.
public var volumeUUIDString : String? { return _get(.volumeUUIDStringKey) }
/// The name of the volume
public var volumeName : String? {
get { return _get(.volumeNameKey) }
set { _set(.volumeNameKey, newValue: newValue) }
}
/// The user-presentable name of the volume
public var volumeLocalizedName : String? { return _get(.volumeLocalizedNameKey) }
/// true if the volume is encrypted.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsEncrypted : Bool? { return _get(.volumeIsEncryptedKey) }
/// true if the volume is the root filesystem.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeIsRootFileSystem : Bool? { return _get(.volumeIsRootFileSystemKey) }
/// true if the volume supports transparent decompression of compressed files using decmpfs.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
/// true if the volume supports clonefile(2).
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsFileCloning : Bool? { return _get(.volumeSupportsFileCloningKey) }
/// true if the volume supports renamex_np(2)'s RENAME_SWAP option.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsSwapRenaming : Bool? { return _get(.volumeSupportsSwapRenamingKey) }
/// true if the volume supports renamex_np(2)'s RENAME_EXCL option.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public var volumeSupportsExclusiveRenaming : Bool? { return _get(.volumeSupportsExclusiveRenamingKey) }
/// true if the volume supports making files immutable with isUserImmutable or isSystemImmutable.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var volumeSupportsImmutableFiles : Bool? { return _get(.volumeSupportsImmutableFilesKey) }
/// true if the volume supports setting POSIX access permissions with fileSecurity.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public var volumeSupportsAccessPermissions : Bool? { return _get(.volumeSupportsAccessPermissionsKey) }
/// true if this item is synced to the cloud, false if it is only a local file.
public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
/// true if this item has conflicts outstanding.
public var ubiquitousItemHasUnresolvedConflicts : Bool? { return _get(.ubiquitousItemHasUnresolvedConflictsKey) }
/// true if data is being downloaded for this item.
public var ubiquitousItemIsDownloading : Bool? { return _get(.ubiquitousItemIsDownloadingKey) }
/// true if there is data present in the cloud for this item.
public var ubiquitousItemIsUploaded : Bool? { return _get(.ubiquitousItemIsUploadedKey) }
/// true if data is being uploaded for this item.
public var ubiquitousItemIsUploading : Bool? { return _get(.ubiquitousItemIsUploadingKey) }
/// returns the download status of this item.
public var ubiquitousItemDownloadingStatus : URLUbiquitousItemDownloadingStatus? { return _get(.ubiquitousItemDownloadingStatusKey) }
/// returns the error when downloading the item from iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemDownloadingError : NSError? { return _get(.ubiquitousItemDownloadingErrorKey) }
/// returns the error when uploading the item to iCloud failed, see the NSUbiquitousFile section in FoundationErrors.h
public var ubiquitousItemUploadingError : NSError? { return _get(.ubiquitousItemUploadingErrorKey) }
/// returns whether a download of this item has already been requested with an API like `startDownloadingUbiquitousItem(at:) throws`.
@available(macOS 10.10, iOS 8.0, *)
public var ubiquitousItemDownloadRequested : Bool? { return _get(.ubiquitousItemDownloadRequestedKey) }
/// returns the name of this item's container as displayed to users.
@available(macOS 10.10, iOS 8.0, *)
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
#if os(macOS) || os(iOS)
// true if ubiquitous item is shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousItemIsShared: Bool? { return _get(.ubiquitousItemIsSharedKey) }
// The current user's role for this shared item, or nil if not shared
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserRole: URLUbiquitousSharedItemRole? { return _get(.ubiquitousSharedItemCurrentUserRoleKey) }
// The permissions for the current user, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemCurrentUserPermissions: URLUbiquitousSharedItemPermissions? { return _get(.ubiquitousSharedItemCurrentUserPermissionsKey) }
// The name components for the owner, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemOwnerNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemOwnerNameComponentsKey) }
// The name components for the most recent editor, or nil if not shared.
@available(macOS 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
public var ubiquitousSharedItemMostRecentEditorNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemMostRecentEditorNameComponentsKey) }
#endif
#if !os(macOS)
/// The protection level for this file
@available(iOS 9.0, *)
public var fileProtection : URLFileProtection? { return _get(.fileProtectionKey) }
#endif
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL : ReferenceConvertible, Equatable {
public typealias ReferenceType = NSURL
fileprivate var _url : NSURL
public typealias BookmarkResolutionOptions = NSURL.BookmarkResolutionOptions
public typealias BookmarkCreationOptions = NSURL.BookmarkCreationOptions
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: __shared String) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initialize with string, relative to another URL.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: __shared String, relativeTo url: __shared URL?) {
guard !string.isEmpty else { return nil }
if let inner = NSURL(string: string, relativeTo: url) {
_url = URL._converted(from: inner)
} else {
return nil
}
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
@available(macOS 10.11, iOS 9.0, *)
public init(fileURLWithPath path: __shared String, isDirectory: Bool, relativeTo base: __shared URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
@available(macOS 10.11, iOS 9.0, *)
public init(fileURLWithPath path: __shared String, relativeTo base: __shared URL?) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: __shared String, isDirectory: Bool) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory))
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: __shared String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
/// If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected. If the URL cannot be formed then this will return nil.
@available(macOS 10.11, iOS 9.0, *)
public init?(dataRepresentation: __shared Data, relativeTo url: __shared URL?, isAbsolute: Bool = false) {
guard dataRepresentation.count > 0 else { return nil }
if isAbsolute {
_url = URL._converted(from: NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url))
} else {
_url = URL._converted(from: NSURL(dataRepresentation: dataRepresentation, relativeTo: url))
}
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, obsoleted: 4.2)
public init?(resolvingBookmarkData data: __shared Data, options: BookmarkResolutionOptions = [], relativeTo url: __shared URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Initializes a URL that refers to a location specified by resolving bookmark data.
@available(swift, introduced: 4.2)
public init(resolvingBookmarkData data: __shared Data, options: BookmarkResolutionOptions = [], relativeTo url: __shared URL? = nil, bookmarkDataIsStale: inout Bool) throws {
var stale : ObjCBool = false
_url = URL._converted(from: try NSURL(resolvingBookmarkData: data, options: options, relativeTo: url, bookmarkDataIsStale: &stale))
bookmarkDataIsStale = stale.boolValue
}
/// Creates and initializes an NSURL that refers to the location specified by resolving the alias file at url. If the url argument does not refer to an alias file as defined by the NSURLIsAliasFileKey property, the NSURL returned is the same as url argument. This method fails and returns nil if the url argument is unreachable, or if the original file or directory could not be located or is not reachable, or if the original file or directory is on a volume that could not be located or mounted. The URLBookmarkResolutionWithSecurityScope option is not supported by this method.
@available(macOS 10.10, iOS 8.0, *)
public init(resolvingAliasFileAt url: __shared URL, options: BookmarkResolutionOptions = []) throws {
self.init(reference: try NSURL(resolvingAliasFileAt: url, options: options))
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeTo baseURL: __shared URL?) {
_url = URL._converted(from: NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL))
}
public var hashValue: Int {
return _url.hash
}
// MARK: -
/// Returns the data representation of the URL's relativeString.
///
/// If the URL was initialized with `init?(dataRepresentation:relativeTo:isAbsolute:)`, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the `relativeString` encoded with UTF8 string encoding.
@available(macOS 10.11, iOS 9.0, *)
public var dataRepresentation: Data {
return _url.dataRepresentation
}
// MARK: -
// Future implementation note:
// NSURL (really CFURL, which provides its implementation) has quite a few quirks in its processing of some more esoteric (and some not so esoteric) strings. We would like to move much of this over to the more modern NSURLComponents, but binary compat concerns have made this difficult.
// Hopefully soon, we can replace some of the below delegation to NSURL with delegation to NSURLComponents instead. It cannot be done piecemeal, because otherwise we will get inconsistent results from the API.
/// Returns the absolute string for the URL.
public var absoluteString: String {
if let string = _url.absoluteString {
return string
} else {
// This should never fail for non-file reference URLs
return ""
}
}
/// The relative portion of a URL.
///
/// If `baseURL` is nil, or if the receiver is itself absolute, this is the same as `absoluteString`.
public var relativeString: String {
return _url.relativeString
}
/// Returns the base URL.
///
/// If the URL is itself absolute, then this value is nil.
public var baseURL: URL? {
return _url.baseURL
}
/// Returns the absolute URL.
///
/// If the URL is itself absolute, this will return self.
public var absoluteURL: URL {
if let url = _url.absoluteURL {
return url
} else {
// This should never fail for non-file reference URLs
return self
}
}
// MARK: -
/// Returns the scheme of the URL.
public var scheme: String? {
return _url.scheme
}
/// Returns true if the scheme is `file:`.
public var isFileURL: Bool {
return _url.isFileURL
}
// This thing was never really part of the URL specs
@available(*, unavailable, message: "Use `path`, `query`, and `fragment` instead")
public var resourceSpecifier: String {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the host component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var host: String? {
return _url.host
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the port component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var port: Int? {
return _url.port?.intValue
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the user component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var user: String? {
return _url.user
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the password component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var password: String? {
return _url.password
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the path component of the URL; otherwise it returns an empty string.
///
/// If the URL contains a parameter string, it is appended to the path with a `;`.
/// - note: This function will resolve against the base `URL`.
/// - returns: The path, or an empty string if the URL has an empty path.
public var path: String {
if let parameterString = _url.parameterString {
if let path = _url.path {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.path {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the relative path of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// If the URL contains a parameter string, it is appended to the path with a `;`.
///
/// - note: This function will resolve against the base `URL`.
/// - returns: The relative path, or an empty string if the URL has an empty path.
public var relativePath: String {
if let parameterString = _url.parameterString {
if let path = _url.relativePath {
return path + ";" + parameterString
} else {
return ";" + parameterString
}
} else if let path = _url.relativePath {
return path
} else {
return ""
}
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the fragment component of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var fragment: String? {
return _url.fragment
}
@available(*, unavailable, message: "use the 'path' property")
public var parameterString: String? {
fatalError()
}
/// If the URL conforms to RFC 1808 (the most common form of URL), returns the query of the URL; otherwise it returns nil.
///
/// - note: This function will resolve against the base `URL`.
public var query: String? {
return _url.query
}
/// Returns true if the URL path represents a directory.
@available(macOS 10.11, iOS 9.0, *)
public var hasDirectoryPath: Bool {
return _url.hasDirectoryPath
}
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
@available(macOS 10.9, iOS 7.0, *)
public func withUnsafeFileSystemRepresentation<ResultType>(_ block: (UnsafePointer<Int8>?) throws -> ResultType) rethrows -> ResultType {
return try block(_url.fileSystemRepresentation)
}
// MARK: -
// MARK: Path manipulation
/// Returns the path components of the URL, or an empty array if the path is an empty string.
public var pathComponents: [String] {
// In accordance with our above change to never return a nil path, here we return an empty array.
return _url.pathComponents ?? []
}
/// Returns the last path component of the URL, or an empty string if the path is an empty string.
public var lastPathComponent: String {
return _url.lastPathComponent ?? ""
}
/// Returns the path extension of the URL, or an empty string if the path is an empty string.
public var pathExtension: String {
return _url.pathExtension ?? ""
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: If `true`, then a trailing `/` is added to the resulting path.
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL {
if let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
return self
}
}
}
/// Returns a URL constructed by appending the given path component to self.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public func appendingPathComponent(_ pathComponent: String) -> URL {
if let result = _url.appendingPathComponent(pathComponent) {
return result
} else {
// Now we need to do something more expensive
if var c = URLComponents(url: self, resolvingAgainstBaseURL: true) {
c.path = (c.path as NSString).appendingPathComponent(pathComponent)
if let result = c.url {
return result
} else {
// Couldn't get url from components
// Ultimate fallback:
return self
}
} else {
// Ultimate fallback:
return self
}
}
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingLastPathComponent() -> URL {
// This is a slight behavior change from NSURL, but better than returning "http://www.example.com../".
if path.isEmpty {
return self
}
if let result = _url.deletingLastPathComponent.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Returns a URL constructed by appending the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
///
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public func appendingPathExtension(_ pathExtension: String) -> URL {
if path.isEmpty {
return self
}
if let result = _url.appendingPathExtension(pathExtension) {
return result
} else {
return self
}
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will return the URL unchanged.
public func deletingPathExtension() -> URL {
if path.isEmpty {
return self
}
if let result = _url.deletingPathExtension.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Appends a path component to the URL.
///
/// - parameter pathComponent: The path component to add.
/// - parameter isDirectory: Use `true` if the resulting path is a directory.
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) {
self = appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
/// Appends a path component to the URL.
///
/// - note: This function performs a file system operation to determine if the path component is a directory. If so, it will append a trailing `/`. If you know in advance that the path component is a directory or not, then use `func appendingPathComponent(_:isDirectory:)`.
/// - parameter pathComponent: The path component to add.
public mutating func appendPathComponent(_ pathComponent: String) {
self = appendingPathComponent(pathComponent)
}
/// Appends the given path extension to self.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
/// Certain special characters (for example, Unicode Right-To-Left marks) cannot be used as path extensions. If any of those are contained in `pathExtension`, the function will return the URL unchanged.
/// - parameter pathExtension: The extension to append.
public mutating func appendPathExtension(_ pathExtension: String) {
self = appendingPathExtension(pathExtension)
}
/// Returns a URL constructed by removing the last path component of self.
///
/// This function may either remove a path component or append `/..`.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deleteLastPathComponent() {
self = deletingLastPathComponent()
}
/// Returns a URL constructed by removing any path extension.
///
/// If the URL has an empty path (e.g., `http://www.example.com`), then this function will do nothing.
public mutating func deletePathExtension() {
self = deletingPathExtension()
}
/// Returns a `URL` with any instances of ".." or "." removed from its path.
public var standardized : URL {
// The NSURL API can only return nil in case of file reference URL, which we should not be
if let result = _url.standardized.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func standardize() {
self = self.standardized
}
/// Standardizes the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public var standardizedFileURL : URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.standardizingPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method returns `self`.
public func resolvingSymlinksInPath() -> URL {
// NSURL should not return nil here unless this is a file reference URL, which should be impossible
if let result = _url.resolvingSymlinksInPath.map({ URL(reference: $0 as NSURL) }) {
return result
} else {
return self
}
}
/// Resolves any symlinks in the path of a file URL.
///
/// If the `isFileURL` is false, this method does nothing.
public mutating func resolveSymlinksInPath() {
self = self.resolvingSymlinksInPath()
}
// MARK: - Reachability
/// Returns whether the URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
public func checkResourceIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkResourceIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
/// Returns whether the promised item URL's resource exists and is reachable.
///
/// This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. This method is currently applicable only to URLs for file system resources. For other URL types, `false` is returned.
@available(macOS 10.10, iOS 8.0, *)
public func checkPromisedItemIsReachable() throws -> Bool {
var error : NSError?
let result = _url.checkPromisedItemIsReachableAndReturnError(&error)
if let e = error {
throw e
} else {
return result
}
}
// MARK: - Resource Values
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : Any, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
/// Get resource values from URLs of 'promised' items.
///
/// A promised item is not guaranteed to have its contents in the file system until you use `FileCoordinator` to perform a coordinated read on its URL, which causes the contents to be downloaded or otherwise generated. Promised item URLs are returned by various APIs, including currently:
/// NSMetadataQueryUbiquitousDataScope
/// NSMetadataQueryUbiquitousDocumentsScope
/// A `FilePresenter` presenting the contents of the directory located by -URLForUbiquitousContainerIdentifier: or a subdirectory thereof
///
/// The following methods behave identically to their similarly named methods above (`func resourceValues(forKeys:)`, etc.), except that they allow you to get resource values and check for presence regardless of whether the promised item's contents currently exist at the URL. You must use these APIs instead of the normal URL resource value APIs if and only if any of the following are true:
/// You are using a URL that you know came directly from one of the above APIs
/// You are inside the accessor block of a coordinated read or write that used NSFileCoordinatorReadingImmediatelyAvailableMetadataOnly, NSFileCoordinatorWritingForDeleting, NSFileCoordinatorWritingForMoving, or NSFileCoordinatorWritingContentIndependentMetadataOnly
///
/// Most of the URL resource value keys will work with these APIs. However, there are some that are tied to the item's contents that will not work, such as `contentAccessDateKey` or `generationIdentifierKey`. If one of these keys is used, the method will return a `URLResourceValues` value, but the value for that property will be nil.
@available(macOS 10.10, iOS 8.0, *)
public func promisedItemResourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.promisedItemResourceValues(forKeys: Array(keys)))
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValue(_ value: AnyObject?, forKey key: URLResourceKey) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func setResourceValues(_ keyedValues: [URLResourceKey : AnyObject]) throws {
fatalError()
}
@available(*, unavailable, message: "Use struct URLResourceValues and URL.setResourceValues(_:) instead")
public func getResourceValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: URLResourceKey) throws {
fatalError()
}
// MARK: - Bookmarks and Alias Files
/// Returns bookmark data for the URL, created with specified options and resource values.
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
return result as Data
}
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
public static func resourceValues(forKeys keys: Set<URLResourceKey>, fromBookmarkData data: Data) -> URLResourceValues? {
return NSURL.resourceValues(forKeys: Array(keys), fromBookmarkData: data).map { URLResourceValues(keys: keys, values: $0) }
}
/// Creates an alias file on disk at a specified location with specified bookmark data. bookmarkData must have been created with the URLBookmarkCreationSuitableForBookmarkFile option. bookmarkFileURL must either refer to an existing file (which will be overwritten), or to location in an existing directory.
public static func writeBookmarkData(_ data : Data, to url: URL) throws {
// Options are unused
try NSURL.writeBookmarkData(data, to: url, options: 0)
}
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
let result = try NSURL.bookmarkData(withContentsOf: url)
return result as Data
}
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).
@available(macOS 10.7, iOS 8.0, *)
public func startAccessingSecurityScopedResource() -> Bool {
return _url.startAccessingSecurityScopedResource()
}
/// Revokes the access granted to the url by a prior successful call to startAccessingSecurityScopedResource.
@available(macOS 10.7, iOS 8.0, *)
public func stopAccessingSecurityScopedResource() {
_url.stopAccessingSecurityScopedResource()
}
// MARK: - Bridging Support
/// We must not store an NSURL without running it through this function. This makes sure that we do not hold a file reference URL, which changes the nullability of many NSURL functions.
private static func _converted(from url: NSURL) -> NSURL {
// Future readers: file reference URL here is not the same as playgrounds "file reference"
if url.isFileReferenceURL() {
// Convert to a file path URL, or use an invalid scheme
return (url.filePathURL ?? URL(string: "com-apple-unresolvable-file-reference-url:")!) as NSURL
} else {
return url
}
}
fileprivate init(reference: __shared NSURL) {
_url = URL._converted(from: reference).copy() as! NSURL
}
private var reference : NSURL {
return _url
}
public static func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
}
extension URL : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURL {
return _url
}
public static func _forceBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) {
if !_conditionallyBridgeFromObjectiveC(source, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSURL, result: inout URL?) -> Bool {
result = URL(reference: source)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURL?) -> URL {
var result: URL?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension URL : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
}
extension NSURL : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as URL)
}
}
extension URL : _CustomPlaygroundQuickLookable {
@available(*, deprecated, message: "URL.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .url(absoluteString)
}
}
extension URL : Codable {
private enum CodingKeys : Int, CodingKey {
case base
case relative
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let relative = try container.decode(String.self, forKey: .relative)
let base = try container.decodeIfPresent(URL.self, forKey: .base)
guard let url = URL(string: relative, relativeTo: base) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid URL string."))
}
self = url
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.relativeString, forKey: .relative)
if let base = self.baseURL {
try container.encode(base, forKey: .base)
}
}
}
//===----------------------------------------------------------------------===//
// File references, for playgrounds.
//===----------------------------------------------------------------------===//
extension URL : _ExpressibleByFileReferenceLiteral {
public init(fileReferenceLiteralResourceName name: String) {
self = Bundle.main.url(forResource: name, withExtension: nil)!
}
}
public typealias _FileReferenceLiteralType = URL
| apache-2.0 | da6854786acf64d9bbc9c487121f06fc | 52.35731 | 765 | 0.686654 | 4.967535 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/Classes/View/CSScrollView.swift | 1 | 1744 | //
// Created by Rene Dohan on 12/22/19.
//
import UIKit
import TPKeyboardAvoiding
open class CSScrollView: TPKeyboardAvoidingScrollView, CSHasLayoutProtocol {
@discardableResult
public class func construct() -> Self { construct(defaultSize: true) }
@discardableResult
public class func construct(_ function: ArgFunc<CSScrollView>) -> Self {
let _self = construct(defaultSize: true)
function(_self)
return _self
}
public let layoutFunctions: CSEvent<Void> = event()
public let eventLayoutSubviewsFirstTime: CSEvent<Void> = event()
@discardableResult
public func layout(function: @escaping Func) -> Self {
layoutFunctions.listen { function() }
function()
return self
}
@discardableResult
public func layout<View: UIView>(_ view: View, function: @escaping (View) -> Void) -> View {
layoutFunctions.listen { function(view) }
function(view)
return view
}
private var isDidLayoutSubviews = false
override open func layoutSubviews() {
super.layoutSubviews()
if !isDidLayoutSubviews {
isDidLayoutSubviews = true
onLayoutSubviewsFirstTime()
onCreateLayout()
onLayoutCreated()
eventLayoutSubviewsFirstTime.fire()
} else {
onUpdateLayout()
}
updateLayout()
onLayoutSubviews()
}
open func onLayoutSubviewsFirstTime() {}
open func onCreateLayout() {}
open func onLayoutCreated() {}
open func onUpdateLayout() {}
open func onLayoutSubviews() {}
@discardableResult
public func updateLayout() -> Self { animate { self.layoutFunctions.fire() }; return self }
}
| mit | 888c8396f0f14ea7a42c1860a4597c28 | 25.424242 | 96 | 0.642202 | 4.997135 | false | false | false | false |
zakkhoyt/ColorPicKit | ColorPicKit/Classes/HSBASpectrum.swift | 1 | 717 | //
// HSBASpectrum.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 10/26/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
@IBDesignable public class HSBASpectum: Spectrum {
fileprivate var hsbaSpectrumView = HSBSpectrumView()
override func configureSpectrum() {
hsbaSpectrumView.borderWidth = borderWidth
hsbaSpectrumView.borderColor = borderColor
addSubview(hsbaSpectrumView)
self.spectrumView = hsbaSpectrumView
}
override func colorAt(position: CGPoint) -> UIColor {
let rgb = hsbaSpectrumView.rgbaFor(point: position)
return UIColor(red: rgb.red, green: rgb.green, blue: rgb.blue, alpha: 1.0)
}
}
| mit | c1aa96308299c4959f818cb04b2abd15 | 25.518519 | 82 | 0.691341 | 3.87027 | false | false | false | false |
marcopompei/Gloss | Sources/Operators.swift | 1 | 18905 | //
// Operators.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: - Operator <~~ (Decode)
/**
Decode custom operator.
*/
infix operator <~~ { associativity left precedence 150 }
/**
Convenience operator for decoding JSON to generic value.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ <T>(key: String, json: JSON) -> T? {
return Decoder.decode(key)(json)
}
/**
Convenience operator for decoding JSON to Decodable object.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ <T: Decodable>(key: String, json: JSON) -> T? {
return Decoder.decodeDecodable(key)(json)
}
/**
Convenience operator for decoding JSON to array of Decodable objects.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ <T: Decodable>(key: String, json: JSON) -> [T]? {
return Decoder.decodeDecodableArray(key)(json)
}
/**
Convenience operator for decoding JSON to dictionary of String to Decodable.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ <T: Decodable>(key: String, json: JSON) -> [String : T]? {
return Decoder.decodeDecodableDictionary(key)(json)
}
/**
Convenience operator for decoding JSON to dictionary of String to Decodable array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ <T: Decodable>(key: String, json: JSON) -> [String : [T]]? {
return Decoder.decodeDecodableDictionary(key)(json)
}
/**
Convenience operator for decoding JSON to enum value.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ <T: RawRepresentable>(key: String, json: JSON) -> T? {
return Decoder.decodeEnum(key)(json)
}
/**
Convenience operator for decoding JSON to array of enum values.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ <T: RawRepresentable>(key: String, json: JSON) -> [T]? {
return Decoder.decodeEnumArray(key)(json)
}
/**
Convenience operator for decoding JSON to Int32.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> Int32? {
return Decoder.decodeInt32(key)(json)
}
/**
Convenience operator for decoding JSON to Int32 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> [Int32]? {
return Decoder.decodeInt32Array(key)(json)
}
/**
Convenience operator for decoding JSON to UInt32.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> UInt32? {
return Decoder.decodeUInt32(key)(json)
}
/**
Convenience operator for decoding JSON to UInt32 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> [UInt32]? {
return Decoder.decodeUInt32Array(key)(json)
}
/**
Convenience operator for decoding JSON to Int64.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> Int64? {
return Decoder.decodeInt64(key)(json)
}
/**
Convenience operator for decoding JSON to Int64 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> [Int64]? {
return Decoder.decodeInt64Array(key)(json)
}
/**
Convenience operator for decoding JSON to UInt64.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> UInt64? {
return Decoder.decodeUInt64(key)(json)
}
/**
Convenience operator for decoding JSON to UInt64 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> [UInt64]? {
return Decoder.decodeUInt64Array(key)(json)
}
/**
Convenience operator for decoding JSON to URL.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> NSURL? {
return Decoder.decodeURL(key)(json)
}
/**
Convenience operator for decoding JSON to array of URLs.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, nil otherwise.
*/
public func <~~ (key: String, json: JSON) -> [NSURL]? {
return Decoder.decodeURLArray(key)(json)
}
// MARK: - Operator ~~> (Encode)
/**
Encode custom operator.
*/
infix operator ~~> { associativity left precedence 150 }
/**
Convenience operator for encoding generic value to JSON
*/
/**
Convenience operator for encoding a generic value to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T>(key: String, property: T?) -> JSON? {
return Encoder.encode(key)(property)
}
/**
Convenience operator for encoding an array of generic values to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T>(key: String, property: [T]?) -> JSON? {
return Encoder.encodeArray(key)(property)
}
/**
Convenience operator for encoding an Encodable object to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T: Encodable>(key: String, property: T?) -> JSON? {
return Encoder.encodeEncodable(key)(property)
}
/**
Convenience operator for encoding an array of Encodable objects to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T: Encodable>(key: String, property: [T]?) -> JSON? {
return Encoder.encodeEncodableArray(key)(property)
}
/**
Convenience operator for encoding a dictionary of String to Encodable to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T: Encodable>(key: String, property: [String : T]?) -> JSON? {
return Encoder.encodeEncodableDictionary(key)(property)
}
/**
Convenience operator for encoding a dictionary of String to Encodable array to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T: Encodable>(key: String, property: [String : [T]]?) -> JSON? {
return Encoder.encodeEncodableDictionary(key)(property)
}
/**
Convenience operator for encoding an enum value to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T: RawRepresentable>(key: String, property: T?) -> JSON? {
return Encoder.encodeEnum(key)(property)
}
/**
Convenience operator for encoding an array of enum values to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> <T: RawRepresentable>(key: String, property: [T]?) -> JSON? {
return Encoder.encodeEnumArray(key)(property)
}
/**
Convenience operator for encoding an Int32 to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: Int32?) -> JSON? {
return Encoder.encodeInt32(key)(property)
}
/**
Convenience operator for encoding an Int32 array to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: [Int32]?) -> JSON? {
return Encoder.encodeInt32Array(key)(property)
}
/**
Convenience operator for encoding an UInt32 to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: UInt32?) -> JSON? {
return Encoder.encodeUInt32(key)(property)
}
/**
Convenience operator for encoding an UInt32 array to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: [UInt32]?) -> JSON? {
return Encoder.encodeUInt32Array(key)(property)
}
/**
Convenience operator for encoding an Int64 to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: Int64?) -> JSON? {
return Encoder.encodeInt64(key)(property)
}
/**
Convenience operator for encoding an Int64 array to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: [Int64]?) -> JSON? {
return Encoder.encodeInt64Array(key)(property)
}
/**
Convenience operator for encoding an UInt64 to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: UInt64?) -> JSON? {
return Encoder.encodeUInt64(key)(property)
}
/**
Convenience operator for encoding an UInt64 array to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: [UInt64]?) -> JSON? {
return Encoder.encodeUInt64Array(key)(property)
}
/**
Convenience operator for encoding a URL to JSON.
- parameter key: JSON key for value to encode.
- parameter property: Object to encode to JSON.
- returns: JSON when successful, nil otherwise.
*/
public func ~~> (key: String, property: NSURL?) -> JSON? {
return Encoder.encodeURL(key)(property)
}
infix operator <~~~ { associativity left precedence 150 }
/**
Convenience operator for decoding JSON to generic value.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ <T>(key: String, json: JSON) throws -> T {
if let value: T = Decoder.decode(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to Decodable object.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ <T: Decodable>(key: String, json: JSON) throws -> T {
if let value: T = Decoder.decodeDecodable(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to array of Decodable objects.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ <T: Decodable>(key: String, json: JSON) throws -> [T] {
if let value: [T] = Decoder.decodeDecodableArray(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to dictionary of String to Decodable.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ <T: Decodable>(key: String, json: JSON) throws -> [String : T] {
if let value: [String : T] = Decoder.decodeDecodableDictionary(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to dictionary of String to Decodable array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ <T: Decodable>(key: String, json: JSON) throws -> [String : [T]] {
if let value: [String : [T]] = Decoder.decodeDecodableDictionary(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to enum value.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ <T: RawRepresentable>(key: String, json: JSON) throws -> T {
if let value: T = Decoder.decodeEnum(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to array of enum values.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ <T: RawRepresentable>(key: String, json: JSON) throws -> [T] {
if let value: [T] = Decoder.decodeEnumArray(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to Int32.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> Int32 {
if let value = Decoder.decodeInt32(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to Int32 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> [Int32] {
if let value = Decoder.decodeInt32Array(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to UInt32.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> UInt32 {
if let value = Decoder.decodeUInt32(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to UInt32 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> [UInt32] {
if let value = Decoder.decodeUInt32Array(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to Int64.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> Int64 {
if let value = Decoder.decodeInt64(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to Int64 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> [Int64] {
if let value = Decoder.decodeInt64Array(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to UInt64.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> UInt64 {
if let value = Decoder.decodeUInt64(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to UInt64 array.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> [UInt64] {
if let value = Decoder.decodeUInt64Array(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
/**
Convenience operator for decoding JSON to URL.
- parameter key: JSON key for value to decode.
- parameter json: JSON.
- returns: Decoded value when successful, throws otherwise.
*/
public func <~~~ (key: String, json: JSON) throws -> NSURL {
if let value = Decoder.decodeURL(key)(json) { return value }
throw GlossError.EmptyForceDecode
}
enum GlossError: ErrorType {
case EmptyForceDecode
}
| mit | 4ed60e9491228aaeb7fbd3b9c5716135 | 27.385886 | 96 | 0.702195 | 3.923013 | false | false | false | false |
alblue/swift | test/SILGen/objc_blocks_bridging.swift | 1 | 19942 |
// RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s --check-prefix=GUARANTEED
// REQUIRES: objc_interop
import Foundation
@objc class Foo {
// CHECK-LABEL: sil hidden [thunk] @$s20objc_blocks_bridging3FooC3foo_1xS3iXE_SitFTo :
// CHECK: bb0([[ARG1:%.*]] : @unowned $@convention(block) @noescape (Int) -> Int, {{.*}}, [[SELF:%.*]] : @unowned $Foo):
// CHECK: [[ARG1_COPY:%.*]] = copy_block [[ARG1]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK:%.*]] = function_ref @$sS2iIyByd_S2iIegyd_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG1_COPY]])
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[BRIDGED]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @$s20objc_blocks_bridging3FooC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@noescape @callee_guaranteed (Int) -> Int, Int, @guaranteed Foo) -> Int
// CHECK: apply [[NATIVE]]([[CONVERT]], {{.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: } // end sil function '$s20objc_blocks_bridging3FooC3foo_1xS3iXE_SitFTo'
@objc dynamic func foo(_ f: (Int) -> Int, x: Int) -> Int {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @$s20objc_blocks_bridging3FooC3bar_1xS3SXE_SStFTo : $@convention(objc_method) (@convention(block) @noescape (NSString) -> @autoreleased NSString, NSString, Foo) -> @autoreleased NSString {
// CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (NSString) -> @autoreleased NSString, [[NSSTRING:%.*]] : @unowned $NSString, [[SELF:%.*]] : @unowned $Foo):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK:%.*]] = function_ref @$sSo8NSStringCABIyBya_S2SIeggo_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[BLOCK_COPY]])
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[BRIDGED]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @$s20objc_blocks_bridging3FooC3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@noescape @callee_guaranteed (@guaranteed String) -> @owned String, @guaranteed String, @guaranteed Foo) -> @owned String
// CHECK: apply [[NATIVE]]([[CONVERT]], {{%.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: } // end sil function '$s20objc_blocks_bridging3FooC3bar_1xS3SXE_SStFTo'
@objc dynamic func bar(_ f: (String) -> String, x: String) -> String {
return f(x)
}
// GUARANTEED-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$sSo8NSStringCABIyBya_S2SIeggo_TR : $@convention(thin) (@guaranteed String, @guaranteed @convention(block) @noescape (NSString) -> @autoreleased NSString) -> @owned String {
// GUARANTEED: bb0(%0 : @guaranteed $String, [[BLOCK:%.*]] : @guaranteed $@convention(block) @noescape (NSString) -> @autoreleased NSString):
// GUARANTEED: [[BRIDGE:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// GUARANTEED: [[NSSTR:%.*]] = apply [[BRIDGE]](%0)
// GUARANTEED: apply [[BLOCK]]([[NSSTR]]) : $@convention(block) @noescape (NSString) -> @autoreleased NSString
// GUARANTEED: } // end sil function '$sSo8NSStringCABIyBya_S2SIeggo_TR'
// CHECK-LABEL: sil hidden [thunk] @$s20objc_blocks_bridging3FooC3bas_1xSSSgA2FXE_AFtFTo : $@convention(objc_method) (@convention(block) @noescape (Optional<NSString>) -> @autoreleased Optional<NSString>, Optional<NSString>, Foo) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (Optional<NSString>) -> @autoreleased Optional<NSString>, [[OPT_STRING:%.*]] : @unowned $Optional<NSString>, [[SELF:%.*]] : @unowned $Foo):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK:%.*]] = function_ref @$sSo8NSStringCSgACIyBya_SSSgADIeggo_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[BLOCK_COPY]])
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[BRIDGED]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @$s20objc_blocks_bridging3FooC3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@noescape @callee_guaranteed (@guaranteed Optional<String>) -> @owned Optional<String>, @guaranteed Optional<String>, @guaranteed Foo) -> @owned Optional<String>
// CHECK: apply [[NATIVE]]([[CONVERT]], {{%.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
@objc dynamic func bas(_ f: (String?) -> String?, x: String?) -> String? {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @$s20objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}FTo
// CHECK: bb0([[F:%.*]] : @trivial $@convention(c) @noescape (Int) -> Int, [[X:%.*]] : @trivial $Int, [[SELF:%.*]] : @unowned $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @$s20objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[NATIVE]]([[F]], [[X]], [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
@objc dynamic func cFunctionPointer(_ fp: @convention(c) (Int) -> Int, x: Int) -> Int {
_ = fp(x)
}
// Blocks and C function pointers must not be reabstracted when placed in optionals.
// CHECK-LABEL: sil hidden [thunk] @$s20objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}FTo
// CHECK: bb0([[ARG0:%.*]] : @unowned $Optional<@convention(block) (NSString) -> @autoreleased NSString>,
// CHECK: [[COPY:%.*]] = copy_block [[ARG0]]
// CHECK: switch_enum [[COPY]] : $Optional<@convention(block) (NSString) -> @autoreleased NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[BLOCK:%.*]] : @owned $@convention(block) (NSString) -> @autoreleased NSString):
// TODO: redundant reabstractions here
// CHECK: [[BLOCK_THUNK:%.*]] = function_ref @$sSo8NSStringCABIeyBya_S2SIeggo_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[BLOCK_THUNK]]([[BLOCK]])
// CHECK: enum $Optional<@callee_guaranteed (@guaranteed String) -> @owned String>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = function_ref @$s20objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Optional<@callee_guaranteed (@guaranteed String) -> @owned String>, @guaranteed String, @guaranteed Foo) -> @owned Optional<String>
// CHECK: apply [[NATIVE]]
@objc dynamic func optFunc(_ f: ((String) -> String)?, x: String) -> String? {
return f?(x)
}
// CHECK-LABEL: sil hidden @$s20objc_blocks_bridging3FooC19optCFunctionPointer{{[_0-9a-zA-Z]*}}F
// CHECK: switch_enum %0
//
// CHECK: bb1([[FP_BUF:%.*]] : @trivial $@convention(c) (NSString) -> @autoreleased NSString):
@objc dynamic func optCFunctionPointer(_ fp: (@convention(c) (String) -> String)?, x: String) -> String? {
return fp?(x)
}
}
// => SEMANTIC SIL TODO: This test needs to be filled out more for ownership
//
// CHECK-LABEL: sil hidden @$s20objc_blocks_bridging10callBlocks{{[_0-9a-zA-Z]*}}F
func callBlocks(_ x: Foo,
f: @escaping (Int) -> Int,
g: @escaping (String) -> String,
h: @escaping (String?) -> String?
) -> (Int, String, String?, String?) {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @guaranteed $@callee_guaranteed (Int) -> Int, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed String) -> @owned String, [[ARG3:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed Optional<String>) -> @owned Optional<String>):
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE_COPY]]
// CHECK: [[NOESCAPE_SENTINEL:%.*]] = mark_dependence {{.*}}on [[CONVERT]]
// CHECK: [[COPY:%.*]] = copy_value [[NOESCAPE_SENTINEL]]
// CHECK: [[F_BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[F_BLOCK_CAPTURE:%.*]] = project_block_storage [[F_BLOCK_STORAGE]]
// CHECK: store [[COPY]] to [init] [[F_BLOCK_CAPTURE]]
// CHECK: [[F_BLOCK_INVOKE:%.*]] = function_ref @$sS2iIegyd_S2iIyByd_TR
// CHECK: [[F_STACK_BLOCK:%.*]] = init_block_storage_header [[F_BLOCK_STORAGE]] : {{.*}}, invoke [[F_BLOCK_INVOKE]]
// CHECK: [[F_BLOCK:%.*]] = copy_block_without_escaping [[F_STACK_BLOCK]]
// CHECK: [[FOO:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.foo!1.foreign
// CHECK: apply [[FOO]]([[F_BLOCK]]
// CHECK: [[G_BLOCK_INVOKE:%.*]] = function_ref @$sS2SIeggo_So8NSStringCABIyBya_TR
// CHECK: [[G_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[G_BLOCK_INVOKE]]
// CHECK: [[G_BLOCK:%.*]] = copy_block_without_escaping [[G_STACK_BLOCK]]
// CHECK: [[BAR:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.bar!1.foreign
// CHECK: apply [[BAR]]([[G_BLOCK]]
// CHECK: [[H_BLOCK_INVOKE:%.*]] = function_ref @$sSSSgAAIeggo_So8NSStringCSgADIyBya_TR
// CHECK: [[H_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[H_BLOCK_INVOKE]]
// CHECK: [[H_BLOCK:%.*]] = copy_block_without_escaping [[H_STACK_BLOCK]]
// CHECK: [[BAS:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.bas!1.foreign
// CHECK: apply [[BAS]]([[H_BLOCK]]
// CHECK: [[G_BLOCK:%.*]] = copy_block {{%.*}} : $@convention(block) (NSString) -> @autoreleased NSString
// CHECK: enum $Optional<@convention(block) (NSString) -> @autoreleased NSString>, #Optional.some!enumelt.1, [[G_BLOCK]]
return (x.foo(f, x: 0), x.bar(g, x: "one"), x.bas(h, x: "two"), x.optFunc(g, x: "three"))
}
class Test: NSObject {
@objc func blockTakesBlock() -> ((Int) -> Int) -> Int {}
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$sS2iIgyd_SiIegyd_S2iIyByd_SiIeyByd_TR
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[ORIG_BLOCK:%.*]] :
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[BLOCK_COPY]])
// CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE]]
// CHECK: [[RESULT:%.*]] = apply {{%.*}}([[CONVERT]])
// CHECK: return [[RESULT]]
func clearDraggingItemImageComponentsProvider(_ x: NSDraggingItem) {
x.imageComponentsProvider = { [] }
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$sSayypGIego_So7NSArrayCSgIeyBa_TR
// CHECK: [[CONVERT:%.*]] = function_ref @$sSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF
// CHECK: [[CONVERTED:%.*]] = apply [[CONVERT]]
// CHECK: [[OPTIONAL:%.*]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[CONVERTED]]
// CHECK: return [[OPTIONAL]]
// CHECK-LABEL: sil hidden @{{.*}}bridgeNonnullBlockResult{{.*}}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$sSSIego_So8NSStringCSgIeyBa_TR
// CHECK: [[CONVERT:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BRIDGED:%.*]] = apply [[CONVERT]]
// CHECK: [[OPTIONAL_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: return [[OPTIONAL_BRIDGED]]
func bridgeNonnullBlockResult() {
nonnullStringBlockResult { return "test" }
}
// CHECK-LABEL: sil hidden @$s20objc_blocks_bridging19bridgeNoescapeBlock2fn5optFnyyyXE_yycSgtF
func bridgeNoescapeBlock(fn: () -> (), optFn: (() -> ())?) {
// CHECK: [[CLOSURE_FN:%.*]] = function_ref @$s20objc_blocks_bridging19bridgeNoescapeBlock2fn5optFnyyyXE_yycSgtFyyXEfU_
// CHECK: [[CONV_FN:%.*]] = convert_function [[CLOSURE_FN]]
// CHECK: [[THICK_FN:%.*]] = thin_to_thick_function [[CONV_FN]]
// without actually escaping sentinel
// CHECK: [[WAE_THUNK:%.*]] = function_ref @$sIg_Ieg_TR
// CHECK: [[WAE_PA:%.*]] = partial_apply [callee_guaranteed] [[WAE_THUNK]]([[THICK_FN]])
// CHECK: [[WAE_MD:%.*]] = mark_dependence [[WAE_PA]] : $@callee_guaranteed () -> () on [[THICK_FN]]
// CHECK: [[WAE:%.*]] = copy_value [[WAE_MD]] : $@callee_guaranteed () -> ()
// CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> ()
// CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]]
// CHECK: store [[WAE]] to [init] [[BLOCK_ADDR]]
// CHECK: [[THUNK:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> ()
// CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}}
// FIXME: We're passing the block as a no-escape -- so we don't have to copy it
// CHECK: [[BLOCK:%.*]] = copy_block_without_escaping [[BLOCK_STACK]]
// CHECK: [[SOME_BLOCK:%.*]] = enum $Optional<@convention(block) @noescape () -> ()>, #Optional.some!enumelt.1, [[BLOCK]]
// CHECK: dealloc_stack [[BLOCK_ALLOC]]
// CHECK: [[FN:%.*]] = function_ref @noescapeBlock : $@convention(c) (Optional<@convention(block) @noescape () -> ()>) -> ()
// CHECK: apply [[FN]]([[SOME_BLOCK]])
noescapeBlock { }
// CHECK: destroy_value [[SOME_BLOCK]]
// CHECK: [[WAE_THUNK:%.*]] = function_ref @$sIg_Ieg_TR
// CHECK: [[WAE_PA:%.*]] = partial_apply [callee_guaranteed] [[WAE_THUNK]](%0)
// CHECK: [[WAE_MD:%.*]] = mark_dependence [[WAE_PA]] : $@callee_guaranteed () -> () on %0
// CHECK: [[WAE:%.*]] = copy_value [[WAE_MD]]
// CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> ()
// CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]]
// CHECK: store [[WAE]] to [init] [[BLOCK_ADDR]]
// CHECK: [[THUNK:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> ()
// CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}}
// FIXME: We're passing the block as a no-escape -- so we don't have to copy it
// CHECK: [[BLOCK:%.*]] = copy_block_without_escaping [[BLOCK_STACK]]
// CHECK: [[SOME_BLOCK:%.*]] = enum $Optional<@convention(block) @noescape () -> ()>, #Optional.some!enumelt.1, [[BLOCK]]
// CHECK: dealloc_stack [[BLOCK_ALLOC]]
// CHECK: [[FN:%.*]] = function_ref @noescapeBlock : $@convention(c) (Optional<@convention(block) @noescape () -> ()>) -> ()
// CHECK: apply [[FN]]([[SOME_BLOCK]])
noescapeBlock(fn)
// CHECK: destroy_value [[SOME_BLOCK]]
// CHECK: [[NIL_BLOCK:%.*]] = enum $Optional<@convention(block) @noescape () -> ()>, #Optional.none!enumelt
// CHECK: [[FN:%.*]] = function_ref @noescapeBlock : $@convention(c) (Optional<@convention(block) @noescape () -> ()>) -> ()
// CHECK: apply [[FN]]([[NIL_BLOCK]])
noescapeBlock(nil)
// CHECK: [[CLOSURE_FN:%.*]] = function_ref @$s20objc_blocks_bridging19bridgeNoescapeBlock2fn5optFnyyyXE_yycSgtF
// CHECK: [[CONV_FN:%.*]] = convert_function [[CLOSURE_FN]]
// CHECK: [[THICK_FN:%.*]] = thin_to_thick_function [[CONV_FN]]
// CHECK: [[WAE_THUNK:%.*]] = function_ref @$sIg_Ieg_TR
// CHECK: [[WAE_PA:%.*]] = partial_apply [callee_guaranteed] [[WAE_THUNK]]([[THICK_FN]])
// CHECK: [[WAE_MD:%.*]] = mark_dependence [[WAE_PA]] : $@callee_guaranteed () -> () on [[THICK_FN]]
// CHECK: [[WAE:%.*]] = copy_value [[WAE_MD]]
// CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> ()
// CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]]
// CHECK: store [[WAE]] to [init] [[BLOCK_ADDR]]
// CHECK: [[THUNK:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> ()
// CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}}
// FIXME: We're passing the block as a no-escape -- so we don't have to copy it
// CHECK: [[BLOCK:%.*]] = copy_block_without_escaping [[BLOCK_STACK]]
// CHECK: [[FN:%.*]] = function_ref @noescapeNonnullBlock : $@convention(c) (@convention(block) @noescape () -> ()) -> ()
// CHECK: apply [[FN]]([[BLOCK]])
noescapeNonnullBlock { }
// CHECK: destroy_value [[BLOCK]]
// CHECK: [[WAE_THUNK:%.*]] = function_ref @$sIg_Ieg_TR
// CHECK: [[WAE_PA:%.*]] = partial_apply [callee_guaranteed] [[WAE_THUNK]](%0)
// CHECK: [[WAE_MD:%.*]] = mark_dependence [[WAE_PA]] : $@callee_guaranteed () -> () on %0
// CHECK: [[WAE:%.*]] = copy_value [[WAE_MD]]
// CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> ()
// CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]]
// CHECK: store [[WAE]] to [init] [[BLOCK_ADDR]]
// CHECK: [[THUNK:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> ()
// CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}}
// FIXME: We're passing the block as a no-escape -- so we don't have to copy it
// CHECK: [[BLOCK:%.*]] = copy_block_without_escaping [[BLOCK_STACK]]
// CHECK: [[FN:%.*]] = function_ref @noescapeNonnullBlock : $@convention(c) (@convention(block) @noescape () -> ()) -> ()
// CHECK: apply [[FN]]([[BLOCK]])
noescapeNonnullBlock(fn)
noescapeBlock(optFn)
noescapeBlockAlias { }
noescapeBlockAlias(fn)
noescapeBlockAlias(nil)
noescapeNonnullBlockAlias { }
noescapeNonnullBlockAlias(fn)
}
public func bridgeNoescapeBlock( optFn: ((String?) -> ())?, optFn2: ((String?) -> ())?) {
noescapeBlock3(optFn, optFn2, "Foobar")
}
@_silgen_name("_returnOptionalEscape")
public func returnOptionalEscape() -> (() ->())?
public func bridgeNoescapeBlock() {
noescapeBlock(returnOptionalEscape())
}
class ObjCClass : NSObject {}
extension ObjCClass {
@objc func someDynamicMethod(closure: (() -> ()) -> ()) {}
}
struct GenericStruct<T> {
let closure: (() -> ()) -> ()
func doStuff(o: ObjCClass) {
o.someDynamicMethod(closure: closure)
}
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$sIg_Iegy_IyB_IyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed (@noescape @callee_guaranteed () -> ()) -> (), @convention(block) @noescape () -> ()) -> () {
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$sIyB_Ieg_TR : $@convention(thin) (@guaranteed @convention(block) @noescape () -> ()) -> ()
// rdar://35402696
func takeOptStringFunction(fn: (String) -> String?) {}
func testGlobalBlock() {
takeOptStringFunction(fn: GlobalBlock)
}
// CHECK-LABEL: sil hidden @$s20objc_blocks_bridging15testGlobalBlockyyF
// CHECK: global_addr @GlobalBlock : $*@convention(block) (NSString) -> @autoreleased Optional<NSString>
// CHECK: function_ref @$sSo8NSStringCABSgIeyBya_S2SIeggo_TR : $@convention(thin) (@guaranteed String, @guaranteed @convention(block) (NSString) -> @autoreleased Optional<NSString>) -> @owned String
| apache-2.0 | 4be9813b5de60de89c62df7c34b36006 | 63.537217 | 302 | 0.615585 | 3.470588 | false | false | false | false |
omise/omise-ios | OmiseSDKTests/Compatability Suite/OmiseTokenRequestTest.swift | 1 | 3310 | import XCTest
import OmiseSDK
@available(*, deprecated)
class OmiseTokenRequestTest: XCTestCase {
private let publicKey = "pkey_test_58wfnlwoxz1tbkdd993"
private let timeout: TimeInterval = 15.0
var testClient: OmiseSDKClient {
return OmiseSDKClient(publicKey: publicKey)
}
var testRequest: OmiseTokenRequest {
return OmiseTokenRequest(
name: "JOHN DOE",
number: "4242424242424242",
expirationMonth: 11,
expirationYear: 2022,
securityCode: "123"
)
}
var invalidRequest: OmiseTokenRequest {
return OmiseTokenRequest(
name: "JOHN DOE",
number: "42424242424242421111", // invalid number
expirationMonth: 11,
expirationYear: 2022,
securityCode: "123",
city: nil,
postalCode: nil
)
}
func testRequestWithDelegate() {
let expectation = self.expectation(description: "async delegate calls")
let delegate = TokenRequestDelegateDummy(expectation: expectation)
testClient.send(testRequest, delegate: delegate)
waitForExpectations(timeout: timeout) { (error) in
if let error = error {
return XCTFail("expectation error: \(error)")
}
XCTAssertNotNil(delegate.token)
XCTAssertNil(delegate.error)
XCTAssertEqual("4242", delegate.token?.card?.lastDigits)
XCTAssertEqual(11, delegate.token?.card?.expirationMonth)
XCTAssertEqual(2022, delegate.token?.card?.expirationYear)
}
}
func testRequestWithCallback() {
let expectation = self.expectation(description: "callback")
testClient.send(testRequest) { (result) in
defer { expectation.fulfill() }
switch result {
case .succeed(token: let token):
XCTAssertEqual("4242", token.card?.lastDigits)
XCTAssertEqual(11, token.card?.expirationMonth)
XCTAssertEqual(2022, token.card?.expirationYear)
case .fail(let error):
XCTFail("Expected succeed request but failed with \(error)")
}
}
waitForExpectations(timeout: timeout, handler: nil)
}
func testBadRequestWithDelegate() {
let expectation = self.expectation(description: "async delegate calls")
let delegate = TokenRequestDelegateDummy(expectation: expectation)
testClient.send(invalidRequest, delegate: delegate)
waitForExpectations(timeout: timeout) { (error) in
if let error = error {
return XCTFail("expectation error: \(error)")
}
XCTAssertNil(delegate.token)
XCTAssertNotNil(delegate.error)
}
}
func testBadRequestWithCallback() {
let expectation = self.expectation(description: "callback")
testClient.send(invalidRequest) { (result) in
defer { expectation.fulfill() }
if case .succeed = result {
XCTFail("Expected failed request")
}
}
waitForExpectations(timeout: timeout, handler: nil)
}
}
| mit | c42bfb7376da9753e8226a9364d6d9b6 | 33.123711 | 79 | 0.590937 | 5.139752 | false | true | false | false |
aichamorro/fitness-tracker | Clients/Apple/FitnessTracker/FitnessTracker/Data/FitnessInfoInsight.swift | 1 | 2952 | //
// FitnessInfoInsight.swift
// FitnessTracker
//
// Created by Alberto Chamorro - Personal on 01/01/2017.
// Copyright © 2017 OnsetBits. All rights reserved.
//
import Foundation
protocol IInsightInfo {
var height: Int { get }
var weight: Double { get }
var musclePercentage: Double { get }
var bodyFatPercentage: Double { get }
var waterPercentage: Double { get }
var muscleWeight: Double { get }
var bodyFatWeight: Double { get }
var waterWeight: Double { get }
}
struct InsightInfo {
let before: IFitnessInfo
let after: IFitnessInfo
}
extension InsightInfo: IInsightInfo {
var height: Int {
return Int(after.height - before.height)
}
var weight: Double {
return after.weight - before.weight
}
var musclePercentage: Double {
return after.musclePercentage - before.musclePercentage
}
var bodyFatPercentage: Double {
return after.bodyFatPercentage - before.bodyFatPercentage
}
var waterPercentage: Double {
return after.waterPercentage - before.waterPercentage
}
var muscleWeight: Double {
return after.muscleWeight - before.muscleWeight
}
var bodyFatWeight: Double {
return after.bodyFatWeight - before.bodyFatWeight
}
var waterWeight: Double {
return after.waterWeight - before.waterWeight
}
}
struct FitnessInfoInsight {
let reference: IFitnessInfo?
let previousRecord: IFitnessInfo?
let firstDayOfWeek: IFitnessInfo?
let firstDayOfMonth: IFitnessInfo?
let firstDayOfYear: IFitnessInfo?
private var canComputeDayInsight: Bool {
return previousRecord != nil && reference != nil
}
private var canComputeWeekInisght: Bool {
return firstDayOfWeek != nil && reference != nil
}
private var canComputeMonthlyInsight: Bool {
return firstDayOfMonth != nil && reference != nil
}
private var canComputeYearInsight: Bool {
return firstDayOfYear != nil && reference != nil
}
var dayInsight: IInsightInfo? {
guard canComputeDayInsight else { return nil }
return InsightInfo(before: previousRecord!, after: reference!)
}
var weekInsight: IInsightInfo? {
guard canComputeWeekInisght else { return nil }
return InsightInfo(before: firstDayOfWeek!, after: reference!)
}
var monthInsight: IInsightInfo? {
guard canComputeMonthlyInsight else { return nil }
return InsightInfo(before: firstDayOfMonth!, after: reference!)
}
var yearInsight: IInsightInfo? {
guard canComputeYearInsight else { return nil }
return InsightInfo(before: firstDayOfYear!, after: reference!)
}
}
extension FitnessInfoInsight {
static var empty: FitnessInfoInsight {
return FitnessInfoInsight(reference: nil, previousRecord: nil, firstDayOfWeek: nil, firstDayOfMonth: nil, firstDayOfYear: nil)
}
}
| gpl-3.0 | 1706e3b95f8509ead16cc1b607c7c40b | 25.115044 | 134 | 0.680447 | 4.457704 | false | false | false | false |
drawRect/Instagram_Stories | InstagramStories/Modules/Home/IGAddStoryCell.swift | 1 | 3379 | //
// IGAddStoryCell.swift
// InstagramStories
//
// Created by Ranjith Kumar on 9/6/17.
// Copyright © 2017 DrawRect. All rights reserved.
//
import UIKit
final class IGAddStoryCell: UICollectionViewCell {
//MARK: - Overriden functions
override init(frame: CGRect) {
super.init(frame: frame)
loadUIElements()
installLayoutConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
//MARK: - iVars
private let addStoryLabel: UILabel = {
let label = UILabel()
label.textColor = .black
label.alpha = 0.5
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 12)
return label
}()
public var userDetails: (String,String)? {
didSet {
if let details = userDetails {
addStoryLabel.text = details.0
profileImageView.imageView.setImage(url: details.1)
}
}
}
private let profileImageView: IGRoundedView = {
let roundedView = IGRoundedView()
roundedView.translatesAutoresizingMaskIntoConstraints = false
roundedView.enableBorder(enabled: false)
return roundedView
}()
lazy var addImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "ic_Add")
iv.translatesAutoresizingMaskIntoConstraints = false
iv.layer.cornerRadius = 20/2
iv.layer.borderWidth = 2.0
iv.layer.borderColor = UIColor.white.cgColor
iv.clipsToBounds = true
return iv
}()
//MARK: - Private functions
private func loadUIElements() {
addSubview(addStoryLabel)
addSubview(profileImageView)
addSubview(addImageView)
}
private func installLayoutConstraints() {
NSLayoutConstraint.activate([
profileImageView.widthAnchor.constraint(equalToConstant: 68),
profileImageView.heightAnchor.constraint(equalToConstant: 68),
profileImageView.igTopAnchor.constraint(equalTo: self.igTopAnchor, constant: 8),
profileImageView.igCenterXAnchor.constraint(equalTo: self.igCenterXAnchor),
addStoryLabel.igTopAnchor.constraint(equalTo: self.profileImageView.igBottomAnchor, constant: 2)])
NSLayoutConstraint.activate([
addStoryLabel.igLeftAnchor.constraint(equalTo: self.igLeftAnchor),
self.igRightAnchor.constraint(equalTo: addStoryLabel.igRightAnchor),
addStoryLabel.igTopAnchor.constraint(equalTo: self.profileImageView.igBottomAnchor, constant: 2),
addStoryLabel.igCenterXAnchor.constraint(equalTo: self.igCenterXAnchor),
self.igBottomAnchor.constraint(equalTo: addStoryLabel.igBottomAnchor, constant: 8)])
NSLayoutConstraint.activate([
self.igRightAnchor.constraint(equalTo: addImageView.igRightAnchor, constant: 17),
addImageView.widthAnchor.constraint(equalToConstant: 20),
addImageView.heightAnchor.constraint(equalToConstant: 20),
self.igBottomAnchor.constraint(equalTo: addImageView.igBottomAnchor, constant: 25)])
layoutIfNeeded()
}
}
| mit | 80c30f444eb1f6a1cbbbccb90310eba6 | 36.120879 | 110 | 0.661042 | 4.960352 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Swift/Extensions/Locale+Extensions.swift | 1 | 2568 | //
// Xcore
// Copyright © 2014 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
extension Locale {
/// Returns `en_US` locale.
///
/// **For DateFormatter:**
///
/// In most cases the best locale to choose is `"en_US_POSIX"`, a locale that's
/// specifically designed to yield US English results regardless of both user
/// and system preferences. `"en_US_POSIX"` is also invariant in time (if the
/// US, at some point in the future, changes the way it formats dates, `"en_US"`
/// will change to reflect the new behaviour, but `"en_US_POSIX"` will not), and
/// between machines (`"en_US_POSIX"` works the same on iOS as it does on
/// mac OS, and as it it does on other platforms).
///
/// - SeeAlso: https://developer.apple.com/library/archive/qa/qa1480/_index.html
public static let us = Locale(identifier: "en_US")
/// Returns `en_US_POSIX` locale.
///
/// **For DateFormatter:**
///
/// In most cases the best locale to choose is `"en_US_POSIX"`, a locale that's
/// specifically designed to yield US English results regardless of both user
/// and system preferences. `"en_US_POSIX"` is also invariant in time (if the
/// US, at some point in the future, changes the way it formats dates, `"en_US"`
/// will change to reflect the new behaviour, but `"en_US_POSIX"` will not), and
/// between machines (`"en_US_POSIX"` works the same on iOS as it does on
/// mac OS, and as it it does on other platforms).
///
/// - SeeAlso: https://developer.apple.com/library/archive/qa/qa1480/_index.html
public static let usPosix = Locale(identifier: "en_US_POSIX")
/// Returns `en_GB` (English, United Kingdom) locale.
public static let uk = Locale(identifier: "en_GB")
}
extension Locale {
/// Returns `fr` (French) locale.
public static let fr = Locale(identifier: "fr")
/// Returns `es` (Spanish) locale.
public static let es = Locale(identifier: "es")
/// Returns `de` (German) locale.
public static let de = Locale(identifier: "de")
/// Returns `de_DE` (German, Germany) locale.
public static let deDE = Locale(identifier: "de_DE")
/// Returns `tr` (Turkish) locale.
public static let tr = Locale(identifier: "tr")
}
extension Locale {
public static func printAvailableIdentifiers() {
print("Identifier,Description")
availableIdentifiers.forEach {
print("\"\($0)\",\"\(current.localizedString(forIdentifier: $0) ?? "")\"")
}
}
}
| mit | 48d82ed14c59a5f1c62c1f7ef009ec67 | 36.75 | 86 | 0.63732 | 3.949231 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/Avatar.swift | 1 | 6395 | //
// Avatar.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 27.1.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
import SCrypto
// Avatars are project-specific user accounts
final class Avatar: Storable
{
// ATTRIBUTES -------------
static let PROPERTY_PROJECT = "project"
static let type = "avatar"
let projectId: String
let created: TimeInterval
let uid: String
let accountId: String
var name: String
var isAdmin: Bool
var isDisabled: Bool
// COMPUTED PROPERTIES -----
static var idIndexMap: IdIndexMap
{
return Project.idIndexMap.makeChildPath(parentPathName: PROPERTY_PROJECT, childPath: ["avatar_separator", "avatar_uid"])
}
var idProperties: [Any] { return [projectId, "avatar", uid] }
var properties: [String : PropertyValue]
{
return ["name": name.value, "account": accountId.value, "created": created.value, "admin": isAdmin.value, "disabled": isDisabled.value]
}
// INIT ---------------------
init(name: String, projectId: String, accountId: String, isAdmin: Bool = false, isDisabled: Bool = false, uid: String = UUID().uuidString.lowercased(), created: TimeInterval = Date().timeIntervalSince1970)
{
self.isAdmin = isAdmin
self.isDisabled = isDisabled
self.projectId = projectId
self.name = name
self.created = created
self.uid = uid
self.accountId = accountId
}
static func create(from properties: PropertySet, withId id: Id) throws -> Avatar
{
return Avatar(name: properties["name"].string(), projectId: id[PROPERTY_PROJECT].string(), accountId: properties["account"].string(), isAdmin: properties["admin"].bool(), isDisabled: properties["disabled"].bool(), uid: id["avatar_uid"].string(), created: properties["created"].time())
}
// IMPLEMENTED METHODS -----
func update(with properties: PropertySet)
{
if let name = properties["name"].string
{
self.name = name
}
if let isAdmin = properties["admin"].bool
{
self.isAdmin = isAdmin
}
if let isDisabled = properties["disabled"].bool
{
self.isDisabled = isDisabled
}
}
// OTHER METHODS ---------
// The private infor for this avatar instance
func info() throws -> AvatarInfo?
{
return try AvatarInfo.get(avatarId: idString)
}
static func project(fromId avatarId: String) -> String
{
return property(withName: PROPERTY_PROJECT, fromId: avatarId).string()
}
// Creates a new avatar id based on the provided properties
/*
static func createId(projectId: String, avatarName: String) -> String
{
return parseId(from: [projectId, "avatar", avatarName.toKey])
}*/
// Retrieves avatar data from the database
/*
static func get(projectId: String, avatarName: String) throws -> Avatar?
{
return try get(createId(projectId: projectId, avatarName: avatarName))
}*/
/*
fileprivate static func nameKey(ofId avatarId: String) -> String
{
return property(withName: "avatar_name_key", fromId: avatarId).string()
}*/
}
// This class contains avatar info that is only visible in the project scope
final class AvatarInfo: Storable
{
// ATTRIBUTES -------------
static let PROPERTY_AVATAR = "avatar"
static let type = "avatar_info"
let avatarId: String
var isShared: Bool
// Phase id -> Carousel id
// var carouselIds: [String : String]
private var passwordHash: String?
private var _image: UIImage?
var image: UIImage?
{
// Reads the image from CB if necessary
if let image = _image
{
return image
}
else
{
if let image = attachment(named: "image")?.toImage
{
_image = image
return image
}
else
{
return nil
}
}
}
// COMPUTED PROPERTIES ----
static var idIndexMap: IdIndexMap
{
return Avatar.idIndexMap.makeChildPath(parentPathName: PROPERTY_AVATAR, childPath: ["info_separator"])
}
var idProperties: [Any] { return [avatarId, "info"] }
var properties: [String : PropertyValue]
{
return ["offline_password": passwordHash.value, "shared": isShared.value]
}
var projectId: String { return Avatar.project(fromId: avatarId) }
// The key version of the avatar's name
// var nameKey: String { return Avatar.nameKey(ofId: avatarId) }
// Whether the info requires a password for authentication
var requiresPassword: Bool { return passwordHash != nil }
// INIT --------------------
init(avatarId: String, password: String? = nil, isShared: Bool = false)
{
self.avatarId = avatarId
self.isShared = isShared
if let password = password
{
// Uses the avatar id as salt
self.passwordHash = createPasswordHash(password: password)
}
}
private init(avatarId: String, passwordHash: String?, isShared: Bool)
{
self.avatarId = avatarId
self.passwordHash = passwordHash
self.isShared = isShared
}
static func create(from properties: PropertySet, withId id: Id) throws -> AvatarInfo
{
return AvatarInfo(avatarId: id[PROPERTY_AVATAR].string(), passwordHash: properties["offline_password"].string, isShared: properties["shared"].bool())
}
// IMPLEMENTED METHODS ---
func update(with properties: PropertySet)
{
if let isShared = properties["shared"].bool
{
self.isShared = isShared
}
if let passwordHash = properties["offline_password"].string
{
self.passwordHash = passwordHash
}
}
// OTHER METHODS -------
// Changes the image associated with this avatar
func setImage(_ image: UIImage) throws
{
if (_image != image)
{
_image = image
if let attachment = Attachment.parse(fromImage: image)
{
try saveAttachment(attachment, withName: "image")
}
}
}
// Updates the avatar's password
func setPassword(_ password: String)
{
passwordHash = createPasswordHash(password: password)
}
func resetPassword()
{
passwordHash = nil
}
func authenticate(loggedAccountId: String?, password: String) -> Bool
{
if passwordHash == nil
{
return true
}
else
{
return createPasswordHash(password: password) == passwordHash
}
}
private func createPasswordHash(password: String) -> String
{
return (avatarId + password).SHA256()
}
static func get(avatarId: String) throws -> AvatarInfo?
{
return try get(parseId(from: [avatarId, "info"]))
}
// The avatar id portion of the avatar info id string
static func avatarId(fromAvatarInfoId infoId: String) -> String
{
return property(withName: PROPERTY_AVATAR, fromId: infoId).string()
}
}
| mit | c85f09a360bce0d92c83ec959aacbec8 | 22.335766 | 286 | 0.685174 | 3.513187 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/SearchRange.swift | 1 | 1007 | //
// SearchRange.swift
// LeetCode
//
// Created by jourhuang on 2021/2/25.
// Copyright © 2021 伯驹 黄. All rights reserved.
//
import Foundation
// https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
var result = [-1, -1]
if nums.isEmpty {
return result
}
var start = 0
var end = nums.count - 1
while start <= end {
let mid = start + (end - start) / 2
if nums[mid] == target {
start = mid
end = mid
while start > 0 && target == nums[start - 1] {
start -= 1
}
while end < nums.count - 1 && target == nums[end + 1] {
end += 1
}
result[0] = start
result[1] = end
return result
} else if nums[mid] > target {
end -= 1
} else {
start += 1
}
}
return result
}
| mit | 78a17a07121df979f7d52e158961f1bd | 24 | 92 | 0.477 | 3.745318 | false | false | false | false |
Zuikyo/ZIKRouter | ZRouter/ServiceRouter/Alias.swift | 1 | 1279 | //
// Alias.swift
// ZRouter
//
// Created by zuik on 2017/11/5.
// Copyright © 2017 zuik. All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import ZIKRouter
public typealias RouterState = ZIKRouterState
public typealias RouteConfig = ZIKRouteConfiguration
public typealias PerformRouteConfig = ZIKPerformRouteConfiguration
public typealias RemoveRouteConfig = ZIKRemoveRouteConfiguration
public typealias AnyServiceRouter = ServiceRouter<Any, PerformRouteConfig>
public typealias ZIKAnyServiceRoute = ZIKServiceRoute<AnyObject, PerformRouteConfig>
public typealias ZIKAnyServiceRouter = ZIKServiceRouter<AnyObject, PerformRouteConfig>
public typealias ZIKAnyServiceRouterType = ZIKServiceRouterType<AnyObject, PerformRouteConfig>
public typealias ModuleServiceRouter<ModuleConfig> = ServiceRouter<Any, ModuleConfig>
public typealias ZIKModuleServiceRouter<ModuleConfig: PerformRouteConfig> = ZIKServiceRouter<AnyObject, ModuleConfig>
public typealias DestinationServiceRouter<Destination> = ServiceRouter<Destination, PerformRouteConfig>
public typealias ZIKDestinationServiceRouter<Destination: AnyObject> = ZIKServiceRouter<Destination, PerformRouteConfig>
| mit | 2b0c640fc3194a7069710b164dc364a9 | 48.153846 | 120 | 0.841941 | 4.698529 | false | true | false | false |
Witcast/witcast-ios | Pods/Material/Sources/Frameworks/Motion/Sources/MotionTransitionState.swift | 1 | 6441 | /*
* The MIT License (MIT)
*
* Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Original Inspiration & Author
* Copyright (c) 2016 Luke Zhao <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
internal class MotionTransitionStateWrapper {
/// A reference to a MotionTransitionState.
internal var state: MotionTransitionState
/**
An initializer that accepts a given MotionTransitionState.
- Parameter state: A MotionTransitionState.
*/
internal init(state: MotionTransitionState) {
self.state = state
}
}
public struct MotionTransitionState {
/// The initial state that the transition will start at.
internal var beginState: MotionTransitionStateWrapper?
/// The start state if there is a match in the desition view controller.
public var beginStateIfMatched: [MotionTransition]?
/// A reference to the position.
public var position: CGPoint?
/// A reference to the size.
public var size: CGSize?
/// A reference to the transform.
public var transform: CATransform3D?
/// A reference to the opacity.
public var opacity: Double?
/// A reference to the cornerRadius.
public var cornerRadius: CGFloat?
/// A reference to the backgroundColor.
public var backgroundColor: CGColor?
/// A reference to the zPosition.
public var zPosition: CGFloat?
/// A reference to the contentsRect.
public var contentsRect: CGRect?
/// A reference to the contentsScale.
public var contentsScale: CGFloat?
/// A reference to the borderWidth.
public var borderWidth: CGFloat?
/// A reference to the borderColor.
public var borderColor: CGColor?
/// A reference to the shadowColor.
public var shadowColor: CGColor?
/// A reference to the shadowOpacity.
public var shadowOpacity: Float?
/// A reference to the shadowOffset.
public var shadowOffset: CGSize?
/// A reference to the shadowRadius.
public var shadowRadius: CGFloat?
/// A reference to the shadowPath.
public var shadowPath: CGPath?
/// A boolean for the masksToBounds state.
public var masksToBounds: Bool?
/// A boolean indicating whether to display a shadow or not.
public var displayShadow = true
/// A reference to the overlay settings.
public var overlay: (color: CGColor, opacity: CGFloat)?
/// A reference to the spring animation settings.
public var spring: (CGFloat, CGFloat)?
/// A time delay on starting the animation.
public var delay: TimeInterval = 0
/// The duration of the animation.
public var duration: TimeInterval?
/// The timing function value of the animation.
public var timingFunction: CAMediaTimingFunction?
/// The arc curve value.
public var arc: CGFloat?
/// The identifier value to match source and destination views.
public var motionIdentifier: String?
/// The cascading animation settings.
public var cascade: (TimeInterval, CascadeDirection, Bool)?
/**
A boolean indicating whether to ignore the subview transition
animations or not.
*/
public var ignoreSubviewTransitions: Bool?
/// The coordinate space to transition views within.
public var coordinateSpace: MotionCoordinateSpace?
/// Change the size of a view based on a scale factor.
public var useScaleBasedSizeChange: Bool?
/// The type of snapshot to use.
public var snapshotType: MotionSnapshotType?
/// Do not fade the view when transitioning.
public var nonFade = false
/// Force an animation.
public var forceAnimate = false
/// Custom target states.
public var custom: [String: Any]?
/**
An initializer that accepts an Array of MotionTransitions.
- Parameter transitions: An Array of MotionTransitions.
*/
init(transitions: [MotionTransition]) {
append(contentsOf: transitions)
}
}
extension MotionTransitionState {
/**
Adds a MotionTransition to the current state.
- Parameter _ element: A MotionTransition.
*/
public mutating func append(_ element: MotionTransition) {
element.apply(&self)
}
/**
Adds an Array of MotionTransitions to the current state.
- Parameter contentsOf elements: An Array of MotionTransitions.
*/
public mutating func append(contentsOf elements: [MotionTransition]) {
for v in elements {
v.apply(&self)
}
}
/**
A subscript that returns a custom value for a specified key.
- Parameter key: A String.
- Returns: An optional Any value.
*/
public subscript(key: String) -> Any? {
get {
return custom?[key]
}
set(value) {
if nil == custom {
custom = [:]
}
custom![key] = value
}
}
}
extension MotionTransitionState: ExpressibleByArrayLiteral {
/**
An initializer implementing the ExpressibleByArrayLiteral protocol.
- Parameter arrayLiteral elements: A list of MotionTransitions.
*/
public init(arrayLiteral elements: MotionTransition...) {
append(contentsOf: elements)
}
}
| apache-2.0 | caf84e539aee9bc48f8a08e398292aa1 | 29.966346 | 81 | 0.672256 | 4.969907 | false | false | false | false |
CulturaMobile/culturamobile-api | Sources/App/Models/Dates.swift | 1 | 2125 | import Vapor
import FluentProvider
import AuthProvider
import HTTP
final class Dates: Model {
fileprivate static let databaseTableName = "dates"
static var entity = "dates"
let storage = Storage()
static let idKey = "id"
static let foreignIdKey = "date_id"
var startDate: Date
var endDate: Date
init(startDate: Date, endDate: Date) {
self.startDate = startDate
self.endDate = endDate
}
// MARK: Row
/// Initializes from the database row
init(row: Row) throws {
startDate = try row.get("start_date")
endDate = try row.get("end_date")
}
// Serializes object to the database
func makeRow() throws -> Row {
var row = Row()
try row.set("start_date", startDate)
try row.set("end_date", endDate)
return row
}
}
// MARK: Preparation
extension Dates: Preparation {
/// Prepares a table/collection in the database for storing objects
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.datetime("start_date")
builder.datetime("end_date")
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSON
// How the model converts from / to JSON.
//
extension Dates: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
startDate: json.get("start_date"),
endDate: json.get("end_date")
)
id = try json.get("id")
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("start_date", startDate)
try json.set("end_date", endDate)
return json
}
}
// MARK: HTTP
// This allows User models to be returned
// directly in route closures
extension Dates: ResponseRepresentable { }
extension Dates: Timestampable {
static var updatedAtKey: String { return "updated_at" }
static var createdAtKey: String { return "created_at" }
}
| mit | a0c8fd23c8c521bba76fa95475528df3 | 23.147727 | 71 | 0.607529 | 4.267068 | false | false | false | false |
grpc/grpc-swift | Tests/GRPCTests/AsyncAwaitSupport/AsyncServerHandler/ServerInterceptorStateMachine/ServerInterceptorStateMachineStreamStateTests.swift | 1 | 4860 | /*
* Copyright 2022, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if compiler(>=5.6)
@testable import GRPC
import XCTest
internal final class ServerInterceptorStateMachineStreamStateTests: GRPCTestCase {
func testInboundStreamState_receiveMetadataWhileIdle() {
var state = ServerInterceptorStateMachine.InboundStreamState.idle
XCTAssertEqual(state.receiveMetadata(), .accept)
XCTAssertEqual(state, .receivingMessages)
}
func testInboundStreamState_receiveMessageWhileIdle() {
let state = ServerInterceptorStateMachine.InboundStreamState.idle
XCTAssertEqual(state.receiveMessage(), .reject)
XCTAssertEqual(state, .idle)
}
func testInboundStreamState_receiveEndWhileIdle() {
var state = ServerInterceptorStateMachine.InboundStreamState.idle
XCTAssertEqual(state.receiveEnd(), .accept)
XCTAssertEqual(state, .done)
}
func testInboundStreamState_receiveMetadataWhileReceivingMessages() {
var state = ServerInterceptorStateMachine.InboundStreamState.receivingMessages
XCTAssertEqual(state.receiveMetadata(), .reject)
XCTAssertEqual(state, .receivingMessages)
}
func testInboundStreamState_receiveMessageWhileReceivingMessages() {
let state = ServerInterceptorStateMachine.InboundStreamState.receivingMessages
XCTAssertEqual(state.receiveMessage(), .accept)
XCTAssertEqual(state, .receivingMessages)
}
func testInboundStreamState_receiveEndWhileReceivingMessages() {
var state = ServerInterceptorStateMachine.InboundStreamState.receivingMessages
XCTAssertEqual(state.receiveEnd(), .accept)
XCTAssertEqual(state, .done)
}
func testInboundStreamState_receiveMetadataWhileDone() {
var state = ServerInterceptorStateMachine.InboundStreamState.done
XCTAssertEqual(state.receiveMetadata(), .reject)
XCTAssertEqual(state, .done)
}
func testInboundStreamState_receiveMessageWhileDone() {
let state = ServerInterceptorStateMachine.InboundStreamState.done
XCTAssertEqual(state.receiveMessage(), .reject)
XCTAssertEqual(state, .done)
}
func testInboundStreamState_receiveEndWhileDone() {
var state = ServerInterceptorStateMachine.InboundStreamState.done
XCTAssertEqual(state.receiveEnd(), .reject)
XCTAssertEqual(state, .done)
}
func testOutboundStreamState_sendMetadataWhileIdle() {
var state = ServerInterceptorStateMachine.OutboundStreamState.idle
XCTAssertEqual(state.sendMetadata(), .accept)
XCTAssertEqual(state, .writingMessages)
}
func testOutboundStreamState_sendMessageWhileIdle() {
let state = ServerInterceptorStateMachine.OutboundStreamState.idle
XCTAssertEqual(state.sendMessage(), .reject)
XCTAssertEqual(state, .idle)
}
func testOutboundStreamState_sendEndWhileIdle() {
var state = ServerInterceptorStateMachine.OutboundStreamState.idle
XCTAssertEqual(state.sendEnd(), .accept)
XCTAssertEqual(state, .done)
}
func testOutboundStreamState_sendMetadataWhileReceivingMessages() {
var state = ServerInterceptorStateMachine.OutboundStreamState.writingMessages
XCTAssertEqual(state.sendMetadata(), .reject)
XCTAssertEqual(state, .writingMessages)
}
func testOutboundStreamState_sendMessageWhileReceivingMessages() {
let state = ServerInterceptorStateMachine.OutboundStreamState.writingMessages
XCTAssertEqual(state.sendMessage(), .accept)
XCTAssertEqual(state, .writingMessages)
}
func testOutboundStreamState_sendEndWhileReceivingMessages() {
var state = ServerInterceptorStateMachine.OutboundStreamState.writingMessages
XCTAssertEqual(state.sendEnd(), .accept)
XCTAssertEqual(state, .done)
}
func testOutboundStreamState_sendMetadataWhileDone() {
var state = ServerInterceptorStateMachine.OutboundStreamState.done
XCTAssertEqual(state.sendMetadata(), .reject)
XCTAssertEqual(state, .done)
}
func testOutboundStreamState_sendMessageWhileDone() {
let state = ServerInterceptorStateMachine.OutboundStreamState.done
XCTAssertEqual(state.sendMessage(), .reject)
XCTAssertEqual(state, .done)
}
func testOutboundStreamState_sendEndWhileDone() {
var state = ServerInterceptorStateMachine.OutboundStreamState.done
XCTAssertEqual(state.sendEnd(), .reject)
XCTAssertEqual(state, .done)
}
}
#endif // compiler(>=5.6)
| apache-2.0 | 54bec7d734c5009973d1aeb3bdc1bb7e | 36.384615 | 82 | 0.781687 | 4.650718 | false | true | false | false |
kylelol/KKFloatingActionButton | Example/ViewController.swift | 1 | 2906 | //
// ViewController.swift
// FloatingMaterialButton
//
// Created by Kyle Kirkland on 7/10/15.
// Copyright (c) 2015 Kyle Kirkland. All rights reserved.
//
import UIKit
import KKFloatingActionButton
class ViewController: UIViewController {
@IBOutlet weak var floatingButton: KKFloatingMaterialButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Must get called before anything.
self.floatingButton.configureViews()
// Customization points.
self.floatingButton.dataSource = self
self.floatingButton.delegate = self
self.floatingButton.customTableViewCell = (UINib(nibName: "KKMenuTableViewCell", bundle: nil), "MenuTableCell")
self.floatingButton.buttonBgColor = UIColor.whiteColor()
self.floatingButton.menuBgColor = UIColor.whiteColor()
self.floatingButton.buttonShadowOpacity = 0.3
self.floatingButton.menuBgOpacity = 0.7
self.floatingButton.rotatingImage = UIImage(named: "plus_sign")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: KKFloatingMaterialButtonDelegate {
func menuTableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
NSLog("Selected row at index path ")
}
func menuTableView(tableView: UITableView, heightForCellAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60.0
}
}
extension ViewController: KKFloatingMaterialButtonDataSource {
func numberOfRowsInMenuTableView() -> Int {
return 5
}
func menuTableView(tableView: UITableView, cellForAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MenuTableCell") as! KKMenuTableViewCell
let buttonCenter = self.floatingButton.center
cell.imageViewTrailingConstraint.constant = self.view.frame.size.width - (buttonCenter.x + cell.imageContainerView.frame.size.width/2)
let tuple = tupleForIndexPath(indexPath)
cell.menuImageView.image = tuple.0
cell.menuLabel.text = tuple.1
cell.setNeedsLayout()
cell.layoutIfNeeded()
return cell
}
func tupleForIndexPath(indexPath: NSIndexPath) -> (UIImage, String) {
switch indexPath.row {
case 0:
return (UIImage(named: "albumImage")!, "Album")
case 1: return (UIImage(named: "contactImage")!, "Contact")
case 2: return (UIImage(named: "eventImage")!, "Event")
case 3: return (UIImage(named: "listImage")!, "List")
default : return (UIImage(named: "albumImage")!, "Default")
}
}
}
| mit | 55fe8d993a7b8396397175e140c4046e | 32.022727 | 142 | 0.675155 | 4.950596 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/Browser/URIFixup.swift | 3 | 2029 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
class URIFixup {
static func getURL(_ entry: String) -> URL? {
let trimmed = entry.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
guard let escaped = trimmed.addingPercentEncoding(withAllowedCharacters: CharacterSet.URLAllowedCharacterSet()) else {
return nil
}
// Then check if the URL includes a scheme. This will handle
// all valid requests starting with "http://", "about:", etc.
// However, we ensure that the scheme is one that is listed in
// the official URI scheme list, so that other such search phrases
// like "filetype:" are recognised as searches rather than URLs.
if let url = punycodedURL(escaped), url.schemeIsValid {
return url
}
// If there's no scheme, we're going to prepend "http://". First,
// make sure there's at least one "." in the host. This means
// we'll allow single-word searches (e.g., "foo") at the expense
// of breaking single-word hosts without a scheme (e.g., "localhost").
if trimmed.range(of: ".") == nil {
return nil
}
if trimmed.range(of: " ") != nil {
return nil
}
// If there is a ".", prepend "http://" and try again. Since this
// is strictly an "http://" URL, we also require a host.
if let url = punycodedURL("http://\(escaped)"), url.host != nil {
return url
}
return nil
}
static func punycodedURL(_ string: String) -> URL? {
var components = URLComponents(string: string)
if AppConstants.MOZ_PUNYCODE {
let host = components?.host?.utf8HostToAscii()
components?.host = host
}
return components?.url
}
}
| mpl-2.0 | c01850c6324b1094f561619f267a1f98 | 37.283019 | 126 | 0.604731 | 4.459341 | false | false | false | false |
HabitRPG/habitrpg-ios | HabiticaTests/MarkdownTests.swift | 1 | 31809 | //
// MarkdownTests.swift
// HabiticaTests
//
// Created by Phillip Thelen on 02.05.19.
// Copyright © 2019 HabitRPG Inc. All rights reserved.
//
import Foundation
import XCTest
@testable import Habitica
import Down
class MarkdownTests: XCTestCase {
func testOldMarkdownPerformance() throws {
let down = Down(markdownString: markdown)
measure {
let _ = try! down.toHabiticaAttributedString(useAST: false)
}
}
func testASTMarkdownPerformance() throws {
let down = Down(markdownString: markdown)
measure {
let _ = try! down.toHabiticaAttributedString()
}
}
func testASTMarkdownReference() throws {
let down = Down(markdownString: refMarkdown)
let result = try! down.toHabiticaAttributedString()
let ref = try! down.toHabiticaAttributedString(useAST: false)
XCTAssertEqual(result, ref)
}
let refMarkdown = """
# Heading
## Heading2
### Heading3
#### Heading4
##### Heading5
###### Heading6
This **is** a *paragraph* with `inline`
elements <p></p>
This is followed by a hard linebreak\(" ")
This is after the linebreak
---
[this is a link](www.text.com)

> this is a quote
```
code block
code block
```
<html>
block
</html>
1. first item
2. second item
"""
let markdown = """
Markdown: Syntax
================
<ul id="ProjectSubmenu">
<li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
<li><a href="/projects/markdown/basics" title="Markdown Basics">Basics</a></li>
<li><a class="selected" title="Markdown Syntax Documentation">Syntax</a></li>
<li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
<li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
</ul>
* [Overview](#overview)
* [Philosophy](#philosophy)
* [Inline HTML](#html)
* [Automatic Escaping for Special Characters](#autoescape)
* [Block Elements](#block)
* [Paragraphs and Line Breaks](#p)
* [Headers](#header)
* [Blockquotes](#blockquote)
* [Lists](#list)
* [Code Blocks](#precode)
* [Horizontal Rules](#hr)
* [Span Elements](#span)
* [Links](#link)
* [Emphasis](#em)
* [Code](#code)
* [Images](#img)
* [Miscellaneous](#misc)
* [Backslash Escapes](#backslash)
* [Automatic Links](#autolink)
**Note:** This document is itself written using Markdown; you
can [see the source for it by adding '.text' to the URL][src].
[src]: /projects/markdown/syntax.text
* * *
<h2 id="overview">Overview</h2>
<h3 id="philosophy">Philosophy</h3>
Markdown is intended to be as easy-to-read and easy-to-write as is feasible.
Readability, however, is emphasized above all else. A Markdown-formatted
document should be publishable as-is, as plain text, without looking
like it's been marked up with tags or formatting instructions. While
Markdown's syntax has been influenced by several existing text-to-HTML
filters -- including [Setext] [1], [atx] [2], [Textile] [3], [reStructuredText] [4],
[Grutatext] [5], and [EtText] [6] -- the single biggest source of
inspiration for Markdown's syntax is the format of plain text email.
[1]: http://docutils.sourceforge.net/mirror/setext.html
[2]: http://www.aaronsw.com/2002/atx/
[3]: http://textism.com/tools/textile/
[4]: http://docutils.sourceforge.net/rst.html
[5]: http://www.triptico.com/software/grutatxt.html
[6]: http://ettext.taint.org/doc/
To this end, Markdown's syntax is comprised entirely of punctuation
characters, which punctuation characters have been carefully chosen so
as to look like what they mean. E.g., asterisks around a word actually
look like \\*emphasis\\*. Markdown lists look like, well, lists. Even
blockquotes look like quoted passages of text, assuming you've ever
used email.
<h3 id="html">Inline HTML</h3>
Markdown's syntax is intended for one purpose: to be used as a
format for *writing* for the web.
Markdown is not a replacement for HTML, or even close to it. Its
syntax is very small, corresponding only to a very small subset of
HTML tags. The idea is *not* to create a syntax that makes it easier
to insert HTML tags. In my opinion, HTML tags are already easy to
insert. The idea for Markdown is to make it easy to read, write, and
edit prose. HTML is a *publishing* format; Markdown is a *writing*
format. Thus, Markdown's formatting syntax only addresses issues that
can be conveyed in plain text.
For any markup that is not covered by Markdown's syntax, you simply
use HTML itself. There's no need to preface it or delimit it to
indicate that you're switching from Markdown to HTML; you just use
the tags.
The only restrictions are that block-level HTML elements -- e.g. `<div>`,
`<table>`, `<pre>`, `<p>`, etc. -- must be separated from surrounding
content by blank lines, and the start and end tags of the block should
not be indented with tabs or spaces. Markdown is smart enough not
to add extra (unwanted) `<p>` tags around HTML block-level tags.
For example, to add an HTML table to a Markdown article:
This is a regular paragraph.
<table>
<tr>
<td>Foo</td>
</tr>
</table>
This is another regular paragraph.
Note that Markdown formatting syntax is not processed within block-level
HTML tags. E.g., you can't use Markdown-style `*emphasis*` inside an
HTML block.
Span-level HTML tags -- e.g. `<span>`, `<cite>`, or `<del>` -- can be
used anywhere in a Markdown paragraph, list item, or header. If you
want, you can even use HTML tags instead of Markdown formatting; e.g. if
you'd prefer to use HTML `<a>` or `<img>` tags instead of Markdown's
link or image syntax, go right ahead.
Unlike block-level HTML tags, Markdown syntax *is* processed within
span-level tags.
<h3 id="autoescape">Automatic Escaping for Special Characters</h3>
In HTML, there are two characters that demand special treatment: `<`
and `&`. Left angle brackets are used to start tags; ampersands are
used to denote HTML entities. If you want to use them as literal
characters, you must escape them as entities, e.g. `<`, and
`&`.
Ampersands in particular are bedeviling for web writers. If you want to
write about 'AT&T', you need to write '`AT&T`'. You even need to
escape ampersands within URLs. Thus, if you want to link to:
http://images.google.com/images?num=30&q=larry+bird
you need to encode the URL as:
http://images.google.com/images?num=30&q=larry+bird
in your anchor tag `href` attribute. Needless to say, this is easy to
forget, and is probably the single most common source of HTML validation
errors in otherwise well-marked-up web sites.
Markdown allows you to use these characters naturally, taking care of
all the necessary escaping for you. If you use an ampersand as part of
an HTML entity, it remains unchanged; otherwise it will be translated
into `&`.
So, if you want to include a copyright symbol in your article, you can write:
©
and Markdown will leave it alone. But if you write:
AT&T
Markdown will translate it to:
AT&T
Similarly, because Markdown supports [inline HTML](#html), if you use
angle brackets as delimiters for HTML tags, Markdown will treat them as
such. But if you write:
4 < 5
Markdown will translate it to:
4 < 5
However, inside Markdown code spans and blocks, angle brackets and
ampersands are *always* encoded automatically. This makes it easy to use
Markdown to write about HTML code. (As opposed to raw HTML, which is a
terrible format for writing about HTML syntax, because every single `<`
and `&` in your example code needs to be escaped.)
* * *
<h2 id="block">Block Elements</h2>
<h3 id="p">Paragraphs and Line Breaks</h3>
A paragraph is simply one or more consecutive lines of text, separated
by one or more blank lines. (A blank line is any line that looks like a
blank line -- a line containing nothing but spaces or tabs is considered
blank.) Normal paragraphs should not be indented with spaces or tabs.
The implication of the "one or more consecutive lines of text" rule is
that Markdown supports "hard-wrapped" text paragraphs. This differs
significantly from most other text-to-HTML formatters (including Movable
Type's "Convert Line Breaks" option) which translate every line break
character in a paragraph into a `<br />` tag.
When you *do* want to insert a `<br />` break tag using Markdown, you
end a line with two or more spaces, then type return.
Yes, this takes a tad more effort to create a `<br />`, but a simplistic
"every line break is a `<br />`" rule wouldn't work for Markdown.
Markdown's email-style [blockquoting][bq] and multi-paragraph [list items][l]
work best -- and look better -- when you format them with hard breaks.
[bq]: #blockquote
[l]: #list
<h3 id="header">Headers</h3>
Markdown supports two styles of headers, [Setext] [1] and [atx] [2].
Setext-style headers are "underlined" using equal signs (for first-level
headers) and dashes (for second-level headers). For example:
This is an H1
=============
This is an H2
-------------
Any number of underlining `=`'s or `-`'s will work.
Atx-style headers use 1-6 hash characters at the start of the line,
corresponding to header levels 1-6. For example:
# This is an H1
## This is an H2
###### This is an H6
Optionally, you may "close" atx-style headers. This is purely
cosmetic -- you can use this if you think it looks better. The
closing hashes don't even need to match the number of hashes
used to open the header. (The number of opening hashes
determines the header level.) :
# This is an H1 #
## This is an H2 ##
### This is an H3 ######
<h3 id="blockquote">Blockquotes</h3>
Markdown uses email-style `>` characters for blockquoting. If you're
familiar with quoting passages of text in an email message, then you
know how to create a blockquote in Markdown. It looks best if you hard
wrap the text and put a `>` before every line:
> This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
> consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
> Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
>
> Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
> id sem consectetuer libero luctus adipiscing.
Markdown allows you to be lazy and only put the `>` before the first
line of a hard-wrapped paragraph:
> This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
> Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
id sem consectetuer libero luctus adipiscing.
Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by
adding additional levels of `>`:
> This is the first level of quoting.
>
> > This is nested blockquote.
>
> Back to the first level.
Blockquotes can contain other Markdown elements, including headers, lists,
and code blocks:
> ## This is a header.
>
> 1. This is the first list item.
> 2. This is the second list item.
>
> Here's some example code:
>
> return shell_exec("echo $input | $markdown_script");
Any decent text editor should make email-style quoting easy. For
example, with BBEdit, you can make a selection and choose Increase
Quote Level from the Text menu.
<h3 id="list">Lists</h3>
Markdown supports ordered (numbered) and unordered (bulleted) lists.
Unordered lists use asterisks, pluses, and hyphens -- interchangably
-- as list markers:
* Red
* Green
* Blue
is equivalent to:
+ Red
+ Green
+ Blue
and:
- Red
- Green
- Blue
Ordered lists use numbers followed by periods:
1. Bird
2. McHale
3. Parish
It's important to note that the actual numbers you use to mark the
list have no effect on the HTML output Markdown produces. The HTML
Markdown produces from the above list is:
<ol>
<li>Bird</li>
<li>McHale</li>
<li>Parish</li>
</ol>
If you instead wrote the list in Markdown like this:
1. Bird
1. McHale
1. Parish
or even:
3. Bird
1. McHale
8. Parish
you'd get the exact same HTML output. The point is, if you want to,
you can use ordinal numbers in your ordered Markdown lists, so that
the numbers in your source match the numbers in your published HTML.
But if you want to be lazy, you don't have to.
If you do use lazy list numbering, however, you should still start the
list with the number 1. At some point in the future, Markdown may support
starting ordered lists at an arbitrary number.
List markers typically start at the left margin, but may be indented by
up to three spaces. List markers must be followed by one or more spaces
or a tab.
To make lists look nice, you can wrap items with hanging indents:
* Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
viverra nec, fringilla in, laoreet vitae, risus.
* Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
Suspendisse id sem consectetuer libero luctus adipiscing.
But if you want to be lazy, you don't have to:
* Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
viverra nec, fringilla in, laoreet vitae, risus.
* Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
Suspendisse id sem consectetuer libero luctus adipiscing.
If list items are separated by blank lines, Markdown will wrap the
items in `<p>` tags in the HTML output. For example, this input:
* Bird
* Magic
will turn into:
<ul>
<li>Bird</li>
<li>Magic</li>
</ul>
But this:
* Bird
* Magic
will turn into:
<ul>
<li><p>Bird</p></li>
<li><p>Magic</p></li>
</ul>
List items may consist of multiple paragraphs. Each subsequent
paragraph in a list item must be indented by either 4 spaces
or one tab:
1. This is a list item with two paragraphs. Lorem ipsum dolor
sit amet, consectetuer adipiscing elit. Aliquam hendrerit
mi posuere lectus.
Vestibulum enim wisi, viverra nec, fringilla in, laoreet
vitae, risus. Donec sit amet nisl. Aliquam semper ipsum
sit amet velit.
2. Suspendisse id sem consectetuer libero luctus adipiscing.
It looks nice if you indent every line of the subsequent
paragraphs, but here again, Markdown will allow you to be
lazy:
* This is a list item with two paragraphs.
This is the second paragraph in the list item. You're
only required to indent the first line. Lorem ipsum dolor
sit amet, consectetuer adipiscing elit.
* Another item in the same list.
To put a blockquote within a list item, the blockquote's `>`
delimiters need to be indented:
* A list item with a blockquote:
> This is a blockquote
> inside a list item.
To put a code block within a list item, the code block needs
to be indented *twice* -- 8 spaces or two tabs:
* A list item with a code block:
<code goes here>
It's worth noting that it's possible to trigger an ordered list by
accident, by writing something like this:
1986. What a great season.
In other words, a *number-period-space* sequence at the beginning of a
line. To avoid this, you can backslash-escape the period:
1986\\. What a great season.
<h3 id="precode">Code Blocks</h3>
Pre-formatted code blocks are used for writing about programming or
markup source code. Rather than forming normal paragraphs, the lines
of a code block are interpreted literally. Markdown wraps a code block
in both `<pre>` and `<code>` tags.
To produce a code block in Markdown, simply indent every line of the
block by at least 4 spaces or 1 tab. For example, given this input:
This is a normal paragraph:
This is a code block.
Markdown will generate:
<p>This is a normal paragraph:</p>
<pre><code>This is a code block.
</code></pre>
One level of indentation -- 4 spaces or 1 tab -- is removed from each
line of the code block. For example, this:
Here is an example of AppleScript:
tell application "Foo"
beep
end tell
will turn into:
<p>Here is an example of AppleScript:</p>
<pre><code>tell application "Foo"
beep
end tell
</code></pre>
A code block continues until it reaches a line that is not indented
(or the end of the article).
Within a code block, ampersands (`&`) and angle brackets (`<` and `>`)
are automatically converted into HTML entities. This makes it very
easy to include example HTML source code using Markdown -- just paste
it and indent it, and Markdown will handle the hassle of encoding the
ampersands and angle brackets. For example, this:
<div class="footer">
© 2004 Foo Corporation
</div>
will turn into:
<pre><code><div class="footer">
&copy; 2004 Foo Corporation
</div>
</code></pre>
Regular Markdown syntax is not processed within code blocks. E.g.,
asterisks are just literal asterisks within a code block. This means
it's also easy to use Markdown to write about Markdown's own syntax.
<h3 id="hr">Horizontal Rules</h3>
You can produce a horizontal rule tag (`<hr />`) by placing three or
more hyphens, asterisks, or underscores on a line by themselves. If you
wish, you may use spaces between the hyphens or asterisks. Each of the
following lines will produce a horizontal rule:
* * *
***
*****
- - -
---------------------------------------
* * *
<h2 id="span">Span Elements</h2>
<h3 id="link">Links</h3>
Markdown supports two style of links: *inline* and *reference*.
In both styles, the link text is delimited by [square brackets].
To create an inline link, use a set of regular parentheses immediately
after the link text's closing square bracket. Inside the parentheses,
put the URL where you want the link to point, along with an *optional*
title for the link, surrounded in quotes. For example:
This is [an example](http://example.com/ "Title") inline link.
[This link](http://example.net/) has no title attribute.
Will produce:
<p>This is <a href="http://example.com/" title="Title">
an example</a> inline link.</p>
<p><a href="http://example.net/">This link</a> has no
title attribute.</p>
If you're referring to a local resource on the same server, you can
use relative paths:
See my [About](/about/) page for details.
Reference-style links use a second set of square brackets, inside
which you place a label of your choosing to identify the link:
This is [an example][id] reference-style link.
You can optionally use a space to separate the sets of brackets:
This is [an example] [id] reference-style link.
Then, anywhere in the document, you define your link label like this,
on a line by itself:
[id]: http://example.com/ "Optional Title Here"
That is:
* Square brackets containing the link identifier (optionally
indented from the left margin using up to three spaces);
* followed by a colon;
* followed by one or more spaces (or tabs);
* followed by the URL for the link;
* optionally followed by a title attribute for the link, enclosed
in double or single quotes, or enclosed in parentheses.
The following three link definitions are equivalent:
[foo]: http://example.com/ "Optional Title Here"
[foo]: http://example.com/ 'Optional Title Here'
[foo]: http://example.com/ (Optional Title Here)
**Note:** There is a known bug in Markdown.pl 1.0.1 which prevents
single quotes from being used to delimit link titles.
The link URL may, optionally, be surrounded by angle brackets:
[id]: <http://example.com/> "Optional Title Here"
You can put the title attribute on the next line and use extra spaces
or tabs for padding, which tends to look better with longer URLs:
[id]: http://example.com/longish/path/to/resource/here
"Optional Title Here"
Link definitions are only used for creating links during Markdown
processing, and are stripped from your document in the HTML output.
Link definition names may consist of letters, numbers, spaces, and
punctuation -- but they are *not* case sensitive. E.g. these two
links:
[link text][a]
[link text][A]
are equivalent.
The *implicit link name* shortcut allows you to omit the name of the
link, in which case the link text itself is used as the name.
Just use an empty set of square brackets -- e.g., to link the word
"Google" to the google.com web site, you could simply write:
[Google][]
And then define the link:
[Google]: http://google.com/
Because link names may contain spaces, this shortcut even works for
multiple words in the link text:
Visit [Daring Fireball][] for more information.
And then define the link:
[Daring Fireball]: http://daringfireball.net/
Link definitions can be placed anywhere in your Markdown document. I
tend to put them immediately after each paragraph in which they're
used, but if you want, you can put them all at the end of your
document, sort of like footnotes.
Here's an example of reference links in action:
I get 10 times more traffic from [Google] [1] than from
[Yahoo] [2] or [MSN] [3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
Using the implicit link name shortcut, you could instead write:
I get 10 times more traffic from [Google][] than from
[Yahoo][] or [MSN][].
[google]: http://google.com/ "Google"
[yahoo]: http://search.yahoo.com/ "Yahoo Search"
[msn]: http://search.msn.com/ "MSN Search"
Both of the above examples will produce the following HTML output:
<p>I get 10 times more traffic from <a href="http://google.com/"
title="Google">Google</a> than from
<a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a>
or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>
For comparison, here is the same paragraph written using
Markdown's inline link style:
I get 10 times more traffic from [Google](http://google.com/ "Google")
than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or
[MSN](http://search.msn.com/ "MSN Search").
The point of reference-style links is not that they're easier to
write. The point is that with reference-style links, your document
source is vastly more readable. Compare the above examples: using
reference-style links, the paragraph itself is only 81 characters
long; with inline-style links, it's 176 characters; and as raw HTML,
it's 234 characters. In the raw HTML, there's more markup than there
is text.
With Markdown's reference-style links, a source document much more
closely resembles the final output, as rendered in a browser. By
allowing you to move the markup-related metadata out of the paragraph,
you can add links without interrupting the narrative flow of your
prose.
<h3 id="em">Emphasis</h3>
Markdown treats asterisks (`*`) and underscores (`_`) as indicators of
emphasis. Text wrapped with one `*` or `_` will be wrapped with an
HTML `<em>` tag; double `*`'s or `_`'s will be wrapped with an HTML
`<strong>` tag. E.g., this input:
*single asterisks*
_single underscores_
**double asterisks**
__double underscores__
will produce:
<em>single asterisks</em>
<em>single underscores</em>
<strong>double asterisks</strong>
<strong>double underscores</strong>
You can use whichever style you prefer; the lone restriction is that
the same character must be used to open and close an emphasis span.
Emphasis can be used in the middle of a word:
un*frigging*believable
But if you surround an `*` or `_` with spaces, it'll be treated as a
literal asterisk or underscore.
To produce a literal asterisk or underscore at a position where it
would otherwise be used as an emphasis delimiter, you can backslash
escape it:
\\*this text is surrounded by literal asterisks\\*
<h3 id="code">Code</h3>
To indicate a span of code, wrap it with backtick quotes (`` ` ``).
Unlike a pre-formatted code block, a code span indicates code within a
normal paragraph. For example:
Use the `printf()` function.
will produce:
<p>Use the <code>printf()</code> function.</p>
To include a literal backtick character within a code span, you can use
multiple backticks as the opening and closing delimiters:
``There is a literal backtick (`) here.``
which will produce this:
<p><code>There is a literal backtick (`) here.</code></p>
The backtick delimiters surrounding a code span may include spaces --
one after the opening, one before the closing. This allows you to place
literal backtick characters at the beginning or end of a code span:
A single backtick in a code span: `` ` ``
A backtick-delimited string in a code span: `` `foo` ``
will produce:
<p>A single backtick in a code span: <code>`</code></p>
<p>A backtick-delimited string in a code span: <code>`foo`</code></p>
With a code span, ampersands and angle brackets are encoded as HTML
entities automatically, which makes it easy to include example HTML
tags. Markdown will turn this:
Please don't use any `<blink>` tags.
into:
<p>Please don't use any <code><blink></code> tags.</p>
You can write this:
`—` is the decimal-encoded equivalent of `—`.
to produce:
<p><code>&#8212;</code> is the decimal-encoded
equivalent of <code>&mdash;</code>.</p>
<h3 id="img">Images</h3>
Admittedly, it's fairly difficult to devise a "natural" syntax for
placing images into a plain text document format.
Markdown uses an image syntax that is intended to resemble the syntax
for links, allowing for two styles: *inline* and *reference*.
Inline image syntax looks like this:


That is:
* An exclamation mark: `!`;
* followed by a set of square brackets, containing the `alt`
attribute text for the image;
* followed by a set of parentheses, containing the URL or path to
the image, and an optional `title` attribute enclosed in double
or single quotes.
Reference-style image syntax looks like this:
![Alt text][id]
Where "id" is the name of a defined image reference. Image references
are defined using syntax identical to link references:
[id]: url/to/image "Optional title attribute"
As of this writing, Markdown has no syntax for specifying the
dimensions of an image; if this is important to you, you can simply
use regular HTML `<img>` tags.
* * *
<h2 id="misc">Miscellaneous</h2>
<h3 id="autolink">Automatic Links</h3>
Markdown supports a shortcut style for creating "automatic" links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:
<http://example.com/>
Markdown will turn this into:
<a href="http://example.com/">http://example.com/</a>
Automatic links for email addresses work similarly, except that
Markdown will also perform a bit of randomized decimal and hex
entity-encoding to help obscure your address from address-harvesting
spambots. For example, Markdown will turn this:
<[email protected]>
into something like this:
<a href="mailto:addre
ss@example.co
m">address@exa
mple.com</a>
which will render in a browser as a clickable link to "[email protected]".
(This sort of entity-encoding trick will indeed fool many, if not
most, address-harvesting bots, but it definitely won't fool all of
them. It's better than nothing, but an address published in this way
will probably eventually start receiving spam.)
<h3 id="backslash">Backslash Escapes</h3>
Markdown allows you to use backslash escapes to generate literal
characters which would otherwise have special meaning in Markdown's
formatting syntax. For example, if you wanted to surround a word
with literal asterisks (instead of an HTML `<em>` tag), you can use
backslashes before the asterisks, like this:
\\*literal asterisks\\*
Markdown provides backslash escapes for the following characters:
\\ backslash
` backtick
* asterisk
_ underscore
{} curly braces
[] square brackets
() parentheses
# hash mark
+ plus sign
- minus sign (hyphen)
. dot
! exclamation mark
"""
}
| gpl-3.0 | b69df1ef6541f5a920ad4effd384b7ba | 31.859504 | 303 | 0.644743 | 4.188018 | false | false | false | false |
manhpro/website | iOSQuiz-master/iOSQuiz-master/LeoiOSQuiz/Classes/Services/API/APIServices.swift | 1 | 1826 | //
// APIServices.swift
// LeoiOSQuiz
//
// Created by NeoLap on 4/15/17.
// Copyright © 2017 Leo LE. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
import PromiseKit
class APIServices {
func request<T: Mappable>(_ input: APIBaseInput) -> Promise<T> {
var headers = input.headers
if input.isTokenRequired {
headers["Authorization"] = AppUserDefaults.authentication.tokenType + " " + AppUserDefaults.authentication.accessToken
}
return Promise { fulfill, reject in
Alamofire.request(input.urlString,
method: input.requestType,
parameters: input.parameters,
encoding: input.encoding,
headers: headers)
.validate(statusCode: 200..<600)
.responseJSON { (response) in
switch response.result {
case .success(let value):
if let statusCode = response.response?.statusCode {
switch statusCode {
case 200:
guard let data = value as? [String: Any], let t = T(JSON: data) else {
reject(ResponseError.invalidData)
return
}
fulfill(t)
case 401:
reject(ResponseError.unauthorized)
default:
reject(ResponseError.unknown(statusCode: statusCode))
}
}
case .failure(let error):
reject(error)
}
}
}
}
}
| cc0-1.0 | 7a3ed94a8a01fefb24d7088fa0c57048 | 32.796296 | 130 | 0.465753 | 5.887097 | false | false | false | false |
remypanicker/firefox-ios | ReadingList/ReadingListServerMetadata.swift | 34 | 1360 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
public struct ReadingListServerMetadata: Equatable {
public var guid: String
public var lastModified: ReadingListTimestamp
init(guid: String, lastModified: ReadingListTimestamp) {
self.guid = guid
self.lastModified = lastModified
}
/// Initialize from server record.
init?(json: AnyObject) {
let guid = json.valueForKeyPath("id") as? String
let lastModified = json.valueForKeyPath("last_modified") as? NSNumber
if guid == nil || lastModified == nil {
return nil
}
self.guid = guid!
self.lastModified = lastModified!.longLongValue
}
init?(row: AnyObject) {
let guid = row.valueForKeyPath("id") as? String
let lastModified = row.valueForKeyPath("last_modified") as? NSNumber
if guid == nil || lastModified == nil {
return nil
}
self.guid = guid!
self.lastModified = lastModified!.longLongValue
}
}
public func ==(lhs: ReadingListServerMetadata, rhs: ReadingListServerMetadata) -> Bool {
return lhs.guid == rhs.guid && lhs.lastModified == rhs.lastModified
}
| mpl-2.0 | 1bb9302f756867839e17f2ca14c488c8 | 33 | 88 | 0.651471 | 4.62585 | false | false | false | false |
abertelrud/swift-package-manager | IntegrationTests/Tests/IntegrationTests/Helpers.swift | 2 | 13035 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import XCTest
import TSCBasic
import TSCTestSupport
import enum TSCUtility.Git
let sdkRoot: AbsolutePath? = {
if let environmentPath = ProcessInfo.processInfo.environment["SDK_ROOT"] {
return AbsolutePath(environmentPath)
}
#if os(macOS)
let result = try! Process.popen(arguments: ["xcrun", "--sdk", "macosx", "--show-sdk-path"])
let sdkRoot = try! AbsolutePath(result.utf8Output().spm_chomp())
return sdkRoot
#else
return nil
#endif
}()
let toolchainPath: AbsolutePath = {
if let environmentPath = ProcessInfo.processInfo.environment["TOOLCHAIN_PATH"] {
return AbsolutePath(environmentPath)
}
#if os(macOS)
let swiftcPath = try! AbsolutePath(sh("xcrun", "--find", "swift").stdout.spm_chomp())
#else
let swiftcPath = try! AbsolutePath(sh("which", "swift").stdout.spm_chomp())
#endif
let toolchainPath = swiftcPath.parentDirectory.parentDirectory.parentDirectory
return toolchainPath
}()
let clang: AbsolutePath = {
if let environmentPath = ProcessInfo.processInfo.environment["CLANG_PATH"] {
return AbsolutePath(environmentPath)
}
let clangPath = toolchainPath.appending(components: "usr", "bin", "clang")
return clangPath
}()
let xcodebuild: AbsolutePath = {
#if os(macOS)
let xcodebuildPath = try! AbsolutePath(sh("xcrun", "--find", "xcodebuild").stdout.spm_chomp())
return xcodebuildPath
#else
fatalError("should not be used on other platforms than macOS")
#endif
}()
let swift: AbsolutePath = {
if let environmentPath = ProcessInfo.processInfo.environment["SWIFT_PATH"] {
return AbsolutePath(environmentPath)
}
let swiftPath = toolchainPath.appending(components: "usr", "bin", "swift")
return swiftPath
}()
let swiftc: AbsolutePath = {
if let environmentPath = ProcessInfo.processInfo.environment["SWIFTC_PATH"] {
return AbsolutePath(environmentPath)
}
let swiftcPath = toolchainPath.appending(components: "usr", "bin", "swiftc")
return swiftcPath
}()
let lldb: AbsolutePath = {
if let environmentPath = ProcessInfo.processInfo.environment["LLDB_PATH"] {
return AbsolutePath(environmentPath)
}
// We check if it exists because lldb doesn't exist in Xcode's default toolchain.
let toolchainLLDBPath = toolchainPath.appending(components: "usr", "bin", "lldb")
if localFileSystem.exists(toolchainLLDBPath) {
return toolchainLLDBPath
}
#if os(macOS)
let lldbPath = try! AbsolutePath(sh("xcrun", "--find", "lldb").stdout.spm_chomp())
return lldbPath
#else
fatalError("LLDB_PATH environment variable required")
#endif
}()
let swiftpmBinaryDirectory: AbsolutePath = {
if let environmentPath = ProcessInfo.processInfo.environment["SWIFTPM_BIN_DIR"] {
return AbsolutePath(environmentPath)
}
return swift.parentDirectory
}()
let swiftBuild: AbsolutePath = {
return swiftpmBinaryDirectory.appending(component: "swift-build")
}()
let swiftPackage: AbsolutePath = {
return swiftpmBinaryDirectory.appending(component: "swift-package")
}()
let swiftTest: AbsolutePath = {
return swiftpmBinaryDirectory.appending(component: "swift-test")
}()
let swiftRun: AbsolutePath = {
return swiftpmBinaryDirectory.appending(component: "swift-run")
}()
let isSelfHosted: Bool = {
return ProcessInfo.processInfo.environment["SWIFTCI_IS_SELF_HOSTED"] != nil
}()
@discardableResult
func sh(
_ arguments: CustomStringConvertible...,
env: [String: String] = [:],
file: StaticString = #file,
line: UInt = #line
) throws -> (stdout: String, stderr: String) {
let result = try _sh(arguments, env: env, file: file, line: line)
let stdout = try result.utf8Output()
let stderr = try result.utf8stderrOutput()
if result.exitStatus != .terminated(code: 0) {
XCTFail("Command failed with exit code: \(result.exitStatus) - \(result.integrationTests_debugDescription)", file: file, line: line)
}
return (stdout, stderr)
}
@discardableResult
func shFails(
_ arguments: CustomStringConvertible...,
env: [String: String] = [:],
file: StaticString = #file,
line: UInt = #line
) throws -> (stdout: String, stderr: String) {
let result = try _sh(arguments, env: env, file: file, line: line)
let stdout = try result.utf8Output()
let stderr = try result.utf8stderrOutput()
if result.exitStatus == .terminated(code: 0) {
XCTFail("Command unexpectedly succeeded with exit code: \(result.exitStatus) - \(result.integrationTests_debugDescription)", file: file, line: line)
}
return (stdout, stderr)
}
@discardableResult
func _sh(
_ arguments: [CustomStringConvertible],
env: [String: String] = [:],
file: StaticString = #file,
line: UInt = #line
) throws -> ProcessResult {
var environment = ProcessInfo.processInfo.environment
if let sdkRoot = sdkRoot {
environment["SDKROOT"] = sdkRoot.pathString
}
environment.merge(env, uniquingKeysWith: { $1 })
let result = try Process.popen(arguments: arguments.map { $0.description }, environment: environment)
return result
}
/// Test-helper function that runs a block of code on a copy of a test fixture
/// package. The copy is made into a temporary directory, and the block is
/// given a path to that directory. The block is permitted to modify the copy.
/// The temporary copy is deleted after the block returns. The fixture name may
/// contain `/` characters, which are treated as path separators, exactly as if
/// the name were a relative path.
func fixture(
name: String,
file: StaticString = #file,
line: UInt = #line,
body: (AbsolutePath) throws -> Void
) {
do {
// Make a suitable test directory name from the fixture subpath.
let fixtureSubpath = RelativePath(name)
let copyName = fixtureSubpath.components.joined(separator: "_")
// Create a temporary directory for the duration of the block.
try withTemporaryDirectory(prefix: copyName) { tmpDirPath in
defer {
// Unblock and remove the tmp dir on deinit.
try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])
try? localFileSystem.removeFileTree(tmpDirPath)
}
// Construct the expected path of the fixture.
// FIXME: This seems quite hacky; we should provide some control over where fixtures are found.
let fixtureDir = AbsolutePath("../../../Fixtures/\(name)", relativeTo: AbsolutePath(#file))
// Check that the fixture is really there.
guard localFileSystem.isDirectory(fixtureDir) else {
XCTFail("No such fixture: \(fixtureDir)", file: file, line: line)
return
}
// The fixture contains either a checkout or just a Git directory.
if localFileSystem.isFile(fixtureDir.appending(component: "Package.swift")) {
// It's a single package, so copy the whole directory as-is.
let dstDir = tmpDirPath.appending(component: copyName)
try systemQuietly("cp", "-R", "-H", fixtureDir.pathString, dstDir.pathString)
// Invoke the block, passing it the path of the copied fixture.
try body(dstDir)
} else {
// Copy each of the package directories and construct a git repo in it.
for fileName in try! localFileSystem.getDirectoryContents(fixtureDir).sorted() {
let srcDir = fixtureDir.appending(component: fileName)
guard localFileSystem.isDirectory(srcDir) else { continue }
let dstDir = tmpDirPath.appending(component: fileName)
try systemQuietly("cp", "-R", "-H", srcDir.pathString, dstDir.pathString)
initGitRepo(dstDir, tag: "1.2.3", addFile: false)
}
// Invoke the block, passing it the path of the copied fixture.
try body(tmpDirPath)
}
}
} catch {
XCTFail("\(error)", file: file, line: line)
}
}
/// Test-helper function that creates a new Git repository in a directory. The new repository will contain
/// exactly one empty file unless `addFile` is `false`, and if a tag name is provided, a tag with that name will be
/// created.
func initGitRepo(
_ dir: AbsolutePath,
tag: String? = nil,
addFile: Bool = true,
file: StaticString = #file,
line: UInt = #line
) {
initGitRepo(dir, tags: tag.flatMap({ [$0] }) ?? [], addFile: addFile, file: file, line: line)
}
func initGitRepo(
_ dir: AbsolutePath,
tags: [String],
addFile: Bool = true,
file: StaticString = #file,
line: UInt = #line
) {
do {
if addFile {
let file = dir.appending(component: "file.swift")
try localFileSystem.writeFileContents(file, bytes: "")
}
try systemQuietly([Git.tool, "-C", dir.pathString, "init"])
try systemQuietly([Git.tool, "-C", dir.pathString, "config", "user.email", "[email protected]"])
try systemQuietly([Git.tool, "-C", dir.pathString, "config", "user.name", "Example Example"])
try systemQuietly([Git.tool, "-C", dir.pathString, "config", "commit.gpgsign", "false"])
try systemQuietly([Git.tool, "-C", dir.pathString, "add", "."])
try systemQuietly([Git.tool, "-C", dir.pathString, "commit", "-m", "Add some files."])
for tag in tags {
try systemQuietly([Git.tool, "-C", dir.pathString, "tag", tag])
}
} catch {
XCTFail("\(error)", file: file, line: line)
}
}
func binaryTargetsFixture(_ closure: (AbsolutePath) throws -> Void) throws {
fixture(name: "BinaryTargets") { fixturePath in
let inputsPath = fixturePath.appending(component: "Inputs")
let packagePath = fixturePath.appending(component: "TestBinary")
// Generating StaticLibrary.xcframework.
try withTemporaryDirectory { tmpDir in
let subpath = inputsPath.appending(component: "StaticLibrary")
let sourcePath = subpath.appending(component: "StaticLibrary.m")
let headersPath = subpath.appending(component: "include")
let libraryPath = tmpDir.appending(component: "libStaticLibrary.a")
try sh(clang, "-c", sourcePath, "-I", headersPath, "-fobjc-arc", "-fmodules", "-o", libraryPath)
let xcframeworkPath = packagePath.appending(component: "StaticLibrary.xcframework")
try sh(xcodebuild, "-create-xcframework", "-library", libraryPath, "-headers", headersPath, "-output", xcframeworkPath)
}
// Generating DynamicLibrary.xcframework.
try withTemporaryDirectory { tmpDir in
let subpath = inputsPath.appending(component: "DynamicLibrary")
let sourcePath = subpath.appending(component: "DynamicLibrary.m")
let headersPath = subpath.appending(component: "include")
let libraryPath = tmpDir.appending(component: "libDynamicLibrary.dylib")
try sh(clang, sourcePath, "-I", headersPath, "-fobjc-arc", "-fmodules", "-dynamiclib", "-o", libraryPath)
let xcframeworkPath = packagePath.appending(component: "DynamicLibrary.xcframework")
try sh(xcodebuild, "-create-xcframework", "-library", libraryPath, "-headers", headersPath, "-output", xcframeworkPath)
}
// Generating SwiftFramework.xcframework.
try withTemporaryDirectory { tmpDir in
let subpath = inputsPath.appending(component: "SwiftFramework")
let projectPath = subpath.appending(component: "SwiftFramework.xcodeproj")
try sh(xcodebuild, "-project", projectPath, "-scheme", "SwiftFramework", "-derivedDataPath", tmpDir, "COMPILER_INDEX_STORE_ENABLE=NO")
let frameworkPath = AbsolutePath("Build/Products/Debug/SwiftFramework.framework", relativeTo: tmpDir)
let xcframeworkPath = packagePath.appending(component: "SwiftFramework.xcframework")
try sh(xcodebuild, "-create-xcframework", "-framework", frameworkPath, "-output", xcframeworkPath)
}
try closure(packagePath)
}
}
func XCTSkip(_ message: String? = nil) throws {
throw XCTSkip(message)
}
extension ProcessResult {
var integrationTests_debugDescription: String {
return """
command: \(arguments.map { $0.description }.joined(separator: " "))
stdout:
\((try? utf8Output()) ?? "")
stderr:
\((try? utf8stderrOutput()) ?? "")
"""
}
}
| apache-2.0 | 4999630cf7145acce73662af93cf7964 | 36.782609 | 156 | 0.656694 | 4.372694 | false | false | false | false |
k-thorat/Dotzu | Framework/Dotzu/Dotzu/ManagerListLogViewController.swift | 1 | 10042 | //
// ManagerListLogViewController.swift
// exampleWindow
//
// Created by Remi Robert on 06/12/2016.
// Copyright © 2016 Remi Robert. All rights reserved.
//
import UIKit
import MessageUI
class ManagerListLogViewController: UIViewController {
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var labelEmptyState: UILabel!
@IBOutlet weak var segment: UISegmentedControl!
@IBOutlet weak var buttonScrollDown: UIButton! {
didSet {
buttonScrollDown.isHidden = true
buttonScrollDown.layer.cornerRadius = 25
}
}
private let dataSourceLogs = ListLogDataSource<Log>()
fileprivate let dataSourceNetwork = ListLogDataSource<LogRequest>()
private var firstLaunch = true
private var obsLogs: NotificationObserver<Void>!
private var obsSettings: NotificationObserver<Void>!
private var obsNetwork: NotificationObserver<Void>!
fileprivate var state: ManagerListLogState = .logs {
didSet {
if state == .logs {
tableview.dataSource = dataSourceLogs
dataSourceLogs.reloadData()
} else {
tableview.dataSource = dataSourceNetwork
dataSourceNetwork.reloadData()
}
let count = state == .logs ? dataSourceLogs.count : dataSourceNetwork.count
let lastPath = state == .logs ? dataSourceLogs.lastPath : dataSourceNetwork.lastPath
tableview.reloadData()
if count > 0 {
tableview.scrollToRow(at: lastPath, at: .top, animated: false)
}
labelEmptyState.isHidden = count > 0
}
}
@IBAction func scrollDown(_ sender: Any) {
let lastPath = state == .logs ? dataSourceLogs.lastPath : dataSourceNetwork.lastPath
tableview.scrollToRow(at: lastPath, at: .top, animated: true)
}
@IBAction func didChangeState(_ sender: Any) {
state = ManagerListLogState(rawValue: segment.selectedSegmentIndex) ?? .logs
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let count = state == .logs ? dataSourceLogs.count : dataSourceNetwork.count
if count > 0 {
if firstLaunch {
firstLaunch = false
let lastPath = state == .logs ? dataSourceLogs.lastPath : dataSourceNetwork.lastPath
tableview.scrollToRow(at: lastPath, at: .top, animated: false)
} else {
changeStateButtonScrollDown(show: isScrollable(scrollView: tableview))
}
}
labelEmptyState.isHidden = count > 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
LogNotificationApp.resetCountBadge.post(Void())
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
LogNotificationApp.resetCountBadge.post(Void())
}
@IBAction func showActions() {
let alertController = UIAlertController(title: "More actions",
message: nil,
preferredStyle: .actionSheet)
let sendLogsButton = UIAlertAction(title: "Email logs",
style: .default,
handler: { [weak self] (action) in self?.emailLogs() })
alertController.addAction(sendLogsButton)
let resetLogsButton = UIAlertAction(title: "Reset logs & network",
style: .destructive,
handler: { [weak self] (action) in self?.resetLogs() })
alertController.addAction(resetLogsButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler:nil)
alertController.addAction(cancelButton)
self.navigationController?.present(alertController, animated: true, completion: nil)
}
private func emailLogs() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self;
let appName = Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String
mail.setSubject("\(appName ?? "App") Log")
var formattedData = Data()
for itemIndex in 0...self.dataSourceLogs.count {
if let log = self.dataSourceLogs[itemIndex] {
let format = LoggerFormat.format(log: log)
let data = Data(("Log Index:\(itemIndex)\n \(format.str) \n\n").utf8)
formattedData.append(data)
}
}
mail.addAttachmentData(formattedData, mimeType: "text/plain", fileName: "log-\(Date())")
self.present(mail, animated: true, completion: nil)
}
}
private func resetLogs() {
dataSourceLogs.reset()
dataSourceNetwork.reset()
let storeLogs = StoreManager<Log>(store: .log)
let storeNetwork = StoreManager<LogRequest>(store: .network)
storeLogs.reset()
storeNetwork.reset()
labelEmptyState.isHidden = false
tableview.reloadData()
}
private func initTableView() {
labelEmptyState.isHidden = true
tableview.registerCellWithNib(cell: LogTableViewCell.self)
tableview.registerCellWithNib(cell: LogNetworkTableViewCell.self)
tableview.estimatedRowHeight = 50
tableview.rowHeight = UITableView.automaticDimension
tableview.dataSource = dataSourceLogs
tableview.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
segment.tintColor = Color.mainGreen
initTableView()
dataSourceNetwork.reloadData()
dataSourceLogs.reloadData()
obsSettings = NotificationObserver(notification: LogNotificationApp.settingsChanged, block: { [weak self] _ in
guard let weakSelf = self else { return }
weakSelf.tableview.reloadData()
})
obsNetwork = NotificationObserver(notification: LogNotificationApp.stopRequest, block: { [weak self] _ in
guard let weakSelf = self, weakSelf.state == .network else { return }
DispatchQueue.main.async {
weakSelf.dataSourceNetwork.reloadData()
weakSelf.tableview.reloadData()
weakSelf.labelEmptyState.isHidden = weakSelf.dataSourceNetwork.count > 0
let lastPath = weakSelf.dataSourceNetwork.lastPath
let lastVisiblePath = weakSelf.tableview.indexPathsForVisibleRows?.last
if let lastVisiblePath = lastVisiblePath {
if lastVisiblePath.row + 1 >= lastPath.row {
weakSelf.tableview.scrollToRow(at: lastPath, at: .top, animated: false)
}
}
}
})
obsLogs = NotificationObserver(notification: LogNotificationApp.refreshLogs, block: { [weak self] _ in
guard let weakSelf = self, weakSelf.state == .logs else { return }
DispatchQueue.main.async {
weakSelf.dataSourceLogs.reloadData()
weakSelf.tableview.reloadData()
weakSelf.labelEmptyState.isHidden = weakSelf.dataSourceLogs.count > 0
let lastPath = weakSelf.dataSourceLogs.lastPath
let lastVisiblePath = weakSelf.tableview.indexPathsForVisibleRows?.last
if let lastVisiblePath = lastVisiblePath {
if lastVisiblePath.row + 1 >= lastPath.row {
weakSelf.tableview.scrollToRow(at: lastPath, at: .top, animated: false)
}
}
}
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? DetailRequestViewController,
let req = sender as? LogRequest {
controller.log = req
} else if let controller = segue.destination as? ContainerFilterViewController {
controller.state = state
}
}
}
extension ManagerListLogViewController: UIScrollViewDelegate {
fileprivate func changeStateButtonScrollDown(show: Bool) {
if show {
buttonScrollDown.isHidden = false
}
let widthScreen = UIScreen.main.bounds.size.width
UIView.animate(withDuration: 1, delay: show ? 0.5 : 0, usingSpringWithDamping: show ? 0.5 : 0, initialSpringVelocity: show ? 6 : 0, options: .curveEaseOut, animations: {
self.buttonScrollDown.frame.origin.x = show ? widthScreen - 60 : widthScreen
}, completion: nil)
}
fileprivate func isScrollable(scrollView: UIScrollView) -> Bool {
let ratio = scrollView.contentSize.height - scrollView.contentOffset.y
return !(ratio <= scrollView.frame.size.height)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
changeStateButtonScrollDown(show: isScrollable(scrollView: scrollView))
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
changeStateButtonScrollDown(show: isScrollable(scrollView: scrollView))
}
}
extension ManagerListLogViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if state == .logs {
return
}
guard let LogRequest = dataSourceNetwork[indexPath.row] else {return}
performSegue(withIdentifier: "detailRequestSegue", sender: LogRequest)
}
}
extension ManagerListLogViewController: MFMailComposeViewControllerDelegate {
public func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
| mit | a3b98c934733b4a54eeaf6ee1e1e7e2f | 38.845238 | 177 | 0.622548 | 5.246082 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKitDemo/SwiftMKitDemoNotifyContentExtension/NotificationViewController.swift | 1 | 2764 | //
// NotificationViewController.swift
// SwiftMKitDemoNotifyContentExtension
//
// Created by Mao on 11/11/2016.
// Copyright © 2016 cdts. All rights reserved.
//
import UIKit
import UserNotifications
import UserNotificationsUI
struct NotificationPresentItem {
let url: URL
let title: String
let text: String
}
@available(iOS 10.0, *)
class NotificationViewController: UIViewController, UNNotificationContentExtension {
var items: [NotificationPresentItem] = []
fileprivate var index: Int = 0
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any required interface initialization here.
}
func didReceive(_ notification: UNNotification) {
let content = notification.request.content
if let items = content.userInfo["items"] as? [[String: AnyObject]] {
for i in 0..<items.count {
let item = items[i]
guard let title = item["title"] as? String, let text = item["text"] as? String else {
continue
}
if i > content.attachments.count - 1 {
continue
}
let url = content.attachments[i].url
let presentItem = NotificationPresentItem(url: url, title: title, text: text)
self.items.append(presentItem)
}
}
updateUI(index: 0)
}
fileprivate func updateUI(index: Int) {
let item = items[index]
if item.url.startAccessingSecurityScopedResource() {
imageView.image = UIImage(contentsOfFile: item.url.path)
item.url.stopAccessingSecurityScopedResource()
}
label.text = item.title
textView.text = item.text
self.index = index
}
func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
if response.actionIdentifier == "switch" {
let nextIndex: Int
if index == 0 {
nextIndex = 1
} else {
nextIndex = 0
}
updateUI(index: nextIndex)
completion(.doNotDismiss)
} else if response.actionIdentifier == "open" {
completion(.dismissAndForwardAction)
} else if response.actionIdentifier == "dismiss" {
completion(.dismiss)
} else {
completion(.dismissAndForwardAction)
}
}
}
| mit | 86d59ce4fc8f91dda561a2a319948c93 | 29.362637 | 153 | 0.5751 | 5.313462 | false | false | false | false |
sishenyihuba/Weibo | Weibo/01-Home(首页)/PhotoBrowser/PhotoBrowserTransition.swift | 1 | 4007 | //
// PhotoBrowserTransition.swift
// Weibo
//
// Created by daixianglong on 2017/2/9.
// Copyright © 2017年 Dale. All rights reserved.
//
import UIKit
protocol TransitionDelegate : NSObjectProtocol {
func startRect(index : NSIndexPath) -> CGRect
func endRect(index : NSIndexPath) -> CGRect
func imageView(index : NSIndexPath) -> UIImageView
}
protocol DimissDelegate : NSObjectProtocol {
func indexPathForDismiss() -> NSIndexPath
func imageView() -> UIImageView
}
class PhotoBrowserTransition: NSObject {
var isPresented : Bool = false
var presentedDelegate : TransitionDelegate?
var dimissDelegate : DimissDelegate?
var index : NSIndexPath?
}
extension PhotoBrowserTransition :UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
return self
}
}
extension PhotoBrowserTransition : UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.3
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
isPresented ? animationForPresentedView(transitionContext) : animationForDismissView(transitionContext)
}
func animationForPresentedView(transitionContext: UIViewControllerContextTransitioning) {
// 1.取出弹出的View
let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey)!
// 2.将prensentedView添加到containerView中
transitionContext.containerView()?.backgroundColor = UIColor.blackColor()
transitionContext.containerView()?.addSubview(presentedView)
// 3.执行动画
presentedView.alpha = 0.0
guard let imageView = presentedDelegate?.imageView(index!) else {
return
}
guard let startRect = presentedDelegate?.startRect(index!) else {
return
}
guard let endRect = presentedDelegate?.endRect(index!) else {
return
}
imageView.frame = startRect
transitionContext.containerView()?.addSubview(imageView)
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 10, options: [], animations: {
imageView.frame = endRect
}) { (_) in
presentedView.alpha = 1.0
imageView.removeFromSuperview()
transitionContext.containerView()?.backgroundColor = UIColor.clearColor()
transitionContext.completeTransition(true)
}
}
func animationForDismissView(transitionContext: UIViewControllerContextTransitioning) {
guard let dismissDeletgate = dimissDelegate , presentedDelegate = presentedDelegate else {
return
}
// 1.取出消失的View
let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey)
dismissView?.removeFromSuperview()
// 2.执行动画
let imageView = dismissDeletgate.imageView()
transitionContext.containerView()?.addSubview(imageView)
let indexPath = dismissDeletgate.indexPathForDismiss()
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
imageView.frame = presentedDelegate.startRect(indexPath)
}) { (_) -> Void in
imageView.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
}
| mit | cf356acec25a13ba94f049a98b83c2c1 | 35.648148 | 217 | 0.691764 | 6.3126 | false | false | false | false |
abertelrud/swift-package-manager | Sources/PackageGraph/PackageGraph+Loading.swift | 2 | 44748 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import OrderedCollections
import PackageLoading
import PackageModel
import TSCBasic
extension PackageGraph {
/// Load the package graph for the given package path.
public static func load(
root: PackageGraphRoot,
identityResolver: IdentityResolver,
additionalFileRules: [FileRuleDescription] = [],
externalManifests: OrderedCollections.OrderedDictionary<PackageIdentity, (manifest: Manifest, fs: FileSystem)>,
requiredDependencies: Set<PackageReference> = [],
unsafeAllowedPackages: Set<PackageReference> = [],
binaryArtifacts: [PackageIdentity: [String: BinaryArtifact]],
shouldCreateMultipleTestProducts: Bool = false,
createREPLProduct: Bool = false,
customPlatformsRegistry: PlatformRegistry? = .none,
customXCTestMinimumDeploymentTargets: [PackageModel.Platform: PlatformVersion]? = .none,
testEntryPointPath: AbsolutePath? = nil,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) throws -> PackageGraph {
let observabilityScope = observabilityScope.makeChildScope(description: "Loading Package Graph")
// Create a map of the manifests, keyed by their identity.
var manifestMap = externalManifests
// prefer roots
root.manifests.forEach {
manifestMap[$0.key] = ($0.value, fileSystem)
}
let successors: (GraphLoadingNode) -> [GraphLoadingNode] = { node in
node.requiredDependencies().compactMap{ dependency in
return manifestMap[dependency.identity].map { (manifest, fileSystem) in
GraphLoadingNode(identity: dependency.identity, manifest: manifest, productFilter: dependency.productFilter, fileSystem: fileSystem)
}
}
}
// Construct the root root dependencies set.
let rootDependencies = Set(root.dependencies.compactMap{
manifestMap[$0.identity]?.manifest
})
let rootManifestNodes = root.packages.map { identity, package in
GraphLoadingNode(identity: identity, manifest: package.manifest, productFilter: .everything, fileSystem: fileSystem)
}
let rootDependencyNodes = root.dependencies.lazy.compactMap { (dependency: PackageDependency) -> GraphLoadingNode? in
manifestMap[dependency.identity].map {
GraphLoadingNode(identity: dependency.identity, manifest: $0.manifest, productFilter: dependency.productFilter, fileSystem: $0.fs)
}
}
let inputManifests = rootManifestNodes + rootDependencyNodes
// Collect the manifests for which we are going to build packages.
var allNodes: [GraphLoadingNode]
// Detect cycles in manifest dependencies.
if let cycle = findCycle(inputManifests, successors: successors) {
observabilityScope.emit(PackageGraphError.cycleDetected(cycle))
// Break the cycle so we can build a partial package graph.
allNodes = inputManifests.filter({ $0.manifest != cycle.cycle[0] })
} else {
// Sort all manifests toplogically.
allNodes = try topologicalSort(inputManifests, successors: successors)
}
var flattenedManifests: [PackageIdentity: GraphLoadingNode] = [:]
for node in allNodes {
if let existing = flattenedManifests[node.identity] {
let merged = GraphLoadingNode(
identity: node.identity,
manifest: node.manifest,
productFilter: existing.productFilter.union(node.productFilter),
fileSystem: node.fileSystem
)
flattenedManifests[node.identity] = merged
} else {
flattenedManifests[node.identity] = node
}
}
// sort by identity
allNodes = flattenedManifests.keys.sorted().map { flattenedManifests[$0]! } // force unwrap fine since we are iterating on keys
// Create the packages.
var manifestToPackage: [Manifest: Package] = [:]
for node in allNodes {
let nodeObservabilityScope = observabilityScope.makeChildScope(
description: "loading package \(node.identity)",
metadata: .packageMetadata(identity: node.identity, kind: node.manifest.packageKind)
)
let manifest = node.manifest
// Derive the path to the package.
//
// FIXME: Lift this out of the manifest.
let packagePath = manifest.path.parentDirectory
nodeObservabilityScope.trap {
// Create a package from the manifest and sources.
let builder = PackageBuilder(
identity: node.identity,
manifest: manifest,
productFilter: node.productFilter,
path: packagePath,
additionalFileRules: additionalFileRules,
binaryArtifacts: binaryArtifacts[node.identity] ?? [:],
shouldCreateMultipleTestProducts: shouldCreateMultipleTestProducts,
testEntryPointPath: testEntryPointPath,
createREPLProduct: manifest.packageKind.isRoot ? createREPLProduct : false,
fileSystem: node.fileSystem,
observabilityScope: nodeObservabilityScope
)
let package = try builder.construct()
manifestToPackage[manifest] = package
// Throw if any of the non-root package is empty.
if package.targets.isEmpty // System packages have targets in the package but not the manifest.
&& package.manifest.targets.isEmpty // An unneeded dependency will not have loaded anything from the manifest.
&& !manifest.packageKind.isRoot {
throw PackageGraphError.noModules(package)
}
}
}
// Resolve dependencies and create resolved packages.
let resolvedPackages = try createResolvedPackages(
nodes: allNodes,
identityResolver: identityResolver,
manifestToPackage: manifestToPackage,
rootManifests: root.manifests,
unsafeAllowedPackages: unsafeAllowedPackages,
platformRegistry: customPlatformsRegistry ?? .default,
xcTestMinimumDeploymentTargets: customXCTestMinimumDeploymentTargets ?? MinimumDeploymentTarget.default.xcTestMinimumDeploymentTargets,
observabilityScope: observabilityScope
)
let rootPackages = resolvedPackages.filter{ root.manifests.values.contains($0.manifest) }
checkAllDependenciesAreUsed(rootPackages, observabilityScope: observabilityScope)
return try PackageGraph(
rootPackages: rootPackages,
rootDependencies: resolvedPackages.filter{ rootDependencies.contains($0.manifest) },
dependencies: requiredDependencies,
binaryArtifacts: binaryArtifacts
)
}
}
private func checkAllDependenciesAreUsed(_ rootPackages: [ResolvedPackage], observabilityScope: ObservabilityScope) {
for package in rootPackages {
// List all dependency products dependent on by the package targets.
let productDependencies: Set<ResolvedProduct> = Set(package.targets.flatMap({ target in
return target.dependencies.compactMap({ targetDependency in
switch targetDependency {
case .product(let product, _):
return product
case .target:
return nil
}
})
}))
for dependency in package.dependencies {
// We continue if the dependency contains executable products to make sure we don't
// warn on a valid use-case for a lone dependency: swift run dependency executables.
guard !dependency.products.contains(where: { $0.type == .executable }) else {
continue
}
// Skip this check if this dependency is a system module because system module packages
// have no products.
//
// FIXME: Do/should we print a warning if a dependency has no products?
if dependency.products.isEmpty && dependency.targets.filter({ $0.type == .systemModule }).count == 1 {
continue
}
// Skip this check if this dependency contains a command plugin product.
if dependency.products.contains(where: \.isCommandPlugin) {
continue
}
// Otherwise emit a warning if none of the dependency package's products are used.
let dependencyIsUsed = dependency.products.contains(where: productDependencies.contains)
if !dependencyIsUsed && !observabilityScope.errorsReportedInAnyScope {
observabilityScope.emit(.unusedDependency(dependency.identity.description))
}
}
}
}
fileprivate extension ResolvedProduct {
/// Returns true if and only if the product represents a command plugin target.
var isCommandPlugin: Bool {
guard type == .plugin else { return false }
guard let target = underlyingProduct.targets.compactMap({ $0 as? PluginTarget }).first else { return false }
guard case .command = target.capability else { return false }
return true
}
}
/// Create resolved packages from the loaded packages.
private func createResolvedPackages(
nodes: [GraphLoadingNode],
identityResolver: IdentityResolver,
manifestToPackage: [Manifest: Package],
// FIXME: This shouldn't be needed once <rdar://problem/33693433> is fixed.
rootManifests: [PackageIdentity: Manifest],
unsafeAllowedPackages: Set<PackageReference>,
platformRegistry: PlatformRegistry,
xcTestMinimumDeploymentTargets: [PackageModel.Platform: PlatformVersion],
observabilityScope: ObservabilityScope
) throws -> [ResolvedPackage] {
// Create package builder objects from the input manifests.
let packageBuilders: [ResolvedPackageBuilder] = nodes.compactMap{ node in
guard let package = manifestToPackage[node.manifest] else {
return nil
}
let isAllowedToVendUnsafeProducts = unsafeAllowedPackages.contains{ $0.identity == package.identity }
let allowedToOverride = rootManifests.values.contains(node.manifest)
return ResolvedPackageBuilder(
package,
productFilter: node.productFilter,
isAllowedToVendUnsafeProducts: isAllowedToVendUnsafeProducts,
allowedToOverride: allowedToOverride
)
}
// Create a map of package builders keyed by the package identity.
// This is guaranteed to be unique so we can use spm_createDictionary
let packagesByIdentity: [PackageIdentity: ResolvedPackageBuilder] = packageBuilders.spm_createDictionary{
return ($0.package.identity, $0)
}
// Resolve module aliases, if specified, for targets and their dependencies
// across packages. Aliasing will result in target renaming.
let moduleAliasingUsed = try resolveModuleAliases(packageBuilders: packageBuilders, observabilityScope: observabilityScope)
// Scan and validate the dependencies
for packageBuilder in packageBuilders {
let package = packageBuilder.package
let packageObservabilityScope = observabilityScope.makeChildScope(
description: "Validating package dependencies",
metadata: package.diagnosticsMetadata
)
var dependencies = OrderedCollections.OrderedDictionary<PackageIdentity, ResolvedPackageBuilder>()
var dependenciesByNameForTargetDependencyResolution = [String: ResolvedPackageBuilder]()
// Establish the manifest-declared package dependencies.
package.manifest.dependenciesRequired(for: packageBuilder.productFilter).forEach { dependency in
let dependencyPackageRef = dependency.createPackageRef()
// Otherwise, look it up by its identity.
if let resolvedPackage = packagesByIdentity[dependency.identity] {
// check if this resolved package already listed in the dependencies
// this means that the dependencies share the same identity
// FIXME: this works but the way we find out about this is based on a side effect, need to improve it
guard dependencies[resolvedPackage.package.identity] == nil else {
let error = PackageGraphError.dependencyAlreadySatisfiedByIdentifier(
package: package.identity.description,
dependencyLocation: dependencyPackageRef.locationString,
otherDependencyURL: resolvedPackage.package.manifest.packageLocation,
identity: dependency.identity)
return packageObservabilityScope.emit(error)
}
// check if the resolved package location is the same as the dependency one
// if not, this means that the dependencies share the same identity
// which only allowed when overriding
if resolvedPackage.package.manifest.canonicalPackageLocation != dependencyPackageRef.canonicalLocation && !resolvedPackage.allowedToOverride {
let error = PackageGraphError.dependencyAlreadySatisfiedByIdentifier(
package: package.identity.description,
dependencyLocation: dependencyPackageRef.locationString,
otherDependencyURL: resolvedPackage.package.manifest.packageLocation,
identity: dependency.identity)
// 9/2021 this is currently emitting a warning only to support
// backwards compatibility with older versions of SwiftPM that had too weak of a validation
// we will upgrade this to an error in a few versions to tighten up the validation
if dependency.explicitNameForTargetDependencyResolutionOnly == .none ||
resolvedPackage.package.manifest.displayName == dependency.explicitNameForTargetDependencyResolutionOnly {
packageObservabilityScope.emit(warning: error.description + ". this will be escalated to an error in future versions of SwiftPM.")
} else {
return packageObservabilityScope.emit(error)
}
} else if resolvedPackage.package.manifest.canonicalPackageLocation == dependencyPackageRef.canonicalLocation &&
resolvedPackage.package.manifest.packageLocation != dependencyPackageRef.locationString &&
!resolvedPackage.allowedToOverride {
packageObservabilityScope.emit(info: "dependency on '\(resolvedPackage.package.identity)' is represented by similar locations ('\(resolvedPackage.package.manifest.packageLocation)' and '\(dependencyPackageRef.locationString)') which are treated as the same canonical location '\(dependencyPackageRef.canonicalLocation)'.")
}
// checks if two dependencies have the same explicit name which can cause target based dependency package lookup issue
if let explicitDependencyName = dependency.explicitNameForTargetDependencyResolutionOnly {
if let previouslyResolvedPackage = dependenciesByNameForTargetDependencyResolution[explicitDependencyName] {
let error = PackageGraphError.dependencyAlreadySatisfiedByName(
package: package.identity.description,
dependencyLocation: dependencyPackageRef.locationString,
otherDependencyURL: previouslyResolvedPackage.package.manifest.packageLocation,
name: explicitDependencyName)
return packageObservabilityScope.emit(error)
}
}
// checks if two dependencies have the same implicit (identity based) name which can cause target based dependency package lookup issue
if let previouslyResolvedPackage = dependenciesByNameForTargetDependencyResolution[dependency.identity.description] {
let error = PackageGraphError.dependencyAlreadySatisfiedByName(
package: package.identity.description,
dependencyLocation: dependencyPackageRef.locationString,
otherDependencyURL: previouslyResolvedPackage.package.manifest.packageLocation,
name: dependency.identity.description)
return packageObservabilityScope.emit(error)
}
let nameForTargetDependencyResolution = dependency.explicitNameForTargetDependencyResolutionOnly ?? dependency.identity.description
dependenciesByNameForTargetDependencyResolution[nameForTargetDependencyResolution] = resolvedPackage
dependencies[resolvedPackage.package.identity] = resolvedPackage
}
}
packageBuilder.dependencies = Array(dependencies.values)
packageBuilder.defaultLocalization = package.manifest.defaultLocalization
packageBuilder.platforms = computePlatforms(
package: package,
usingXCTest: false,
platformRegistry: platformRegistry,
xcTestMinimumDeploymentTargets: xcTestMinimumDeploymentTargets
)
let testPlatforms = computePlatforms(
package: package,
usingXCTest: true,
platformRegistry: platformRegistry,
xcTestMinimumDeploymentTargets: xcTestMinimumDeploymentTargets
)
// Create target builders for each target in the package.
let targetBuilders = package.targets.map{ ResolvedTargetBuilder(target: $0, observabilityScope: observabilityScope) }
packageBuilder.targets = targetBuilders
// Establish dependencies between the targets. A target can only depend on another target present in the same package.
let targetMap = targetBuilders.spm_createDictionary({ ($0.target, $0) })
for targetBuilder in targetBuilders {
targetBuilder.dependencies += try targetBuilder.target.dependencies.compactMap { dependency in
switch dependency {
case .target(let target, let conditions):
guard let targetBuilder = targetMap[target] else {
throw InternalError("unknown target \(target.name)")
}
return .target(targetBuilder, conditions: conditions)
case .product:
return nil
}
}
targetBuilder.defaultLocalization = packageBuilder.defaultLocalization
targetBuilder.platforms = targetBuilder.target.type == .test ? testPlatforms : packageBuilder.platforms
}
// Create product builders for each product in the package. A product can only contain a target present in the same package.
packageBuilder.products = try package.products.map{
try ResolvedProductBuilder(product: $0, packageBuilder: packageBuilder, targets: $0.targets.map {
guard let target = targetMap[$0] else {
throw InternalError("unknown target \($0)")
}
return target
})
}
}
let dupProductsChecker = DuplicateProductsChecker(packageBuilders: packageBuilders)
try dupProductsChecker.run(lookupByProductIDs: moduleAliasingUsed, observabilityScope: observabilityScope)
// The set of all target names.
var allTargetNames = Set<String>()
// Track if multiple targets are found with the same name.
var foundDuplicateTarget = false
// Do another pass and establish product dependencies of each target.
for packageBuilder in packageBuilders {
let package = packageBuilder.package
let packageObservabilityScope = observabilityScope.makeChildScope(
description: "Validating package targets",
metadata: package.diagnosticsMetadata
)
// Get all implicit system library dependencies in this package.
let implicitSystemTargetDeps = packageBuilder.dependencies
.flatMap({ $0.targets })
.filter({
if case let systemLibrary as SystemLibraryTarget = $0.target {
return systemLibrary.isImplicit
}
return false
})
let lookupByProductIDs = packageBuilder.package.manifest.disambiguateByProductIDs || moduleAliasingUsed
// Get all the products from dependencies of this package.
let productDependencies = packageBuilder.dependencies
.flatMap({ (dependency: ResolvedPackageBuilder) -> [ResolvedProductBuilder] in
// Filter out synthesized products such as tests and implicit executables.
// Check if a dependency product is explicitly declared as a product in its package manifest
let manifestProducts = dependency.package.manifest.products.lazy.map { $0.name }
let explicitProducts = dependency.package.products.filter { manifestProducts.contains($0.name) }
let explicitIdsOrNames = Set(explicitProducts.lazy.map({ lookupByProductIDs ? $0.identity : $0.name }))
return dependency.products.filter({ lookupByProductIDs ? explicitIdsOrNames.contains($0.product.identity) : explicitIdsOrNames.contains($0.product.name) })
})
let productDependencyMap = lookupByProductIDs ? productDependencies.spm_createDictionary({ ($0.product.identity, $0) }) : productDependencies.spm_createDictionary({ ($0.product.name, $0) })
// Establish dependencies in each target.
for targetBuilder in packageBuilder.targets {
// Record if we see a duplicate target.
foundDuplicateTarget = foundDuplicateTarget || !allTargetNames.insert(targetBuilder.target.name).inserted
// Directly add all the system module dependencies.
targetBuilder.dependencies += implicitSystemTargetDeps.map { .target($0, conditions: []) }
// Establish product dependencies.
for case .product(let productRef, let conditions) in targetBuilder.target.dependencies {
// Find the product in this package's dependency products.
// Look it up by ID if module aliasing is used, otherwise by name.
let product = lookupByProductIDs ? productDependencyMap[productRef.identity] : productDependencyMap[productRef.name]
guard let product = product else {
// Only emit a diagnostic if there are no other diagnostics.
// This avoids flooding the diagnostics with product not
// found errors when there are more important errors to
// resolve (like authentication issues).
if !observabilityScope.errorsReportedInAnyScope {
// Emit error if a product (not target) declared in the package is also a productRef (dependency)
let declProductsAsDependency = package.products.filter { product in
lookupByProductIDs ? product.identity == productRef.identity : product.name == productRef.name
}.map {$0.targets}.flatMap{$0}.filter { t in
t.name != productRef.name
}
let error = PackageGraphError.productDependencyNotFound(
package: package.identity.description,
targetName: targetBuilder.target.name,
dependencyProductName: productRef.name,
dependencyPackageName: productRef.package,
dependencyProductInDecl: !declProductsAsDependency.isEmpty
)
packageObservabilityScope.emit(error)
}
continue
}
// Starting in 5.2, and target-based dependency, we require target product dependencies to
// explicitly reference the package containing the product, or for the product, package and
// dependency to share the same name. We don't check this in manifest loading for root-packages so
// we can provide a more detailed diagnostic here.
if packageBuilder.package.manifest.toolsVersion >= .v5_2 && productRef.package == nil {
let referencedPackageIdentity = product.packageBuilder.package.identity
guard let referencedPackageDependency = (packageBuilder.package.manifest.dependencies.first { package in
return package.identity == referencedPackageIdentity
}) else {
throw InternalError("dependency reference for \(product.packageBuilder.package.manifest.packageLocation) not found")
}
let referencedPackageName = referencedPackageDependency.nameForTargetDependencyResolutionOnly
if productRef.name != referencedPackageName {
let error = PackageGraphError.productDependencyMissingPackage(
productName: productRef.name,
targetName: targetBuilder.target.name,
packageIdentifier: referencedPackageName
)
packageObservabilityScope.emit(error)
}
}
targetBuilder.dependencies.append(.product(product, conditions: conditions))
}
}
}
// If a target with similar name was encountered before, we emit a diagnostic.
if foundDuplicateTarget {
for targetName in allTargetNames.sorted() {
// Find the packages this target is present in.
let packages = packageBuilders
.filter({ $0.targets.contains(where: { $0.target.name == targetName }) })
.map{ $0.package.identity.description }
.sorted()
if packages.count > 1 {
observabilityScope.emit(ModuleError.duplicateModule(targetName, packages))
}
}
}
return try packageBuilders.map{ try $0.construct() }
}
fileprivate extension Product {
var isDefaultLibrary: Bool {
return type == .library(.automatic)
}
}
private class DuplicateProductsChecker {
var packageIDToBuilder = [String: ResolvedPackageBuilder]()
var checkedPkgIDs = [String]()
init(packageBuilders: [ResolvedPackageBuilder]) {
for packageBuilder in packageBuilders {
let pkgID = packageBuilder.package.identity.description.lowercased()
packageIDToBuilder[pkgID] = packageBuilder
}
}
func run(lookupByProductIDs: Bool = false, observabilityScope: ObservabilityScope) throws {
var productToPkgMap = [String: [String]]()
for (_, pkgBuilder) in packageIDToBuilder {
let useProductIDs = pkgBuilder.package.manifest.disambiguateByProductIDs || lookupByProductIDs
let depProductRefs = pkgBuilder.package.targets.map{$0.dependencies}.flatMap{$0}.compactMap{$0.product}
for depRef in depProductRefs {
if let depPkg = depRef.package?.lowercased() {
checkedPkgIDs.append(depPkg)
let depProductIDs = packageIDToBuilder[depPkg]?.package.products.filter { $0.identity == depRef.identity }.map { useProductIDs && $0.isDefaultLibrary ? $0.identity : $0.name } ?? []
for depID in depProductIDs {
productToPkgMap[depID, default: []].append(depPkg)
}
} else {
let depPkgs = pkgBuilder.dependencies.filter{$0.products.contains{$0.product.name == depRef.name}}.map{$0.package.identity.description.lowercased()}
productToPkgMap[depRef.name, default: []].append(contentsOf: depPkgs)
checkedPkgIDs.append(contentsOf: depPkgs)
}
}
for (depIDOrName, depPkgs) in productToPkgMap.filter({Set($0.value).count > 1}) {
let name = depIDOrName.components(separatedBy: "_").dropFirst().joined(separator: "_")
throw PackageGraphError.duplicateProduct(product: name.isEmpty ? depIDOrName : name, packages: depPkgs.sorted())
}
}
let uncheckedPkgs = packageIDToBuilder.filter{!checkedPkgIDs.contains($0.key)}
for (pkgID, pkgBuilder) in uncheckedPkgs {
let productIDOrNames = pkgBuilder.products.map { pkgBuilder.package.manifest.disambiguateByProductIDs && $0.product.isDefaultLibrary ? $0.product.identity : $0.product.name }
for productIDOrName in productIDOrNames {
productToPkgMap[productIDOrName, default: []].append(pkgID)
}
}
let duplicates = productToPkgMap.filter({Set($0.value).count > 1})
for (productName, pkgs) in duplicates {
throw PackageGraphError.duplicateProduct(product: productName, packages: pkgs.sorted())
}
}
}
private func computePlatforms(
package: Package,
usingXCTest: Bool,
platformRegistry: PlatformRegistry,
xcTestMinimumDeploymentTargets: [PackageModel.Platform: PlatformVersion]
) -> SupportedPlatforms {
// the supported platforms as declared in the manifest
let declaredPlatforms: [SupportedPlatform] = package.manifest.platforms.map { platform in
let declaredPlatform = platformRegistry.platformByName[platform.platformName]
?? PackageModel.Platform.custom(name: platform.platformName, oldestSupportedVersion: platform.version)
return SupportedPlatform(
platform: declaredPlatform,
version: .init(platform.version),
options: platform.options
)
}
// the derived platforms based on known minimum deployment target logic
var derivedPlatforms = [SupportedPlatform]()
/// Add each declared platform to the supported platforms list.
for platform in package.manifest.platforms {
let declaredPlatform = platformRegistry.platformByName[platform.platformName]
?? PackageModel.Platform.custom(name: platform.platformName, oldestSupportedVersion: platform.version)
var version = PlatformVersion(platform.version)
if usingXCTest, let xcTestMinimumDeploymentTarget = xcTestMinimumDeploymentTargets[declaredPlatform], version < xcTestMinimumDeploymentTarget {
version = xcTestMinimumDeploymentTarget
}
// If the declared version is smaller than the oldest supported one, we raise the derived version to that.
if version < declaredPlatform.oldestSupportedVersion {
version = declaredPlatform.oldestSupportedVersion
}
let supportedPlatform = SupportedPlatform(
platform: declaredPlatform,
version: version,
options: platform.options
)
derivedPlatforms.append(supportedPlatform)
}
// Find the undeclared platforms.
let remainingPlatforms = Set(platformRegistry.platformByName.keys).subtracting(derivedPlatforms.map({ $0.platform.name }))
/// Start synthesizing for each undeclared platform.
for platformName in remainingPlatforms.sorted() {
let platform = platformRegistry.platformByName[platformName]!
let minimumSupportedVersion: PlatformVersion
if usingXCTest, let xcTestMinimumDeploymentTarget = xcTestMinimumDeploymentTargets[platform] {
minimumSupportedVersion = xcTestMinimumDeploymentTarget
} else {
minimumSupportedVersion = platform.oldestSupportedVersion
}
let oldestSupportedVersion: PlatformVersion
if platform == .macCatalyst, let iOS = derivedPlatforms.first(where: { $0.platform == .iOS }) {
// If there was no deployment target specified for Mac Catalyst, fall back to the iOS deployment target.
oldestSupportedVersion = max(minimumSupportedVersion, iOS.version)
} else {
oldestSupportedVersion = minimumSupportedVersion
}
let supportedPlatform = SupportedPlatform(
platform: platform,
version: oldestSupportedVersion,
options: []
)
derivedPlatforms.append(supportedPlatform)
}
return SupportedPlatforms(
declared: declaredPlatforms.sorted(by: { $0.platform.name < $1.platform.name }),
derived: derivedPlatforms.sorted(by: { $0.platform.name < $1.platform.name })
)
}
// Track and override module aliases specified for targets in a package graph
private func resolveModuleAliases(packageBuilders: [ResolvedPackageBuilder],
observabilityScope: ObservabilityScope) throws -> Bool {
// If there are no module aliases specified, return early
let hasAliases = packageBuilders.contains { $0.package.targets.contains {
$0.dependencies.contains { dep in
if case let .product(prodRef, _) = dep {
return prodRef.moduleAliases != nil
}
return false
}
}
}
guard hasAliases else { return false }
let aliasTracker = ModuleAliasTracker()
for packageBuilder in packageBuilders {
try aliasTracker.addTargetAliases(targets: packageBuilder.package.targets,
package: packageBuilder.package.identity)
}
// Track targets that need module aliases for each package
for packageBuilder in packageBuilders {
for product in packageBuilder.package.products {
aliasTracker.trackTargetsPerProduct(product: product,
package: packageBuilder.package.identity)
}
}
// Override module aliases upstream if needed
aliasTracker.propagateAliases(observabilityScope: observabilityScope)
// Validate sources (Swift files only) for modules being aliased.
// Needs to be done after `propagateAliases` since aliases defined
// upstream can be overriden.
for packageBuilder in packageBuilders {
for product in packageBuilder.package.products {
try aliasTracker.validateAndApplyAliases(product: product,
package: packageBuilder.package.identity)
}
}
return true
}
/// A generic builder for `Resolved` models.
private class ResolvedBuilder<T> {
/// The constructed object, available after the first call to `construct()`.
private var _constructedObject: T?
/// Construct the object with the accumulated data.
///
/// Note that once the object is constructed, future calls to
/// this method will return the same object.
final func construct() throws -> T {
if let constructedObject = _constructedObject {
return constructedObject
}
let constructedObject = try self.constructImpl()
_constructedObject = constructedObject
return constructedObject
}
/// The object construction implementation.
func constructImpl() throws -> T {
fatalError("Should be implemented by subclasses")
}
}
/// Builder for resolved product.
private final class ResolvedProductBuilder: ResolvedBuilder<ResolvedProduct> {
/// The reference to its package.
unowned let packageBuilder: ResolvedPackageBuilder
/// The product reference.
let product: Product
/// The target builders in the product.
let targets: [ResolvedTargetBuilder]
init(product: Product, packageBuilder: ResolvedPackageBuilder, targets: [ResolvedTargetBuilder]) {
self.product = product
self.packageBuilder = packageBuilder
self.targets = targets
}
override func constructImpl() throws -> ResolvedProduct {
return ResolvedProduct(
product: product,
targets: try targets.map{ try $0.construct() }
)
}
}
/// Builder for resolved target.
private final class ResolvedTargetBuilder: ResolvedBuilder<ResolvedTarget> {
/// Enumeration to represent target dependencies.
enum Dependency {
/// Dependency to another target, with conditions.
case target(_ target: ResolvedTargetBuilder, conditions: [PackageConditionProtocol])
/// Dependency to a product, with conditions.
case product(_ product: ResolvedProductBuilder, conditions: [PackageConditionProtocol])
}
/// The target reference.
let target: Target
/// DiagnosticsEmitter with which to emit diagnostics
let diagnosticsEmitter: DiagnosticsEmitter
/// The target dependencies of this target.
var dependencies: [Dependency] = []
/// The defaultLocalization for this package
var defaultLocalization: String? = nil
/// The platforms supported by this package.
var platforms: SupportedPlatforms = .init(declared: [], derived: [])
init(
target: Target,
observabilityScope: ObservabilityScope
) {
self.target = target
self.diagnosticsEmitter = observabilityScope.makeDiagnosticsEmitter() {
var metadata = ObservabilityMetadata()
metadata.targetName = target.name
return metadata
}
}
func diagnoseInvalidUseOfUnsafeFlags(_ product: ResolvedProduct) throws {
// Diagnose if any target in this product uses an unsafe flag.
for target in try product.recursiveTargetDependencies() {
for (decl, assignments) in target.underlyingTarget.buildSettings.assignments {
let flags = assignments.flatMap(\.values)
if BuildSettings.Declaration.unsafeSettings.contains(decl) && !flags.isEmpty {
self.diagnosticsEmitter.emit(.productUsesUnsafeFlags(product: product.name, target: target.name))
break
}
}
}
}
override func constructImpl() throws -> ResolvedTarget {
let dependencies = try self.dependencies.map { dependency -> ResolvedTarget.Dependency in
switch dependency {
case .target(let targetBuilder, let conditions):
try self.target.validateDependency(target: targetBuilder.target)
return .target(try targetBuilder.construct(), conditions: conditions)
case .product(let productBuilder, let conditions):
try self.target.validateDependency(product: productBuilder.product, productPackage: productBuilder.packageBuilder.package.identity)
let product = try productBuilder.construct()
if !productBuilder.packageBuilder.isAllowedToVendUnsafeProducts {
try self.diagnoseInvalidUseOfUnsafeFlags(product)
}
return .product(product, conditions: conditions)
}
}
return ResolvedTarget(
target: self.target,
dependencies: dependencies,
defaultLocalization: self.defaultLocalization,
platforms: self.platforms
)
}
}
extension Target {
func validateDependency(target: Target) throws {
if self.type == .plugin && target.type == .library {
throw PackageGraphError.unsupportedPluginDependency(targetName: self.name, dependencyName: target.name, dependencyType: target.type.rawValue, dependencyPackage: nil)
}
}
func validateDependency(product: Product, productPackage: PackageIdentity) throws {
if self.type == .plugin && product.type.isLibrary {
throw PackageGraphError.unsupportedPluginDependency(targetName: self.name, dependencyName: product.name, dependencyType: product.type.description, dependencyPackage: productPackage.description)
}
}
}
/// Builder for resolved package.
private final class ResolvedPackageBuilder: ResolvedBuilder<ResolvedPackage> {
/// The package reference.
let package: Package
/// The product filter applied to the package.
let productFilter: ProductFilter
/// Package can vend unsafe products
let isAllowedToVendUnsafeProducts: Bool
/// Package can be overridden
let allowedToOverride: Bool
/// The targets in the package.
var targets: [ResolvedTargetBuilder] = []
/// The products in this package.
var products: [ResolvedProductBuilder] = []
/// The dependencies of this package.
var dependencies: [ResolvedPackageBuilder] = []
/// The defaultLocalization for this package.
var defaultLocalization: String? = nil
/// The platforms supported by this package.
var platforms: SupportedPlatforms = .init(declared: [], derived: [])
init(_ package: Package, productFilter: ProductFilter, isAllowedToVendUnsafeProducts: Bool, allowedToOverride: Bool) {
self.package = package
self.productFilter = productFilter
self.isAllowedToVendUnsafeProducts = isAllowedToVendUnsafeProducts
self.allowedToOverride = allowedToOverride
}
override func constructImpl() throws -> ResolvedPackage {
return ResolvedPackage(
package: self.package,
defaultLocalization: self.defaultLocalization,
platforms: self.platforms,
dependencies: try self.dependencies.map{ try $0.construct() },
targets: try self.targets.map{ try $0.construct() },
products: try self.products.map{ try $0.construct() }
)
}
}
/// Finds the first cycle encountered in a graph.
///
/// This is different from the one in tools support core, in that it handles equality separately from node traversal. Nodes traverse product filters, but only the manifests must be equal for there to be a cycle.
fileprivate func findCycle(
_ nodes: [GraphLoadingNode],
successors: (GraphLoadingNode) throws -> [GraphLoadingNode]
) rethrows -> (path: [Manifest], cycle: [Manifest])? {
// Ordered set to hold the current traversed path.
var path = OrderedCollections.OrderedSet<Manifest>()
var fullyVisitedManifests = Set<Manifest>()
// Function to visit nodes recursively.
// FIXME: Convert to stack.
func visit(
_ node: GraphLoadingNode,
_ successors: (GraphLoadingNode) throws -> [GraphLoadingNode]
) rethrows -> (path: [Manifest], cycle: [Manifest])? {
// Once all successors have been visited, this node cannot participate
// in a cycle.
if fullyVisitedManifests.contains(node.manifest) {
return nil
}
// If this node is already in the current path then we have found a cycle.
if !path.append(node.manifest).inserted {
let index = path.firstIndex(of: node.manifest)! // forced unwrap safe
return (Array(path[path.startIndex..<index]), Array(path[index..<path.endIndex]))
}
for succ in try successors(node) {
if let cycle = try visit(succ, successors) {
return cycle
}
}
// No cycle found for this node, remove it from the path.
let item = path.removeLast()
assert(item == node.manifest)
// Track fully visited nodes
fullyVisitedManifests.insert(node.manifest)
return nil
}
for node in nodes {
if let cycle = try visit(node, successors) {
return cycle
}
}
// Couldn't find any cycle in the graph.
return nil
}
| apache-2.0 | 11f43ebbe3f9b2dbd34ac615a23fc548 | 46.961415 | 342 | 0.650063 | 5.442471 | false | false | false | false |
pabloroca/PR2StudioSwift | Source/PRExtensions.swift | 1 | 2109 | //
// PRExtensions.swift
//
// Created by Pablo Roca Rozas on 3/2/16.
// Copyright © 2016 PR2Studio. All rights reserved.
//
import Foundation
import UIKit
extension String {
public func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.appendingPathComponent(path)
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
let newRed = CGFloat(red)/255
let newGreen = CGFloat(green)/255
let newBlue = CGFloat(blue)/255
self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
#if os(iOS)
extension UIScrollView {
open func scrollToBottom(animated: Bool) {
let rect = CGRect(x: 0, y: contentSize.height - bounds.size.height, width: bounds.size.width, height: bounds.size.height)
scrollRectToVisible(rect, animated: animated)
}
}
#endif
extension OperationQueue {
open func addOperationAfterLast(_ operation: Operation) {
if self.maxConcurrentOperationCount != 1 {
self.maxConcurrentOperationCount = 1
}
let lastOp = self.operations.last
if let lastOp = lastOp {
operation.addDependency(lastOp)
}
self.addOperation(operation)
}
}
extension Double {
public func toPriceString(decimalDigits: Int, currencySymbol: String, thousandsSeparator: String, decimalSeparator: String, symbolOnLeft: Bool = true, spaceBetweenAmountAndSymbol: Bool = false) -> String {
let numformat: NumberFormatter = NumberFormatter()
numformat.numberStyle = .decimal
numformat.alwaysShowsDecimalSeparator = false
numformat.decimalSeparator = decimalSeparator
numformat.minimumFractionDigits = 0
numformat.maximumFractionDigits = decimalDigits
let spacing = spaceBetweenAmountAndSymbol ? " " : ""
let number = NSNumber(value: self)
let numberFormatted = numformat.string(from: number) ?? ""
return symbolOnLeft ? currencySymbol+spacing+numberFormatted : numberFormatted+spacing+currencySymbol
}
}
| mit | 93940c579a8b5970ed30bd989924f837 | 30.462687 | 209 | 0.685484 | 4.419287 | false | false | false | false |
joearms/joearms.github.io | includes/swift/experiment7.swift | 1 | 1875 | // experiment3.swift
// run with:
// $ swift experiment3.swift
import Cocoa
func add_label_and_entry(
window: NSWindow,
x:CGFloat, y:CGFloat,
s: String) -> NSTextView {
let label = NSTextView(frame: NSMakeRect(x, y, 20, 20))
label.string = s
label.editable = false
label.backgroundColor = window.backgroundColor
label.selectable = false
window.contentView!.addSubview(label)
let entry = NSTextView(frame: NSMakeRect(x+30, y, 40, 20))
entry.editable = false
entry.selectable = false
window.contentView!.addSubview(entry)
return entry
}
class AppDelegate: NSObject, NSApplicationDelegate
{
@IBOutlet weak var t2: NSTextView!
let window = NSWindow()
@IBOutlet weak var t1 = add_label_and_entry(window, x:10.0, y:150.0, s:"A")
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:600, height:200))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 3"
t2 = add_label_and_entry(window, x:10.0, y:120.0, s:"B")
let button = NSButton(frame: NSMakeRect(10, 80, 180, 30))
button.bezelStyle = .ThickSquareBezelStyle
button.title = "Compute A+B"
button.target = self
button.action = "myAdder:"
window.contentView!.addSubview(button)
window.makeKeyAndOrderFront(window)
window.level = 1
}
@IBAction func myAction(sender: AnyObject) {
// NSLog("a=%d", t1)
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
| mit | 8c3b1b67c7f9c1fa00ff79f78cb04bdf | 22.734177 | 79 | 0.626667 | 4.157428 | false | false | false | false |
n8iveapps/N8iveKit | NetworkKit/NetworkKit/APIManager.swift | 1 | 2395 | //
// APIManager.swift
// N8NetworkKit
//
// Created by Muhammad Bassio on 8/29/17.
// Copyright © 2017 N8ive Apps. All rights reserved.
//
import Foundation
import N8CoreKit
import N8AuthKit
open class APIManager {
private(set) public var baseURL = ""
public var token = OAuth2Token()
public init() {
}
public init(baseURL:String) {
if baseURL.hasSuffix("/") {
self.baseURL = baseURL
}
else {
self.baseURL = "\(baseURL)/"
}
}
open func requestResult(for endPointPath:String, using httpMethod:HTTPMethod, parameters:Parameters, headers: HTTPHeaders, shouldAuthenticate:Bool, completion:@escaping (_ result:JSON, _ statusCode:Int, _ error:NKError?) -> Void) {
var headers = headers
let requestURL = "\(self.baseURL)endPointPath".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let requestCompletionHandler:((DataResponse<Any>) -> Void) = { response in
if let code = response.response?.statusCode {
do {
let jsonResponse = try JSON(data: response.data!)
//print("\(jsonResponse)")
if code != 200 {
completion(jsonResponse, code, nil)
}
else {
completion(JSON(["":""]), code, NKError(localizedTitle: "", localizedDescription: ""))
}
}
catch let creationError as NSError {
completion(JSON(["":""]), code, NKError(localizedTitle: "Invalid JSON data", localizedDescription: "\(creationError.localizedDescription)"))
}
}
else {
completion(JSON(["":""]), -1, NKError(localizedTitle: "Couldn't reach server", localizedDescription: "The specified server couldn't be reached, please make sure you have an active internet connection and the server is up and running"))
}
}
if shouldAuthenticate {
if let type = self.token.tokenType, let accToken = self.token.accessToken {
headers["Authorization"] = "\(type) \(accToken)"
}
else {
completion(JSON(["":""]), 401, NKError(localizedTitle: "Authentication needed", localizedDescription: "You need a valid access token to finish the specified request, please authenticate first"))
}
}
request(requestURL, method: httpMethod, parameters:parameters, headers: headers).responseJSON(completionHandler: requestCompletionHandler)
}
}
| mit | 0d5e2999f453077dbf300902d7cd3bb6 | 33.2 | 243 | 0.649123 | 4.684932 | false | false | false | false |
crspybits/SMSyncServer | iOS/SharedNotes/Code/SignInViewController.swift | 1 | 1910 | //
// SignInViewController.swift
// SharedNotes
//
// Created by Christopher Prince on 11/26/15.
// Copyright © 2015 Christopher Prince. All rights reserved.
//
import Foundation
import SMSyncServer
import UIKit
public class SignInViewController: SMGoogleUserSignInViewController {
let verticalDistanceBetweenButtons:CGFloat = 30
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.purpleColor()
SMSyncServerUser.session.signInProcessCompleted.addTarget!(self, withSelector: #selector(signInCompletionAction))
let googleSignIn = SMUserSignInManager.session.possibleAccounts[SMGoogleUserSignIn.displayNameS!] as! SMGoogleUserSignIn
let googleSignInButton = googleSignIn.signInButton(delegate: self)
googleSignInButton.frameOrigin = CGPoint(x: 50, y: 100)
self.view.addSubview(googleSignInButton)
let facebookSignIn = SMUserSignInManager.session.possibleAccounts[SMFacebookUserSignIn.displayNameS!] as! SMFacebookUserSignIn
let fbLoginButton = facebookSignIn.signInButton()
fbLoginButton.frameX = googleSignInButton.frameX
fbLoginButton.frameY = googleSignInButton.frameMaxY + verticalDistanceBetweenButtons
self.view.addSubview(fbLoginButton)
}
@objc private func signInCompletionAction(error:NSError?) {
if SMSyncServerUser.session.signedIn && error == nil {
print("SUCCESS signing in!")
self.navigationController?.popViewControllerAnimated(true)
}
else {
var message:String?
if error != nil {
message = "Error: \(error!)"
}
let alert = UIAlertView(title: "There was an error signing in. Please try again.", message: message, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
} | gpl-3.0 | af6b6fb22f62e96396c0712b93f348c8 | 37.979592 | 152 | 0.695128 | 4.894872 | false | false | false | false |
adamontherun/Study-iOS-With-Adam-Live | DragDropData/DragDropData/DogLoverViewController.swift | 1 | 1559 | //Some text.
import UIKit
class DogLoverViewController: UIViewController {
@IBOutlet weak var dogImageView: UIImageView!
@IBOutlet weak var maxBarkLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
maxBarkLabel.text = nil
let dropInteraction = UIDropInteraction(delegate: self)
view.addInteraction(dropInteraction)
}
}
extension DogLoverViewController: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: Dog.self)
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
return UIDropProposal(operation: .copy)
}
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
guard let item = session.items.first else { return }
let provider = item.itemProvider
provider.loadObject(ofClass: Dog.self) { (theDog, error) in
if let error = error {
print(error.localizedDescription)
} else {
DispatchQueue.main.async {
guard let dog = theDog as? Dog else { return }
self.dogImageView.image = dog.image
if let maxBarkVolume = dog.maxBarkVolume {
self.maxBarkLabel.text = "max is: \(maxBarkVolume)"
}
}
}
}
}
}
| mit | e8e22dfebfc6b22a33edfa9e7b896607 | 33.644444 | 119 | 0.623477 | 4.887147 | false | false | false | false |
slimane-swift/SessionMiddleware | Sources/DefaultSerializer.swift | 1 | 1172 | //
// DefaultSerializer.swift
// MIddleware
//
// Created by Yuki Takei on 4/16/16.
//
//
// Need to replace Foundation
import Foundation
extension String {
func splitBy(separator: Character, allowEmptySlices: Bool = false, maxSplit: Int) -> [String] {
return characters.split(separator: separator, maxSplits: maxSplit, omittingEmptySubsequences: allowEmptySlices).map { String($0) }
}
func splitBy(separator: Character, allowEmptySlices: Bool = false) -> [String] {
return characters.split(separator: separator, omittingEmptySubsequences: allowEmptySlices).map { String($0) }
}
}
public struct DefaultSerializer: SerializerType {
public init(){}
public func serialize(_ src: [String: String]) throws -> String {
return src.map({ k, v in "\(k)=\(v)" }).joined(separator: "&")
}
public func deserialize(_ src: String) throws -> [String: String] {
var dict: [String: String] = [:]
src.splitBy(separator: "&", maxSplit: 1).forEach { elem in
let splited = elem.splitBy(separator: "=", maxSplit: 1)
dict[splited[0]] = splited[1]
}
return dict
}
}
| mit | 568f2f01e70e89bbc01e8c88f02dc76d | 29.842105 | 138 | 0.638225 | 4.156028 | false | false | false | false |
Raureif/WikipediaKit | Sources/WikipediaSearchResults.swift | 1 | 1870 | //
// WikipediaSearchResults.swift
// WikipediaKit
//
// Created by Frank Rausch on 2016-07-25.
// Copyright © 2017 Raureif GmbH / Frank Rausch
//
// MIT License
//
// 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.
//
public class WikipediaSearchResults {
public var searchMethod = WikipediaSearchMethod.prefix
public var term: String
public var language: WikipediaLanguage
public var offset = 0
public var canLoadMore = true
public var suggestions = [String]()
public var items = [WikipediaArticlePreview]()
public var hasResults: Bool {
get {
return self.items.count > 0 ? true : false
}
}
public init(language: WikipediaLanguage, term: String) {
self.language = language
self.term = term
}
}
| mit | 9b16db6244d538f0d09d1fee99e3591b | 33.462963 | 80 | 0.703923 | 4.399527 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCapKit/Central/Service.swift | 1 | 3098 | //
// Service.swift
// BlueCap
//
// Created by Troy Stribling on 6/11/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import Foundation
import CoreBluetooth
public class Service : NSObject {
private let profile : ServiceProfile?
private var characteristicsDiscoveredPromise = Promise<[Characteristic]>()
internal let _peripheral : Peripheral
internal let cbService : CBService
internal var discoveredCharacteristics = Dictionary<CBUUID, Characteristic>()
public var name : String {
if let profile = self.profile {
return profile.name
} else {
return "Unknown"
}
}
public var uuid : CBUUID! {
return self.cbService.UUID
}
public var characteristics : [Characteristic] {
return self.discoveredCharacteristics.values.array
}
public var peripheral : Peripheral {
return self._peripheral
}
public func discoverAllCharacteristics() -> Future<[Characteristic]> {
Logger.debug("Service#discoverAllCharacteristics")
return self.discoverIfConnected(nil)
}
public func discoverCharacteristics(characteristics:[CBUUID]) -> Future<[Characteristic]> {
Logger.debug("Service#discoverCharacteristics")
return self.discoverIfConnected(characteristics)
}
private func discoverIfConnected(services:[CBUUID]!) -> Future<[Characteristic]> {
self.characteristicsDiscoveredPromise = Promise<[Characteristic]>()
if self.peripheral.state == .Connected {
self.peripheral.cbPeripheral.discoverCharacteristics(nil, forService:self.cbService)
} else {
self.characteristicsDiscoveredPromise.failure(BCError.peripheralDisconnected)
}
return self.characteristicsDiscoveredPromise.future
}
internal init(cbService:CBService, peripheral:Peripheral) {
self.cbService = cbService
self._peripheral = peripheral
self.profile = ProfileManager.sharedInstance.serviceProfiles[cbService.UUID]
}
internal func didDiscoverCharacteristics(error:NSError!) {
if let error = error {
self.characteristicsDiscoveredPromise.failure(error)
} else {
self.discoveredCharacteristics.removeAll()
if let cbCharacteristics = self.cbService.characteristics {
for cbCharacteristic : AnyObject in cbCharacteristics {
let bcCharacteristic = Characteristic(cbCharacteristic:cbCharacteristic as CBCharacteristic, service:self)
self.discoveredCharacteristics[bcCharacteristic.uuid] = bcCharacteristic
bcCharacteristic.didDiscover()
Logger.debug("Service#didDiscoverCharacteristics: uuid=\(bcCharacteristic.uuid.UUIDString), name=\(bcCharacteristic.name)")
}
self.characteristicsDiscoveredPromise.success(self.characteristics)
}
}
}
} | mit | cfc465116105bdec8d13380ce34b20f7 | 35.892857 | 143 | 0.653002 | 5.571942 | false | false | false | false |
johnnyoin/SwiftTools | SwiftTools/Sources/Color.swift | 1 | 1905 | //
// Color.swift
// SwiftTools
//
// Created by Jeremy Bouillanne on 16/09/16.
// Copyright © 2017 Jeremy Bouillanne. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init(hex: UInt32) {
let red = CGFloat((hex >> 16) & 0xff) / 255.0
let green = CGFloat((hex >> 8) & 0xff) / 255.0
let blue = CGFloat((hex ) & 0xff) / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1)
}
public func translucent(alpha: CGFloat = 0.5) -> UIColor {
return self.withAlphaComponent(alpha)
}
public func lighter() -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
if getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
return UIColor(hue: h,
saturation: s,
brightness: b * 1.2,
alpha: a)
}
return self
}
public func darker() -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
if getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
return UIColor(hue: h,
saturation: s,
brightness: b * 0.75,
alpha: a)
}
return self
}
public func convertedForNavBar() -> UIColor {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
// any R, G or B value under 40 will be negative once converted...
let convertedColors = [red, green, blue].map { convertedColor($0) }
// ...therefore capped to 0
return UIColor(red: convertedColors[0], green: convertedColors[1], blue: convertedColors[2], alpha: alpha)
}
private func convertedColor(_ channel: CGFloat) -> CGFloat {
return (channel * 255 - 40) / (1 - 40 / 255) / 255
}
}
| mit | 8750277d9045bbd5c7c9933d147d0914 | 26.594203 | 110 | 0.560399 | 3.619772 | false | false | false | false |
soapyigu/LeetCode_Swift | DFS/WordSearch.swift | 1 | 1824 | /**
* Question Link: https://leetcode.com/problems/word-search/
* Primary idea: Classic Depth-first Search, go up, down, left, right four directions
*
* Time Complexity: O(mn * 4^(k - 1)), m and n stand for width and height of matrix, k is the word size, Space Complexity: O(mn)
*
*/
class WordSearch {
func exist(board: [[Character]], _ word: String) -> Bool {
guard board.count > 0 && board[0].count > 0 else {
return false
}
let m = board.count
let n = board[0].count
var visited = Array(count: m, repeatedValue: Array(count: n, repeatedValue: false))
var wordContent = [Character](word.characters)
for i in 0..<m {
for j in 0..<n {
if board[i][j] == wordContent[0] && _dfs(board, wordContent, m, n, i, j, &visited, 0) {
return true
}
}
}
return false
}
private func _dfs(board: [[Character]], _ wordContent: [Character], _ m: Int, _ n: Int, _ i: Int, _ j: Int, inout _ visited: [[Bool]], _ index: Int) -> Bool {
if index == wordContent.count {
return true
}
guard i >= 0 && i < m && j >= 0 && j < n else {
return false
}
guard !visited[i][j] && board[i][j] == wordContent[index] else {
return false
}
visited[i][j] = true
if _dfs(board, wordContent, m, n, i + 1, j, &visited, index + 1) || _dfs(board, wordContent, m, n, i - 1, j, &visited, index + 1) || _dfs(board, wordContent, m, n, i, j + 1, &visited, index + 1) || _dfs(board, wordContent, m, n, i, j - 1, &visited, index + 1) {
return true
}
visited[i][j] = false
return false
}
} | mit | 1b07a208a7b3364702541a38524ef359 | 34.096154 | 269 | 0.501096 | 3.590551 | false | false | false | false |
kstaring/swift | test/expr/primary/literal/boolean.swift | 4 | 382 | // RUN: %target-parse-verify-swift
func boolLiterals() {
var b: Bool = false
b = true
_ = b
}
func defaultBoolLiterals() {
let b = false
var _: Bool = b
}
struct CustomBool : ExpressibleByBooleanLiteral {
let value: Bool
init(booleanLiteral value: Bool) {
self.value = value
}
}
func customBoolLiterals() {
var b: CustomBool = false
b = true
_ = b
}
| apache-2.0 | dd14ec41c7a2ed6ffa98e4d65fc3ec21 | 13.148148 | 49 | 0.636126 | 3.350877 | false | false | false | false |
saeta/penguin | Sources/PenguinTables/IndexSet.swift | 1 | 8411 | // 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.
/// PIndexSet represents a (non-strict) subset of indices of a column or table.
///
/// PIndexSet is used for masking and other operations on a `PTypedColumn`, a `PColumn`, and a
/// `PTable`. A `PIndexSet` is most often created via operations on the column types, such as
/// `PColumn`'s `nils` property, which returns a `PIndexSet` representing all the indices (rows)
/// containing nils.
///
/// To help catch errors, operations on `PIndexSet`s check to ensure they represent collections of
/// the same size. e.g. When a `PIndexSet` is used to select rows out of a `PTable`, the `count`
/// property of the `PIndexSet` is checked to ensure it is exactly equal to the `PTable`'s `count`
/// property.
///
/// `PIndexSet` supports both in-place and chaining set operations.
public struct PIndexSet: Equatable {
/// Initializes a `PIndexSet` given a set of indices.
///
/// - Parameter indices: The indices to include in the set.
/// - Parameter count: The number of rows this `PIndexSet` covers.
public init(indices: [Int], count: Int) {
self.impl = Array(repeating: false, count: count)
self.setCount = indices.count
for index in indices {
self.impl[index] = true
}
}
/// Initializes a `PIndexSet` where every index is set to `value`.
///
/// - Parameter value: Every index is included when `value` is true. If `value` is false, then
/// no indices are included.
/// - Parameter count: The number of rows in this `PIndexSet`.
public init(all value: Bool, count: Int) {
// TODO: Optimize internal representation!
self.impl = Array(repeating: value, count: count)
self.setCount = value ? count : 0
}
init(_ bitset: [Bool], setCount: Int) {
self.setCount = setCount
self.impl = bitset
}
init(empty dummy: Bool) {
self.init(all: false, count: 0)
}
/// Include all indices in `rhs` into `self`.
public mutating func union(_ rhs: PIndexSet, extending: Bool? = nil) throws {
if count != rhs.count {
if extending == nil || extending == false {
throw PError.indexSetMisMatch(
lhs: count, rhs: rhs.count, extendingAvailable: extending == nil)
}
self.impl.reserveCapacity(max(count, rhs.count))
}
let unionStop = min(count, rhs.count)
var newSetCount = 0
for i in 0..<unionStop {
let newValue = self.impl[i] || rhs.impl[i]
newSetCount += newValue.asInt
self.impl[i] = newValue
}
if count < rhs.count {
self.impl.append(contentsOf: rhs.impl[unionStop...])
for i in unionStop..<rhs.impl.count {
newSetCount += rhs.impl[i].asInt
}
} else {
for i in unionStop..<impl.count {
newSetCount += impl[i].asInt
}
}
self.setCount = newSetCount
}
/// Return a new `PIndexSet` that includes all indices from both `self` and `rhs`.
public func unioned(_ rhs: PIndexSet, extending: Bool? = nil) throws -> PIndexSet {
var copy = self
try copy.union(rhs, extending: extending)
return copy
}
/// Retain only indicies in both `self` and `rhs.
public mutating func intersect(_ rhs: PIndexSet, extending: Bool? = nil) throws {
if count != rhs.count {
if extending == nil || extending == false {
throw PError.indexSetMisMatch(
lhs: count, rhs: rhs.count, extendingAvailable: extending == nil)
}
self.impl.reserveCapacity(rhs.count)
}
let intersectionStop = min(count, rhs.count)
let newSize = max(count, rhs.count)
var newSetCount = 0
for i in 0..<intersectionStop {
let newValue = self.impl[i] && rhs.impl[i]
newSetCount += newValue.asInt
self.impl[i] = newValue
}
self.setCount = newSetCount
if count < rhs.count {
for _ in intersectionStop..<newSize {
self.impl.append(false)
}
} else {
for i in intersectionStop..<newSize {
self.impl[i] = false
}
}
}
/// Return a new `PIndexSet` that includes only indices in both `self` and `rhs`.
public func intersected(_ rhs: PIndexSet, extending: Bool? = nil) throws -> PIndexSet {
var copy = self
try copy.intersect(rhs, extending: extending)
return copy
}
/// Return a new `PIndexSet` where all indices included in `a` are excluded, and all excluded
/// in `a` are included.
public static prefix func ! (a: PIndexSet) -> PIndexSet {
let bitSet = a.count - a.setCount
if bitSet == 0 {
return PIndexSet(Array(repeating: false, count: a.count), setCount: 0)
}
if bitSet == a.count {
return PIndexSet(Array(repeating: false, count: a.count), setCount: a.count)
}
var newSet = [Bool]()
newSet.reserveCapacity(a.count)
for b in a.impl {
newSet.append(!b)
}
return PIndexSet(newSet, setCount: bitSet)
}
/// Total size of the collection represented by the `PIndexSet`.
///
/// Note: this should not be confused with the number of indices set within the `PIndexSet`.
public var count: Int {
impl.count
}
/// Returns `true` if there is at least one index included in this `PIndexSet`, false otherwise.
public var isEmpty: Bool {
setCount == 0
}
/// Returns true if the index `i` is included in the set, false otherwise.
subscript(i: Int) -> Bool {
get {
impl[i]
}
set {
impl[i] = newValue
}
}
/// Grows the `count` of `self` by 1, and includes the final index in the set iff `value`.
mutating func append(_ value: Bool) {
impl.append(value)
if value {
setCount += 1
}
}
/// Rearrange `self` such that `afterSelf[i] == beforeSelf[indices[i]]`.
mutating func gather(_ indices: [Int]) {
var newImpl = [Bool]()
newImpl.reserveCapacity(impl.count)
for index in indices {
newImpl.append(impl[index])
}
self.impl = newImpl
}
/// Rearrange `self` such that `afterSelf[i] == beforeSelf[indices[i]]`.
func gathering(_ indices: [Int]) -> Self {
var copy = self
copy.gather(indices)
return copy
}
/// Similar to `gathering`, except if `indices[i]` is `nil`, then the index is always included.
///
/// This behavior is helpful when using `PIndexSet` as a `nil`-set.
func gathering(_ indices: [Int?]) -> PIndexSet {
// TODO: Optimize me!
var setCount = 0
var output = [Bool]()
output.reserveCapacity(indices.count)
for index in indices {
if let index = index {
let isSet = impl[index]
if isSet {
setCount += 1
}
output.append(isSet)
} else {
setCount += 1
output.append(true)
}
}
return Self(output, setCount: setCount)
}
public private(set) var setCount: Int
var impl: [Bool] // TODO: support alternate representations.
}
extension PIndexSet {
func makeIterator() -> PIndexSetIterator<Array<Bool>.Iterator> {
PIndexSetIterator(underlying: impl.makeIterator())
}
func makeIndexIterator() -> PIndexSetIndexIterator {
PIndexSetIndexIterator(impl: impl)
}
}
// We don't want to make public key APIs on PIndexSet that would be required
// if we were to conform PIndexSet to the Collection protocol. So instead we
// implement our own iterator.
struct PIndexSetIterator<Underlying: IteratorProtocol>: IteratorProtocol
where Underlying.Element == Bool {
mutating func next() -> Bool? {
underlying.next()
}
var underlying: Underlying
}
struct PIndexSetIndexIterator: IteratorProtocol {
mutating func next() -> Int? {
while offset < impl.count {
if impl[offset] {
let index = offset
offset += 1
return index
}
offset += 1
}
return nil
}
let impl: [Bool]
var offset = 0
}
extension Bool {
var asInt: Int {
switch self {
case false:
return 0
case true:
return 1
}
}
}
| apache-2.0 | 0e7ccea0805549f7e6e50be5cb520b07 | 29.69708 | 98 | 0.643443 | 3.870686 | false | false | false | false |
alisidd/iOS-WeJ | Pods/M13Checkbox/Sources/M13Checkbox.swift | 1 | 17492 | //
// M13Checkbox.swift
// M13Checkbox
//
// Created by McQuilkin, Brandon on 2/23/16.
// Copyright © 2016 Brandon McQuilkin. 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 UIKit
/// A customizable checkbox control for iOS.
@IBDesignable
open class M13Checkbox: UIControl {
//----------------------------
// MARK: - Constants
//----------------------------
/**
The possible states the check can be in.
- Unchecked: No check is shown.
- Checked: A checkmark is shown.
- Mixed: A dash is shown.
*/
public enum CheckState: String {
/// No check is shown.
case unchecked = "Unchecked"
/// A checkmark is shown.
case checked = "Checked"
/// A dash is shown.
case mixed = "Mixed"
}
/**
The possible shapes of the box.
- Square: The box is square with optional rounded corners.
- Circle: The box is a circle.
*/
public enum BoxType: String {
/// The box is a circle.
case circle = "Circle"
/// The box is square with optional rounded corners.
case square = "Square"
}
/**
The possible shapes of the mark.
- Checkmark: The mark is a standard checkmark.
- Radio: The mark is a radio style fill.
*/
public enum MarkType: String {
/// The mark is a standard checkmark.
case checkmark = "Checkmark"
/// The mark is a radio style fill.
case radio = "Radio"
/// The mark is an add/remove icon set.
case addRemove = "AddRemove"
/// The mark is a disclosure indicator.
case disclosure = "Disclosure"
}
/**
The possible animations for switching to and from the unchecked state.
*/
public enum Animation: RawRepresentable, Hashable {
/// Animates the stroke of the box and the check as if they were drawn.
case stroke
/// Animates the checkbox with a bouncey fill effect.
case fill
/// Animates the check mark with a bouncy effect.
case bounce(AnimationStyle)
/// Animates the checkmark and fills the box with a bouncy effect.
case expand(AnimationStyle)
/// Morphs the checkmark from a line.
case flat(AnimationStyle)
/// Animates the box and check as if they were drawn in one continuous line.
case spiral
/// Fades checkmark in or out. (opacity).
case fade(AnimationStyle)
/// Start the box as a dot, and expand the box.
case dot(AnimationStyle)
public init?(rawValue: String) {
// Map the integer values to the animation types.
// This is only for interface builder support. I would like this to be removed eventually.
switch rawValue {
case "Stroke":
self = .stroke
case "Fill":
self = .fill
case "BounceStroke":
self = .bounce(.stroke)
case "BounceFill":
self = .bounce(.fill)
case "ExpandStroke":
self = .expand(.stroke)
case "ExpandFill":
self = .expand(.fill)
case "FlatStroke":
self = .flat(.stroke)
case "FlatFill":
self = .flat(.fill)
case "Spiral":
self = .spiral
case "FadeStroke":
self = .fade(.stroke)
case "FadeFill":
self = .fade(.fill)
case "DotStroke":
self = .dot(.stroke)
case "DotFill":
self = .dot(.fill)
default:
return nil
}
}
public var rawValue: String {
// Map the animation types to integer values.
// This is only for interface builder support. I would like this to be removed eventually.
switch self {
case .stroke:
return "Stroke"
case .fill:
return "Fill"
case let .bounce(style):
switch style {
case .stroke:
return "BounceStroke"
case .fill:
return "BounceFill"
}
case let .expand(style):
switch style {
case .stroke:
return "ExpandStroke"
case .fill:
return "ExpandFill"
}
case let .flat(style):
switch style {
case .stroke:
return "FlatStroke"
case .fill:
return "FlatFill"
}
case .spiral:
return "Spiral"
case let .fade(style):
switch style {
case .stroke:
return "FadeStroke"
case .fill:
return "FadeFill"
}
case let .dot(style):
switch style {
case .stroke:
return "DotStroke"
case .fill:
return "DotFill"
}
}
}
/// The manager for the specific animation type.
fileprivate var manager: M13CheckboxController {
switch self {
case .stroke:
return M13CheckboxStrokeController()
case .fill:
return M13CheckboxFillController()
case let .bounce(style):
return M13CheckboxBounceController(style: style)
case let .expand(style):
return M13CheckboxExpandController(style: style)
case let .flat(style):
return M13CheckboxFlatController(style: style)
case .spiral:
return M13CheckboxSpiralController()
case let .fade(style):
return M13CheckboxFadeController(style: style)
case let .dot(style):
return M13CheckboxDotController(style: style)
}
}
public var hashValue: Int {
return self.rawValue.hashValue
}
}
/**
The possible animation styles.
- Note: Not all animations support all styles.
*/
public enum AnimationStyle: String {
// The animation will focus on the stroke.
case stroke = "Stroke"
// The animation will focus on the fill.
case fill = "Fill"
}
//----------------------------
// MARK: - Properties
//----------------------------
/// The manager that manages display and animations of the checkbox.
/// The default animation is a stroke.
fileprivate var controller: M13CheckboxController = M13CheckboxStrokeController()
//----------------------------
// MARK: - Initalization
//----------------------------
override public init(frame: CGRect) {
super.init(frame: frame)
sharedSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedSetup()
}
/// The setup shared between initalizers.
fileprivate func sharedSetup() {
// Set up the inital state.
for aLayer in controller.layersToDisplay {
layer.addSublayer(aLayer)
}
controller.tintColor = tintColor
controller.resetLayersForState(DefaultValues.checkState)
let longPressGesture = M13CheckboxGestureRecognizer(target: self, action: #selector(M13Checkbox.handleLongPress(_:)))
addGestureRecognizer(longPressGesture)
}
//----------------------------
// MARK: - Values
//----------------------------
/// The object to return from `value` when the checkbox is checked.
open var checkedValue: Any?
/// The object to return from `value` when the checkbox is unchecked.
open var uncheckedValue: Any?
/// The object to return from `value` when the checkbox is mixed.
open var mixedValue: Any?
/**
Returns one of the three "value" properties depending on the checkbox state.
- returns: The value coresponding to the checkbox state.
- note: This is a convenience method so that if one has a large group of checkboxes, it is not necessary to write: if (someCheckbox == thatCheckbox) { if (someCheckbox.checkState == ...
*/
open var value: Any? {
switch checkState {
case .unchecked:
return uncheckedValue
case .checked:
return checkedValue
case .mixed:
return mixedValue
}
}
//----------------------------
// MARK: - State
//----------------------------
/// The current state of the checkbox.
open var checkState: CheckState {
get {
return controller.state
}
set {
setCheckState(newValue, animated: false)
}
}
/**
Change the check state.
- parameter checkState: The new state of the checkbox.
- parameter animated: Whether or not to animate the change.
*/
open func setCheckState(_ newState: CheckState, animated: Bool) {
if checkState == newState {
return
}
if animated {
if enableMorphing {
controller.animate(checkState, toState: newState)
} else {
controller.animate(checkState, toState: nil, completion: { [weak self] in
self?.controller.resetLayersForState(newState)
self?.controller.animate(nil, toState: newState)
})
}
} else {
controller.resetLayersForState(newState)
}
}
/**
Toggle the check state between unchecked and checked.
- parameter animated: Whether or not to animate the change. Defaults to false.
- note: If the checkbox is mixed, it will return to the unchecked state.
*/
open func toggleCheckState(_ animated: Bool = false) {
switch checkState {
case .checked:
setCheckState(.unchecked, animated: animated)
break
case .unchecked:
setCheckState(.checked, animated: animated)
break
case .mixed:
setCheckState(.unchecked, animated: animated)
break
}
}
//----------------------------
// MARK: - Animations
//----------------------------
/// The duration of the animation that occurs when the checkbox switches states. The default is 0.3 seconds.
@IBInspectable open var animationDuration: TimeInterval {
get {
return controller.animationGenerator.animationDuration
}
set {
controller.animationGenerator.animationDuration = newValue
}
}
/// The type of animation to preform when changing from the unchecked state to any other state.
open var stateChangeAnimation: Animation = DefaultValues.animation {
didSet {
// Remove the sublayers
if let layers = layer.sublayers {
for sublayer in layers {
sublayer.removeAllAnimations()
sublayer.removeFromSuperlayer()
}
}
// Set the manager
let newManager = stateChangeAnimation.manager
newManager.tintColor = tintColor
newManager.secondaryTintColor = secondaryTintColor
newManager.secondaryCheckmarkTintColor = secondaryCheckmarkTintColor
newManager.hideBox = hideBox
newManager.pathGenerator = controller.pathGenerator
newManager.animationGenerator.animationDuration = controller.animationGenerator.animationDuration
newManager.state = controller.state
newManager.enableMorphing = controller.enableMorphing
newManager.setMarkType(type: controller.markType, animated: false)
// Set up the inital state.
for aLayer in newManager.layersToDisplay {
layer.addSublayer(aLayer)
}
// Layout and reset
newManager.resetLayersForState(checkState)
controller = newManager
}
}
/// Whether or not to enable morphing between states.
@IBInspectable open var enableMorphing: Bool {
get {
return controller.enableMorphing
}
set {
controller.enableMorphing = newValue
}
}
//----------------------------
// MARK: - UIControl
//----------------------------
@objc func handleLongPress(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began || sender.state == .changed {
isSelected = true
} else {
isSelected = false
if sender.state == .ended {
toggleCheckState(true)
sendActions(for: .valueChanged)
}
}
}
//----------------------------
// MARK: - Appearance
//----------------------------
/// The color of the checkbox's tint color when not in the unselected state. The tint color is is the main color used when not in the unselected state.
@IBInspectable open var secondaryTintColor: UIColor? {
get {
return controller.secondaryTintColor
}
set {
controller.secondaryTintColor = newValue
}
}
/// The color of the checkmark when it is displayed against a filled background.
@IBInspectable open var secondaryCheckmarkTintColor: UIColor? {
get {
return controller.secondaryCheckmarkTintColor
}
set {
controller.secondaryCheckmarkTintColor = newValue
}
}
/// The stroke width of the checkmark.
@IBInspectable open var checkmarkLineWidth: CGFloat {
get {
return controller.pathGenerator.checkmarkLineWidth
}
set {
controller.pathGenerator.checkmarkLineWidth = newValue
controller.resetLayersForState(checkState)
}
}
/// The type of mark to display.
open var markType: MarkType {
get {
return controller.markType
}
set {
controller.markType = newValue
setNeedsLayout()
}
}
/// Set the mark type with the option of animating the change.
open func setMarkType(markType: MarkType, animated: Bool) {
controller.setMarkType(type: markType, animated: animated)
}
/// The stroke width of the box.
@IBInspectable open var boxLineWidth: CGFloat {
get {
return controller.pathGenerator.boxLineWidth
}
set {
controller.pathGenerator.boxLineWidth = newValue
controller.resetLayersForState(checkState)
}
}
/// The corner radius of the box if the box type is square.
@IBInspectable open var cornerRadius: CGFloat {
get {
return controller.pathGenerator.cornerRadius
}
set {
controller.pathGenerator.cornerRadius = newValue
setNeedsLayout()
}
}
/// The shape of the checkbox.
open var boxType: BoxType {
get {
return controller.pathGenerator.boxType
}
set {
controller.pathGenerator.boxType = newValue
setNeedsLayout()
}
}
/// Wether or not to hide the checkbox.
@IBInspectable open var hideBox: Bool {
get {
return controller.hideBox
}
set {
controller.hideBox = newValue
}
}
open override func tintColorDidChange() {
super.tintColorDidChange()
controller.tintColor = tintColor
}
//----------------------------
// MARK: - Layout
//----------------------------
open override func layoutSubviews() {
super.layoutSubviews()
// Update size
controller.pathGenerator.size = min(frame.size.width, frame.size.height)
// Layout
controller.layoutLayers()
}
}
| gpl-3.0 | d977b29d3e2ff10720108ab64d8633a2 | 32.636538 | 464 | 0.550455 | 5.337504 | false | false | false | false |
yangligeryang/codepath | assignments/TumblrDemo/TumblrDemo/SearchViewController.swift | 1 | 1458 | //
// SearchViewController.swift
// TumblrDemo
//
// Created by Yang Yang on 11/6/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import UIKit
class SearchViewController: UIViewController {
@IBOutlet weak var loadingImageView: UIImageView!
@IBOutlet weak var feedImageView: UIImageView!
var loading1: UIImage!
var loading2: UIImage!
var loading3: UIImage!
var images: [UIImage]!
var animatedImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
loading1 = UIImage(named: "loading-1")
loading2 = UIImage(named: "loading-2")
loading3 = UIImage(named: "loading-3")
images = [loading1, loading2, loading3]
animatedImage = UIImage.animatedImage(with: images, duration: 0.8)
loadingImageView.image = animatedImage
}
override func viewDidAppear(_ animated: Bool) {
delay(0.6, closure: {
UIView.animate(withDuration: 1, animations: {
self.loadingImageView.alpha = 0
}, completion: { (Bool) in
UIView.animate(withDuration: 0.6, animations: {
self.feedImageView.alpha = 1
})
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 6a43e62aadaa077a09a3056f12273cc1 | 25.017857 | 74 | 0.586136 | 4.761438 | false | false | false | false |
Obisoft2017/BeautyTeamiOS | BeautyTeam/BeautyTeam/ObiLoginVC.swift | 1 | 8247 | //
// ObiLoginVC.swift
// BeautyTeam
//
// Created by Carl Lee on 4/20/16.
// Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved.
//
import UIKit
import Alamofire
import KeychainSwift
class ObiLoginVC: UITableViewController {
var userNameCell: InputTableViewCell!
var passwordCell: InputTableViewCell!
var rememberMeCell: UITableViewCell!
var loginCell: UITableViewCell!
var loginIndicate: UIActivityIndicatorView = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.registerClass(InputTableViewCell.self, forCellReuseIdentifier: "inputcell")
self.userNameCell = InputTableViewCell(name: "User name", reuseIdentifier: "inputcell")
self.passwordCell = InputTableViewCell(name: "Password", isPassword: true, reuseIdentifier: "inputcell")
self.rememberMeCell = UITableViewCell(style: .Default, reuseIdentifier: nil)
self.rememberMeCell.textLabel?.text = "Remember me"
self.rememberMeCell.accessoryType = .Checkmark
self.loginCell = UITableViewCell(style: .Default, reuseIdentifier: nil)
self.loginCell.textLabel?.text = "Sign in"
self.navigationItem.title = "Sign in"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.loginIndicate)
self.loginIndicate.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 5 = User name + password + remember me + Login
switch section {
case 0:
return 2
case 1:
return 1
case 2:
return 1
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
return self.userNameCell
case 1:
return self.passwordCell
default:
break
}
case 1:
switch indexPath.row {
case 0:
return self.rememberMeCell
default:
break
}
case 2:
switch indexPath.row {
case 0:
return self.loginCell
default:
break
}
default:
break
}
return UITableViewCell()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 1 {
if self.rememberMeCell.accessoryType == .None {
self.rememberMeCell.accessoryType = .Checkmark
} else {
self.rememberMeCell.accessoryType = .None
}
}
if indexPath.section == 2 {
self.loginIndicate.startAnimating()
self.login()
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func login() {
// Validate the username & password.
guard let username = self.userNameCell.inputContent?.text else {
let userNameMissingAlert: UIAlertView = UIAlertView(title: "Missing Data", message: "Please input your user name.", delegate: nil, cancelButtonTitle: "OK")
userNameMissingAlert.show()
return
}
guard let password = self.passwordCell.inputContent?.text else {
let passwordMissingAlert = UIAlertView(title: "Missing Data", message: "Please input your password.", delegate: nil, cancelButtonTitle: "OK")
passwordMissingAlert.show()
return
}
var rememberMe = false
if self.rememberMeCell.accessoryType == .Checkmark {
rememberMe = true
}
Alamofire.request(.POST, ObiBeautyTeam.APIURL + "/", parameters: [
"Username": username,
"Password": password,
"RememberMe": rememberMe.description
]).responseJSON {
response in
guard let rawData = response.result.value as? [String : AnyObject?] else {
UIAlertView(title: "Sign in Failed", message: "Please check your network.", delegate: nil, cancelButtonTitle: "OK").show()
return
}
let data = ObiValue<String>(rawData: rawData)
// Error Handling
if data.statusCode != 200 {
switch data.statusCode {
case 403:
UIAlertView(title: "Sign in Failed", message: "The account is locked out or log in failure.", delegate: nil, cancelButtonTitle: "OK").show()
case 302:
UIAlertView(title: "Sign in Failed", message: "The account Requires Verification.", delegate: nil, cancelButtonTitle: "OK").show()
default:
UIAlertView(title: "Sign in Failed", message: "\(data.statusCode) Unknown Error.\nThe error will be logged to Obisoft.", delegate: nil, cancelButtonTitle: "OK").show()
ObiBeautyTeam.logError("\(data.statusCode) in login")
}
return
}
// If login succeed
// Store Password
let keychain = KeychainSwift()
keychain.set(username, forKey: "obiUserName")
keychain.set(password, forKey: "obiPassword")
self.navigationController?.pushViewController(UIViewController(), animated: true)
}
}
}
| apache-2.0 | 04e4a62f62601323eaf0a33936d3a1f9 | 37 | 191 | 0.604293 | 5.501001 | false | false | false | false |
SwiftKitz/Storez | Sources/Storez/Stores/Cache/CacheSupportedType.swift | 1 | 1213 | //
// CacheSupportedType.swift
// Storez
//
// Created by Mazyad Alabduljaleel on 12/8/15.
// Copyright © 2015 mazy. All rights reserved.
//
/** NSCache only requires objects to conform to AnyObject
*/
public typealias CacheSupportedType = AnyObject
struct CacheSupportedBox <T: CacheSupportedType>: CacheTransaction {
let value: T
var supportedType: AnyObject? {
// FIXME: Compiler crash
let anyObject: AnyObject? = value
return anyObject
}
init?(storedValue: AnyObject?) {
guard let value = storedValue as? T else {
return nil
}
self.value = value
}
init(_ value: T) {
self.value = value
}
}
struct CacheNullableSupportedBox<T: Nullable>: CacheTransaction where T.UnderlyingType: CacheSupportedType {
let value: T
var supportedType: AnyObject? {
return value.wrappedValue
}
init?(storedValue: AnyObject?) {
guard let value = storedValue as? T.UnderlyingType else {
return nil
}
self.value = T(value)
}
init(_ value: T) {
self.value = value
}
}
| mit | baf4611cfa8320c72891ee2ed49d79a6 | 19.2 | 108 | 0.583333 | 4.643678 | false | false | false | false |
KyoheiG3/SimpleAlert | SimpleAlert/AlertContentView.swift | 1 | 2357 | //
// AlertContentView.swift
// SimpleAlert
//
// Created by Kyohei Ito on 2016/09/12.
// Copyright © 2016年 kyohei_ito. All rights reserved.
//
import UIKit
open class AlertContentView: UIView {
@IBOutlet public private(set) weak var contentStackView: UIStackView!
@IBOutlet public private(set) weak var titleLabel: UILabel!
@IBOutlet public private(set) weak var messageLabel: UILabel!
@IBOutlet public private(set) weak var textBackgroundView: UIView!
@IBOutlet private weak var textFieldView: UIView!
@IBOutlet private weak var textFieldStackView: UIStackView!
var textFields: [UITextField] {
return textFieldStackView?.arrangedSubviews.compactMap { $0 as? UITextField } ?? []
}
open override func layoutSubviews() {
super.layoutSubviews()
titleLabel.isHidden = titleLabel.text?.isEmpty ?? true
messageLabel.isHidden = messageLabel.text?.isEmpty ?? true
textFieldView.isHidden = textFields.isEmpty
contentStackView.arrangedSubviews[0].isHidden = titleLabel.isHidden && messageLabel.isHidden && textFieldView.isHidden
isHidden = contentStackView.arrangedSubviews.allSatisfy(\.isHidden)
superview?.isHidden = isHidden
}
func append(_ textField: UITextField) {
textFieldStackView.addArrangedSubview(textField)
}
func removeAllTextField() {
textFieldStackView.removeAllArrangedSubviews()
}
public override init(frame: CGRect) {
super.init(frame: frame)
loadNibContent()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadNibContent()
}
private func loadNibContent() {
let type = AlertContentView.self
let nib = UINib(nibName: String(describing: type), bundle: Bundle(for: type))
if let view = nib.instantiate(withOwner: self, options: nil).first as? UIView {
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: topAnchor),
view.leftAnchor.constraint(equalTo: leftAnchor),
view.rightAnchor.constraint(equalTo: rightAnchor),
view.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
}
| mit | 1c5b0dc4de888c4b4ffd462ffd4bf46c | 34.666667 | 126 | 0.67757 | 5.117391 | false | false | false | false |
MukeshKumarS/Swift | test/attr/attr_warn_unused_result.swift | 1 | 5120 | // RUN: %target-parse-verify-swift
// ---------------------------------------------------------------------------
// Warnings about unused results
// ---------------------------------------------------------------------------
@warn_unused_result func f1() -> [Int] { }
func testFuncsNegative() {
let x = f1()
_ = f1()
_ = f1()
for _ in f1() { }
_ = x
}
func testFuncsPositive() {
f1() // expected-warning{{result of call to 'f1()' is unused}}
let _: () -> Void = { f1() } // expected-warning{{result of call to 'f1()' is unused}}
let _: () -> Void = { _ = f1() } // okay
let _: () -> Void = { testFuncsPositive() } // okay
}
class C1 {
@warn_unused_result
func f1() { }
@warn_unused_result(message="huzzah")
static func f2() { }
@warn_unused_result
func curried1()()() { } // expected-warning {{curried function declaration syntax will be removed in a future version of Swift}}
}
func testMethodsNegative(c1: C1) {
c1.f1 // expected-error{{expression resolves to an unused function}}
c1.curried1() // expected-error{{expression resolves to an unused function}}
c1.curried1()() // expected-error{{expression resolves to an unused function}}
}
func testMethodsPositive(c1: C1) {
c1.f1() // expected-warning{{result of call to 'f1()' is unused}}
C1.f2() // expected-warning{{result of call to 'f2()' is unused: huzzah}}
c1.curried1()()() // expected-warning{{result of call to 'curried1()' is unused}}
}
struct Inits1 {
@warn_unused_result init() { }
}
func testInitsPositive() {
_ = Inits1()
Inits1() // expected-warning{{result of call to 'init()' is unused}}
}
// ---------------------------------------------------------------------------
// Warnings about unused results with mutating versions
// ---------------------------------------------------------------------------
struct Mutating1 {
@warn_unused_result(mutable_variant="fooInPlace")
func foo() -> Mutating1 { return self }
mutating func fooInPlace() { }
@warn_unused_result(message="zug zug", mutable_variant="barInPlace")
func bar(x: Int, y: Int) -> Mutating1 { return self }
mutating func barInPlace(x: Int, y: Int) { }
}
func testMutating1(m1: Mutating1, m2: Mutating1) {
var m2 = m2
m1.foo() // expected-warning{{result of call to 'foo()' is unused}}
m2.foo() // expected-warning{{result of call to non-mutating function 'foo()' is unused; use 'fooInPlace()' to mutate in-place}}{{6-9=fooInPlace}}
m1.bar(1, y: 1) // expected-warning{{result of call to 'bar(_:y:)' is unused: zug zug}}
m2.bar(1, y: 1) // expected-warning{{result of call to non-mutating function 'bar(_:y:)' is unused; use 'barInPlace(_:y:)' to mutate in-place}}{{6-9=barInPlace}}
m2 = m1
}
// ---------------------------------------------------------------------------
// Checking of the warn_unused_attribute itself
// ---------------------------------------------------------------------------
struct BadAttributes1 {
@warn_unused_result(blarg) func f1() { } // expected-warning{{unknown parameter 'blarg' in 'warn_unused_result' attribute}}
@warn_unused_result(wibble="foo") func f2() { } // expected-warning{{unknown parameter 'wibble' in 'warn_unused_result' attribute}}
@warn_unused_result(message) func f3() { } // expected-error{{expected '=' following 'message' parameter}}
@warn_unused_result(message=) func f4() { } // expected-error{{'=' must have consistent whitespace on both sides}}
// expected-error@-1{{expected a string following '=' for 'message' parameter}}
@warn_unused_result(message=blah) func f5() { } // expected-error{{expected a string following '=' for 'message' parameter}}
@warn_unused_result(mutable_variant="oops") static func f6() { } // expected-error{{'mutable_variant' parameter of 'warn_unused_result' attribute does not make sense on a non-instance method}}
@warn_unused_result(mutable_variant="oops") init() { } // expected-error{{'mutable_variant' parameter of 'warn_unused_result' attribute does not make sense on a non-function}}
@warn_unused_result(mutable_variant="oops") mutating func f7() { } // expected-error{{'mutable_variant' parameter of 'warn_unused_result' attribute does not make sense on a mutating method}}
}
class BadAttributes2 {
@warn_unused_result(mutable_variant="oops") func f1() { } // expected-error{{'mutable_variant' parameter of 'warn_unused_result' attribute does not make sense on a method of a class}}
}
@warn_unused_result(mutable_variant="oops") func badMutableVariant() { } // expected-error{{'mutable_variant' parameter of 'warn_unused_result' attribute does not make sense on a non-method}}
// ---------------------------------------------------------------------------
// @warn_unused_result should work on operators as well
// ---------------------------------------------------------------------------
struct S : Equatable {}
@warn_unused_result
func == (lhs: S, rhs: S) -> Bool { return true }
func testUnusedOperators() {
// rdar://18904720
S() == S() // expected-warning {{result of call to '==' is unused}}
S() != S() // expected-warning {{result of call to '!=' is unused}}
}
| apache-2.0 | cef55acb9169e672446537a64030b442 | 42.02521 | 194 | 0.592578 | 3.806691 | false | true | false | false |
xeo-it/DeserializableSwiftGenerator | DeserializableSwiftGenerator/ObjectMapperGenerator.swift | 1 | 1553 | //
// ObjectMapperGenerator.swift
// DeserializableSwiftGenerator
//
// Created by Cem Olcay on 25/12/14.
// Copyright (c) 2014 Cem Olcay. All rights reserved.
//
import Cocoa
final class ObjectMapperGenerator: SWGenerator {
// MARK: SWGeneratorProtocol
override var deserialzeProtocolName: String? {
return "Object,Mappable"
}
override func generateClassBody(sw: SWClass) -> String {
var body = generateInit(sw)
body += "\n"
body += generateMap(sw)
return body
}
// MARK: ObjectMapper Generator
func generateInit(sw: SWClass) -> String {
var initMethod = "\n\t// MARK: Mappable\n\n\t"
initMethod += sw.superName == nil ? "" : "override "
initMethod += "required convenience init?(_ map: Map) {\n"
initMethod += "\t\tself.init()\n"
initMethod += "\t}\n"
return initMethod
}
func generateMap (sw: SWClass) -> String {
var map = ""
if sw.superName != nil {
map = "\toverride func mapping(map: Map) {\n"
map += "\t\tsuper.mapping(map)\n"
} else {
map = "\tfunc mapping(map: Map) {\n"
}
if let p = sw.properties {
for prop in p {
map += "\t\t" +
prop.name +
" <- " +
"map[\"" +
prop.name +
"\"]\n"
}
}
map += "\t}\n"
return map
}
}
| mit | b75fb29aa0e659f7a7e5684e73519565 | 25.322034 | 66 | 0.484868 | 4.208672 | false | false | false | false |
bwhiteley/PSOperations | PSOperations/CloudCondition.swift | 3 | 3149 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
import CloudKit
/// A condition describing that the operation requires access to a specific CloudKit container.
public struct CloudContainerCondition: OperationCondition {
public static let name = "CloudContainer"
static let containerKey = "CKContainer"
/*
CloudKit has no problem handling multiple operations at the same time
so we will allow operations that use CloudKit to be concurrent with each
other.
*/
public static let isMutuallyExclusive = false
let container: CKContainer // this is the container to which you need access.
let permission: CKApplicationPermissions
/**
- parameter container: the `CKContainer` to which you need access.
- parameter permission: the `CKApplicationPermissions` you need for the
container. This parameter has a default value of `[]`, which would get
you anonymized read/write access.
*/
public init(container: CKContainer, permission: CKApplicationPermissions = []) {
self.container = container
self.permission = permission
}
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return CloudKitPermissionOperation(container: container, permission: permission)
}
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
container.verifyPermission(permission, requestingIfNecessary: false) { error in
if let error = error {
let conditionError = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: self.dynamicType.name,
self.dynamicType.containerKey: self.container,
NSUnderlyingErrorKey: error
])
completion(.Failed(conditionError))
}
else {
completion(.Satisfied)
}
}
}
}
/**
This operation asks the user for permission to use CloudKit, if necessary.
If permission has already been granted, this operation will quickly finish.
*/
class CloudKitPermissionOperation: Operation {
let container: CKContainer
let permission: CKApplicationPermissions
init(container: CKContainer, permission: CKApplicationPermissions) {
self.container = container
self.permission = permission
super.init()
if permission != [] {
/*
Requesting non-zero permissions means that this potentially presents
an alert, so it should not run at the same time as anything else
that presents an alert.
*/
addCondition(AlertPresentation())
}
}
override func execute() {
container.verifyPermission(permission, requestingIfNecessary: true) { error in
self.finishWithError(error)
}
}
}
| mit | df47058d3b9c79fafc2531510a402cfc | 33.966667 | 106 | 0.654592 | 5.619643 | false | false | false | false |
phatblat/octokit.swift | OctoKit/Milestone.swift | 1 | 1667 | import Foundation
@objc public class Milestone: NSObject {
public var url: URL?
public var htmlURL: URL?
public var labelsURL: URL?
public var id: Int
public var number: Int?
public var state: Openness?
public var title: String?
public var milestoneDescription: String?
public var creator: User?
public var openIssues: Int?
public var closedIssues: Int?
public var createdAt: Date?
public var updatedAt: Date?
public var closedAt: Date?
public var dueOn: Date?
public init?(_ json: [String: AnyObject]) {
if let id = json["id"] as? Int {
if let urlString = json["html_url"] as? String, let url = URL(string: urlString) {
htmlURL = url
}
if let urlString = json["labels_url"] as? String, let url = URL(string: urlString) {
labelsURL = url
}
self.id = id
number = json["number"] as? Int
state = Openness(rawValue: json["state"] as? String ?? "")
title = json["title"] as? String
milestoneDescription = json["description"] as? String
creator = User(json["creator"] as? [String: AnyObject] ?? [:])
openIssues = json["open_issues"] as? Int
closedIssues = json["closed_issues"] as? Int
createdAt = Time.rfc3339Date(json["created_at"] as? String)
updatedAt = Time.rfc3339Date(json["updated_at"] as? String)
closedAt = Time.rfc3339Date(json["closed_at"] as? String)
dueOn = Time.rfc3339Date(json["due_on"] as? String)
} else {
id = -1
}
}
}
| mit | 90fdd1f26ea3cb8fe453479f9594c9b3 | 36.886364 | 96 | 0.573485 | 4.136476 | false | false | false | false |
benlangmuir/swift | test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-class-1argument-1distinct_use.swift | 14 | 3035 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9NamespaceC5ValueOySS_SiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceC5ValueOySS_SiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main9NamespaceC5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSSN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
final class Namespace<Arg> {
enum Value<First> {
case first(First)
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main9NamespaceC5ValueOySS_SiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Namespace<String>.Value.first(13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE_1]],
// CHECK-SAME: i8* [[ERASED_TYPE_2]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main9NamespaceC5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 6f2048eed45d93f092ba8784585e27dc | 37.417722 | 157 | 0.595717 | 3.013903 | false | false | false | false |
marcelganczak/swift-js-transpiler | test/weheartswift/conditionals-6.swift | 1 | 216 | let year = 2014
if year % 4 == 0 {
if year % 100 == 0 && year % 400 != 0 {
print("Not a leap year!")
} else {
print("Leap year!")
}
} else {
print(year)
print("Not a leap year!")
} | mit | c846b4d7a7434b2aebba434bcb317871 | 18.727273 | 43 | 0.467593 | 3.272727 | false | false | false | false |
tbointeractive/bytes | Example/bytesTests/Specs/Int+RandomSpec.swift | 1 | 1122 | //
// Int+RandomSpec.swift
// bytes
//
// Created by Thorsten Stark on 23.12.16.
// Copyright © 2016 TBO INTERACTIVE GmbH & Co. KG. All rights reserved.
//
import bytes
import Quick
import Nimble
class IntRandomSpec: QuickSpec {
override func spec() {
describe("randomInRange") {
it ("should return an integer value inside the given range") {
let range:Range = 5 ..< 10
let randomInt = Int.random(in: range)
expect(range.contains(randomInt)).to(beTrue())
}
it ("should return allwas the same value when range has length of one") {
let range:Range = 2 ..< 3
for _ in 1 ..< 100 {
let randomInt = Int.random(in: range)
expect(randomInt) == 2
}
}
it ("should return 0 if the range is empty") {
let range:Range = 1..<1
let randomInt = Int.random(in: range)
expect(range.isEmpty).to(beTrue())
expect(randomInt) == 0
}
}
}
}
| mit | fc58785395ac1eddc950949660036342 | 29.297297 | 85 | 0.508475 | 4.378906 | false | false | false | false |
bindlechat/ZenText | ZenText/Classes/Regex.swift | 1 | 1307 | public class Regex {
public class func findTokens(_ regex: String, text: String) -> [String]? {
if let ranges = findTokenRanges(regex, text: text) {
var results = [String]()
for range in ranges {
results.append((text as NSString).substring(with: range))
}
return results
}
return nil
}
// This method supports one capture group. If you use more than one, it will return the last range of each match.
public class func findTokenRanges(_ regex: String, text: String) -> [NSRange]? {
do {
var ranges: [NSRange]?
let regularExpression = try NSRegularExpression(pattern: regex, options: NSRegularExpression.Options(rawValue: 0))
let range = NSRange(location: 0, length: text.count)
let matches = regularExpression.matches(in: text, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range)
if matches.count > 0 {
ranges = [NSRange]()
for match in matches {
ranges!.append(match.range(at: match.numberOfRanges-1))
}
return ranges
}
return nil
} catch {
return nil
}
}
}
| mit | e5be1de3a0c80c217a844a3a7b092eef | 38.606061 | 134 | 0.557001 | 5.046332 | false | false | false | false |
apple/swift-system | Tests/SystemTests/FileTypesTest.swift | 1 | 3230 | /*
This source file is part of the Swift System open source project
Copyright (c) 2020 - 2021 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
import XCTest
#if SYSTEM_PACKAGE
import SystemPackage
#else
import System
#endif
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
final class FileDescriptorTest: XCTestCase {
func testStandardDescriptors() {
XCTAssertEqual(FileDescriptor.standardInput.rawValue, 0)
XCTAssertEqual(FileDescriptor.standardOutput.rawValue, 1)
XCTAssertEqual(FileDescriptor.standardError.rawValue, 2)
}
// Test the constants match the C header values. For various reasons,
func testConstants() {
XCTAssertEqual(O_RDONLY, FileDescriptor.AccessMode.readOnly.rawValue)
XCTAssertEqual(O_WRONLY, FileDescriptor.AccessMode.writeOnly.rawValue)
XCTAssertEqual(O_RDWR, FileDescriptor.AccessMode.readWrite.rawValue)
#if !os(Windows)
XCTAssertEqual(O_NONBLOCK, FileDescriptor.OpenOptions.nonBlocking.rawValue)
#endif
XCTAssertEqual(O_APPEND, FileDescriptor.OpenOptions.append.rawValue)
XCTAssertEqual(O_CREAT, FileDescriptor.OpenOptions.create.rawValue)
XCTAssertEqual(O_TRUNC, FileDescriptor.OpenOptions.truncate.rawValue)
XCTAssertEqual(O_EXCL, FileDescriptor.OpenOptions.exclusiveCreate.rawValue)
#if !os(Windows)
XCTAssertEqual(O_NOFOLLOW, FileDescriptor.OpenOptions.noFollow.rawValue)
XCTAssertEqual(O_CLOEXEC, FileDescriptor.OpenOptions.closeOnExec.rawValue)
#endif
// BSD only
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssertEqual(O_SHLOCK, FileDescriptor.OpenOptions.sharedLock.rawValue)
XCTAssertEqual(O_EXLOCK, FileDescriptor.OpenOptions.exclusiveLock.rawValue)
XCTAssertEqual(O_SYMLINK, FileDescriptor.OpenOptions.symlink.rawValue)
XCTAssertEqual(O_EVTONLY, FileDescriptor.OpenOptions.eventOnly.rawValue)
#endif
XCTAssertEqual(SEEK_SET, FileDescriptor.SeekOrigin.start.rawValue)
XCTAssertEqual(SEEK_CUR, FileDescriptor.SeekOrigin.current.rawValue)
XCTAssertEqual(SEEK_END, FileDescriptor.SeekOrigin.end.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssertEqual(SEEK_HOLE, FileDescriptor.SeekOrigin.nextHole.rawValue)
XCTAssertEqual(SEEK_DATA, FileDescriptor.SeekOrigin.nextData.rawValue)
#endif
}
// TODO: test string conversion
// TODO: test option set string conversion
}
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
final class FilePermissionsTest: XCTestCase {
func testPermissions() {
// TODO: exhaustive tests
XCTAssert(FilePermissions(rawValue: 0o664) == [.ownerReadWrite, .groupReadWrite, .otherRead])
XCTAssert(FilePermissions(rawValue: 0o644) == [.ownerReadWrite, .groupRead, .otherRead])
XCTAssert(FilePermissions(rawValue: 0o777) == [.otherReadWriteExecute, .groupReadWriteExecute, .ownerReadWriteExecute])
// From the docs for FilePermissions
do {
let perms = FilePermissions(rawValue: 0o644)
XCTAssert(perms == [.ownerReadWrite, .groupRead, .otherRead])
XCTAssert(perms.contains(.ownerRead))
}
}
}
| apache-2.0 | b55ee58d0bda04ebb814cbc6ab08b6b2 | 37.452381 | 123 | 0.765635 | 4.032459 | false | true | false | false |
daferpi/p5App | p5App/p5App/MasterViewController+ARFunction.swift | 1 | 3888 | //
// MasterViewController+ARFunction.swift
// p5App
//
// Created by Abel Fernandez on 21/05/2017.
// Copyright © 2017 Daferpi. All rights reserved.
//
import UIKit
import HDAugmentedReality
import MapKit
extension MasterViewController:ARDataSource {
func showARController() {
self.arVC = ARViewController()
self.arVC.dataSource = self
self.arVC.presenter.distanceOffsetMultiplier = 0.1 // Pixels per meter
self.arVC.presenter.distanceOffsetMinThreshold = 500 // Doesn't raise annotations that are nearer than this
// Filtering for performance
self.arVC.presenter.maxDistance = 3000 // Don't show annotations if they are farther than this
self.arVC.presenter.maxVisibleAnnotations = 100 // Max number of annotations on the screen
// Stacking
self.arVC.presenter.verticalStackingEnabled = true
// Location precision
self.arVC.trackingManager.userDistanceFilter = 15
self.arVC.trackingManager.reloadDistanceFilter = 50
// Interface orientation
self.arVC.interfaceOrientationMask = .all
self.arVC.onDidFailToFindLocation =
{
[weak self, weak arVC] elapsedSeconds, acquiredLocationBefore in
self?.handleLocationFailure(elapsedSeconds: elapsedSeconds, acquiredLocationBefore: acquiredLocationBefore, arViewController: arVC)
}
// Setting annotations
var counter = 0
let annotations = self.childList.map { (schoolchild) -> ARAnnotation in
let location = CLLocation(latitude: schoolchild.location.latitude, longitude: schoolchild.location.longitude)
let annotation = ARAnnotation(identifier: "\(counter)", title: schoolchild.name, location: location)
counter += 1
return annotation!
}
self.arVC.setAnnotations(annotations)
// Presenting controller
self.present(self.arVC, animated: true, completion: nil)
}
func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView {
// Annotation views should be lightweight views, try to avoid xibs and autolayout all together.
let annotationView = ChildARAnnotationView()
if let identifier = viewForAnnotation.identifier {
let index = Int(identifier)
let child = self.childList[index!]
annotationView.image = child.photo
annotationView.littleDescription = child.littleDescription
}
annotationView.frame = CGRect(x: 0,y: 0,width: 150,height: 70)
return annotationView;
}
func handleLocationFailure(elapsedSeconds: TimeInterval, acquiredLocationBefore: Bool, arViewController: ARViewController?)
{
guard let arViewController = arViewController else { return }
guard !Platform.isSimulator else { return }
NSLog("Failed to find location after: \(elapsedSeconds) seconds, acquiredLocationBefore: \(acquiredLocationBefore)")
// Example of handling location failure
if elapsedSeconds >= 20 && !acquiredLocationBefore
{
// Stopped bcs we don't want multiple alerts
arViewController.trackingManager.stopTracking()
let alert = UIAlertController(title: "Problems", message: "Cannot find location, use Wi-Fi if possible!", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Close", style: .cancel)
{
(action) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
self.presentedViewController?.present(alert, animated: true, completion: nil)
}
}
}
| mit | f5236af3d5368728ee6068a96a191105 | 41.25 | 147 | 0.647286 | 5.196524 | false | false | false | false |
devpunk/cartesian | cartesian/Model/DrawProject/Menu/Edit/Bar/MDrawProjectMenuEditBarItemColor.swift | 1 | 1199 | import UIKit
class MDrawProjectMenuEditBarItemColor:MDrawProjectMenuEditBarItem, MDrawProjectColorDelegate
{
private weak var controller:CDrawProject?
init()
{
let title:String = NSLocalizedString("MDrawProjectMenuEditBarItemColor_title", comment:"")
super.init(
title:title,
image:#imageLiteral(resourceName: "assetGenericColor"))
}
override func selected(controller:CDrawProject)
{
self.controller = controller
controller.viewProject.showColor(
title:NSLocalizedString("MDrawProjectMenuEditBarItemColor_defaultColor", comment:""),
delegate:self)
}
//MARK: color delegate
func colorSelected(index:Int)
{
guard
let controller:CDrawProject = self.controller,
let node:DNode = controller.editingView?.viewSpatial.model as? DNode
else
{
return
}
let color:MDrawProjectColorItem = controller.modelColor.items[index]
node.colorWithColor(color:color.color)
node.notifyDraw()
DManager.sharedInstance?.save()
}
}
| mit | 8e08a381b7cbaff217bd6dee0ae857ae | 26.25 | 98 | 0.621351 | 5.123932 | false | false | false | false |
HassanEskandari/Eureka | Source/Rows/PopoverSelectorRow.swift | 5 | 2454 | // PopoverSelectorRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class _PopoverSelectorRow<Cell: CellType> : SelectorRow<Cell> where Cell: BaseCell {
public required init(tag: String?) {
super.init(tag: tag)
onPresentCallback = { [weak self] (_, viewController) -> Void in
guard let porpoverController = viewController.popoverPresentationController, let tableView = self?.baseCell.formViewController()?.tableView, let cell = self?.cell else {
fatalError()
}
porpoverController.sourceView = tableView
porpoverController.sourceRect = tableView.convert(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, from: cell)
}
presentationMode = .popover(controllerProvider: ControllerProvider.callback { return SelectorViewController<SelectorRow<Cell>> { _ in } }, onDismiss: { [weak self] in
$0.dismiss(animated: true)
self?.reload()
})
}
open override func didSelect() {
deselect()
super.didSelect()
}
}
public final class PopoverSelectorRow<T: Equatable> : _PopoverSelectorRow<PushSelectorCell<T>>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
| mit | 6a103084ed08e939990c3ddf646d8e27 | 44.444444 | 181 | 0.707416 | 4.638941 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.