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
anilkumarbp/ringcentral-swiftv2.0
Demo/Pods/ringcentral/src/src/Http/Client.swift
1
6236
// // CLient.swift // src // // Created by Anil Kumar BP on 1/21/16. // Copyright © 2016 Anil Kumar BP. All rights reserved. // import Foundation import SwiftyJSON public class Client { // Client Variables internal var useMock: Bool = false internal var appName: String internal var appVersion: String internal var mockRegistry: AnyObject? // Client Constants var contentType = "Content-Type" var jsonContentType = "application/json" var multipartContentType = "multipart/mixed" var urlencodedContentType = "application/x-www-form-urlencoded" var utf8ContentType = "charset=UTF-8" var accept = "Accept" /// Constructor for the Client /// /// - parameter appName: The appKey of your app /// - parameter appVersion: The appSecret of your app init(appName: String = "", appVersion: String = "") { self.appName = appName self.appVersion = appVersion } /// Generic HTTP request with completion handler /// /// - parameter options: List of options for HTTP request /// - parameter completion: Completion handler for HTTP request /// @resposne: ApiResponse Callback public func send(request: NSMutableURLRequest, completionHandler: (response: ApiResponse?, exception: NSException?) -> Void) { let semaphore = dispatch_semaphore_create(0) let task: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in let apiresponse = ApiResponse(request: request, data: data, response: response, error: error) // @success Handler if apiresponse.isOK() { completionHandler(response:apiresponse, exception: nil) dispatch_semaphore_signal(semaphore) } // @failure Handler else { completionHandler(response: apiresponse, exception: NSException(name: "HTTP Error", reason: "error", userInfo: nil)) dispatch_semaphore_signal(semaphore) } } task.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } /// func createRequest() /// /// @param: method NSMutableURLRequest /// @param: url list of options /// @param: query query ( optional ) /// @param: body body ( optional ) /// @param: headers headers /// @response: NSMutableURLRequest public func createRequest(method: String, url: String, query: [String: String]?=nil, body: [String: AnyObject]?, headers: [String: String]!) -> NSMutableURLRequest { var parse = parseProperties(method, url: url, query: query, body: body, headers: headers) // Create a NSMutableURLRequest var request = NSMutableURLRequest() if let nsurl = NSURL(string: url + (parse["query"] as! String)) { request = NSMutableURLRequest(URL: nsurl) request.HTTPMethod = method request.HTTPBody = parse["body"]!.dataUsingEncoding(NSUTF8StringEncoding) for (key,value) in parse["headers"] as! Dictionary<String, String> { print("key :",key, terminator: "") print("value :",value, terminator: "") request.setValue(value, forHTTPHeaderField: key) } } return request } // func parseProperties /// @param: method NSMutableURLRequest /// @param: url list of options /// @param: query query ( optional ) /// @param: body body ( optional ) /// @param: headers headers /// @response: Dictionary internal func parseProperties(method: String, url: String, query: [String: String]?=nil, body: [String: AnyObject]?, headers: [String: String]!) -> [String: AnyObject] { var parse = [String: AnyObject]() var truncatedBodyFinal: String = "" var truncatedQueryFinal: String = "" var queryFinal: String = "" // Check for query if let q = query { queryFinal = "?" for key in q.keys { if(q[key] == "") { queryFinal = "&" } else { queryFinal = queryFinal + key + "=" + q[key]! + "&" } } truncatedQueryFinal = queryFinal.substringToIndex(queryFinal.endIndex.predecessor()) } // Check for Body var bodyFinal: String = "" // Check if the body is empty if (body == nil || body?.count == 0) { truncatedBodyFinal = "" } else { if (headers["Content-type"] == "application/x-www-form-urlencoded;charset=UTF-8") { if let q = body { bodyFinal = "" for key in q.keys { bodyFinal = bodyFinal + key + "=" + (q[key]! as! String) + "&" } truncatedBodyFinal = bodyFinal.substringToIndex(bodyFinal.endIndex.predecessor()) } } else { if let json: AnyObject = body as AnyObject? { let resultJSON = JSON(json) let result = resultJSON.rawString()! // result = Util.jsonToString(json as! [String : AnyObject]) truncatedBodyFinal = result } } } parse["query"] = truncatedQueryFinal parse["body"] = truncatedBodyFinal print("The body is :"+truncatedBodyFinal, terminator: "") parse["headers"] = [String: [String: String]]() // check for Headers if headers.count == 1 { var headersFinal = [String: String]() headersFinal["Content-Type"] = "application/json" headersFinal["Accept"] = "application/json" parse["headers"] = headersFinal } else { parse["headers"] = headers } return parse } }
mit
8129ea35e5588b9e17f10ec38254a093
35.25
173
0.547394
4.960223
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/MergeSort.swift
1
913
// // MergeSort.swift // LeetCode // // Created by 黄伯驹 on 2019/3/9. // Copyright © 2019 伯驹 黄. All rights reserved. // import Foundation // https://leetcode-cn.com/explore/featured/card/top-interview-quesitons-in-2018/261/before-you-start/1109/ //输入: //nums1 = [1,2,3,0,0,0], m = 3 //nums2 = [2,5,6], n = 3 // //输出: [1,2,2,3,5,6] func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { var index = m+n-1 var i = m-1 var j = n-1 //! 因为是把 nums2 移到 nums1,那么 j = 0 就是终止条件 while j >= 0 { if i >= 0 { if nums2[j] >= nums1[i] { nums1[index] = nums2[j] j -= 1 } else { nums1[index] = nums1[i] i -= 1 } } else { nums1[index] = nums2[j] j -= 1 } index -= 1 } }
mit
39a41e8137693df8d51fd829c2e2bae5
20.02439
107
0.451276
2.719243
false
false
false
false
edwellbrook/gosquared-swift
Sources/Chat.swift
1
2011
// // Chat.swift // GoSquaredAPI // // Created by Edward Wellbrook on 27/11/2015. // Copyright (c) 2016 Edward Wellbrook. All rights reserved. // import Foundation public class Chat { private let client: GoSquaredAPI private let basePath: String internal init(client: GoSquaredAPI) { self.client = client self.basePath = "/chat/v1" } // // docs: // // public func chats() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/chats" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // // public func messages(personId: String, limit: Int = 20, offset: Int = 0) -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project), URLQueryItem(name: "limit", value: String(limit)), URLQueryItem(name: "offset", value: String(offset)) ] let path = "\(self.basePath)/chats/\(personId)/messages" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } // // docs: // // public func stream() -> URLRequest { let queryItems = [ URLQueryItem(name: "api_key", value: self.client.apiKey), URLQueryItem(name: "site_token", value: self.client.project) ] let path = "\(self.basePath)/stream" let url = URLComponents(host: "api.gosquared.com", path: path, queryItems: queryItems).url! return URLRequest(url: url, bearer: self.client.bearerToken) } }
mit
492d2aaeb22fa78ebf5e3000c29f1759
27.323944
99
0.597215
3.982178
false
false
false
false
cezarywojcik/Operations
Sources/Core/Shared/NoFailedDependenciesCondition.swift
1
2618
// // NoFailedDependenciesCondition.swift // Operations // // Created by Daniel Thorpe on 27/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation /** A condition that specificed that every dependency of the operation must succeed. If any dependency fails/cancels, the target operation will be fail. */ open class NoFailedDependenciesCondition: Condition { /// The `ErrorType` returned to indicate the condition failed. public enum ErrorType: Error, Equatable { /// When some dependencies were cancelled case cancelledDependencies /// When some dependencies failed with errors case failedDependencies } /// Initializer which takes no parameters. public override init() { super.init() name = "No Cancelled Condition" mutuallyExclusive = false } /** Evaluates the operation with respect to the finished status of its dependencies. The condition first checks if any dependencies were cancelled, in which case it fails with an `NoFailedDependenciesCondition.Error.CancelledDependencies`. Then it checks to see if any dependencies failed due to errors, in which case it fails with an `NoFailedDependenciesCondition.Error.FailedDependencies`. The cancelled or failed operations are no associated with the error. - parameter operation: the `Operation` which the condition is attached to. - parameter completion: the completion block which receives a `OperationConditionResult`. */ open override func evaluate(_ operation: AdvancedOperation, completion: @escaping CompletionBlockType) { let dependencies = operation.dependencies let cancelled = dependencies.filter { $0.isCancelled } let failures = dependencies.filter { if let operation = $0 as? AdvancedOperation { return operation.failed } return false } if !cancelled.isEmpty { completion(.failed(ErrorType.cancelledDependencies)) } else if !failures.isEmpty { completion(.failed(ErrorType.failedDependencies)) } else { completion(.satisfied) } } } /// Equatable conformance for `NoFailedDependenciesCondition.Error` public func == (lhs: NoFailedDependenciesCondition.ErrorType, rhs: NoFailedDependenciesCondition.ErrorType) -> Bool { switch (lhs, rhs) { case (.cancelledDependencies, .cancelledDependencies), (.failedDependencies, .failedDependencies): return true default: return false } }
mit
fd601cc0735f435ac7abdc458daa5446
32.139241
117
0.691749
5.153543
false
false
false
false
herrkaefer/CaseAssistant
CaseAssistant/IAPProductTableViewCell.swift
1
2115
// // IAPProductTableViewCell.swift // CaseAssistant // // Created by HerrKaefer on 15/6/15. // Copyright (c) 2015年 HerrKaefer. All rights reserved. // import UIKit import StoreKit class IAPProductCell: UITableViewCell { @IBOutlet weak var productTitleLabel: UILabel! @IBOutlet weak var productDescriptionLabel: UILabel! @IBOutlet weak var productPriceLabel: UILabel! @IBOutlet weak var buyButton: UIButton! { didSet { buyButton.layer.cornerRadius = 5.0 buyButton.addTarget(self, action: #selector(IAPProductCell.buyButtonTapped(_:)), for: .touchUpInside) } } static let priceFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.formatterBehavior = .behavior10_4 formatter.numberStyle = .currency return formatter }() var buyButtonHandler: ((_ product: SKProduct) -> ())? var product: SKProduct? { didSet { guard let product = product else { return } productTitleLabel?.text = product.localizedTitle productDescriptionLabel?.text = product.localizedDescription if CaseProducts.store.isProductPurchased(product.productIdentifier) { productPriceLabel?.text = "[已经购买]" buyButton.isHidden = true } else if IAPHelper.canMakePayments() { IAPProductCell.priceFormatter.locale = product.priceLocale productPriceLabel?.text = IAPProductCell.priceFormatter.string(from: product.price) buyButton.isHidden = false } else { productPriceLabel?.text = "[无法购买]" buyButton.isHidden = true } } } override func prepareForReuse() { super.prepareForReuse() productTitleLabel?.text = "" productPriceLabel?.text = "" } func buyButtonTapped(_ sender: AnyObject) { buyButtonHandler?(product!) } }
mpl-2.0
85a92928c8459e4c7bd5fedb7f198b9a
27.337838
113
0.595613
5.446753
false
false
false
false
marekhac/WczasyNadBialym-iOS
WczasyNadBialym/WczasyNadBialym/ViewControllers/Accommodation/AccommodationDetails/AccommodationDetailsViewController.swift
1
13947
// // AccommodationDetailsViewController.swift // WczasyNadBialym // // Created by Marek Hać on 24.02.2017. // Copyright © 2017 Marek Hać. All rights reserved. // import UIKit import MapKit import SVProgressHUD import GoogleMobileAds class AccommodationDetailsViewController: UIViewController, MKMapViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var bannerView: GADBannerView! @IBOutlet weak var bannerViewHeightConstraint: NSLayoutConstraint! var adHandler : AdvertisementHandler? let imagesReuseIdentifier = "imageCell" // also enter this string as the cell identifier in the storyboard let featuresReuseIdentifier = "featuresCell" var accommodationProperties = [String]() var selectedAccommodationId: String = "" var selectedAccommodationType: String = "" var picturesURLArray = [String]() var largePicturesURLArray = [String]() var featutesFilesArray = [String]() var advantagesFilesArray = [String]() let mapType = MKMapType.standard var selectedPicture: Int = 0 var gpsLat: Double = 0.0 var gpsLng: Double = 0.0 var pinTitle: String = "" var pinSubtitle: String = "" @IBOutlet var mainView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var phoneTextView: UITextView! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var descriptionTextView: UITextView! @IBOutlet weak var prizeUnitLabel: UILabel! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var phoneTextViewHeightContraint: NSLayoutConstraint! @IBOutlet weak var headerView: UIView! @IBOutlet weak var imageCollectionView: UICollectionView! @IBOutlet weak var featuresCollectionView: UICollectionView! @IBOutlet weak var featuresSegmentedControl: UISegmentedControl! @IBOutlet weak var imageCollectionViewHeightContraint: NSLayoutConstraint! @IBOutlet weak var accommodationPropertiesCollectionViewHeightContraint: NSLayoutConstraint! lazy var viewModel: AccommodationDetailsViewModel = { return AccommodationDetailsViewModel() }() // init view model func initViewModel () { let dispatchGroup = DispatchGroup() viewModel.updateGalleryViewClosure = { DispatchQueue.main.async { let accomodationGalleryModel = self.viewModel.getAccommodationGallery() if let pictures = accomodationGalleryModel { if (pictures.mainImgMini.count != 0) { self.picturesURLArray.append(pictures.dirMainPicture + pictures.mainImgMini) self.largePicturesURLArray.append(pictures.dirMainPicture + pictures.mainImgFull) } for picture in pictures.arrayOfPictures { self.picturesURLArray.append(pictures.dirMiniPictures + picture) self.largePicturesURLArray.append(pictures.dirLargePictures + picture) } self.imageCollectionViewHeightContraint.constant = ImageCollectionViewHeight.large.rawValue self.imageCollectionView.reloadData() self.view.updateLayoutWithAnimation(andDuration: 0.5) } else { LogEventHandler.report(LogEventType.debug, "No pictures to show") } dispatchGroup.leave() } } viewModel.updateDetailViewClosure = { DispatchQueue.main.async { let accommodationDetailsModel = self.viewModel.getAccommodationDetailsModel() if let details = accommodationDetailsModel { self.gpsLat = details.gpsLat self.gpsLng = details.gpsLng self.pinTitle = details.name self.pinSubtitle = details.phone self.mapView.fillMap(details.gpsLat, details.gpsLng, details.name, details.phone, self.mapType) self.nameLabel.text = details.name self.priceLabel.text = details.price self.phoneTextView.text = details.phone.replacingOccurrences(of: "<br>", with: "\n") self.phoneTextView.updateHeight(of: self.phoneTextViewHeightContraint) self.view.updateLayoutWithAnimation(andDuration: 0.5) self.headerView.isHidden = false // remove all html tags let detailsStripped = details.description.removeHTMLTags() self.descriptionTextView.text = detailsStripped } else { LogEventHandler.report(LogEventType.debug, "No accommodations to show") } dispatchGroup.leave() } } viewModel.updatePropertiesViewClosure = { DispatchQueue.main.async { let accommodationPropertiesModel = self.viewModel.getAccommodationProperties() if let properties = accommodationPropertiesModel { self.featutesFilesArray = properties.features self.advantagesFilesArray = properties.advantages // accommodationProperties will store features or advantages // depends on user demand. Default is features self.accommodationProperties = self.featutesFilesArray // reload and update collection view height self.accommodationPropertiesPostProcessOperations(focusOnTheBottomOfScrollView: false) } else { LogEventHandler.report(LogEventType.debug, "No properties to save") } dispatchGroup.leave() } } // Use GCD to synchronize the network tasks dispatchGroup.enter() self.viewModel.fetchAccommodationDetails(for: self.selectedAccommodationId, accommodationType: self.selectedAccommodationType) dispatchGroup.enter() self.viewModel.fetchAccommodationGallery(for: self.selectedAccommodationId) dispatchGroup.enter() self.viewModel.fetchAccommodationProperties(for: self.selectedAccommodationId) // call closure when the group's task count reaches 0 dispatchGroup.notify(queue: .main) { [weak self] in SVProgressHUD.dismiss() self?.scrollView.isHidden = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLoad() { super.viewDidLoad() // hide everything while loading self.scrollView.isHidden = true self.headerView.isHidden = true // hide images collection view (since we don't know if there are any images at all) self.imageCollectionViewHeightContraint.constant = ImageCollectionViewHeight.small.rawValue // left small row for better user experience // header self.headerView.backgroundColor = UIColor(patternImage: UIImage(named:"background_blue")!) self.headerView.addBlurSubview(at: 0) // the whole view self.mainView.backgroundColor = UIColor(patternImage: UIImage(named:"background_gradient2")!) self.mainView.addBlurSubview(at: 0) LogEventHandler.report(LogEventType.debug, "Selected accommodation id: \(self.selectedAccommodationId)") SVProgressHUD.show() initViewModel() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) displayAdvertisementBanner() } // MARK: - Request for advertisement func displayAdvertisementBanner() { self.adHandler = AdvertisementHandler(bannerAdView: self.bannerView) if let adHandler = self.adHandler { adHandler.adViewHeightConstraint = self.bannerViewHeightConstraint adHandler.showAd(viewController: self) } } // MARK: - UICollectionViewDataSource protocol func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if (collectionView == self.imageCollectionView) { return self.picturesURLArray.count } else { return self.accommodationProperties.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if (collectionView == self.imageCollectionView) { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imagesReuseIdentifier, for: indexPath as IndexPath) as! ImageCell cell.imageView.downloadImageAsync(self.picturesURLArray[indexPath.row]) return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: featuresReuseIdentifier, for: indexPath as IndexPath) as! FeaturesCell let featureImage = UIImage(named: self.accommodationProperties[indexPath.row]) cell.featureImageView.image = featureImage return cell } } // MARK: - UICollectionViewDelegate protocol func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { LogEventHandler.report(LogEventType.debug, "Selected accommodation picture cell: \(indexPath.item)") } func accommodationPropertiesPostProcessOperations(focusOnTheBottomOfScrollView focus: Bool) { let queue = OperationQueue() let reloadCollectionView = BlockOperation(block: { OperationQueue.main.addOperation({ self.featuresCollectionView.reloadData() self.featuresCollectionView.layoutIfNeeded() }) }) queue.addOperation(reloadCollectionView) let updateCollectionViewHeightContraint = BlockOperation(block: { OperationQueue.main.addOperation({ self.accommodationPropertiesCollectionViewHeightContraint.constant = self.featuresCollectionView.contentSize.height self.view.updateLayoutWithAnimation(andDuration: 0.5) }) }) updateCollectionViewHeightContraint.addDependency(reloadCollectionView) queue.addOperation(updateCollectionViewHeightContraint) if(focus) { let focusOnTheBottomOfScrollView = BlockOperation(block: { OperationQueue.main.addOperation({ let contentSizeHeight = self.scrollView.contentSize.height; let boundsSizeHeight = self.scrollView.bounds.size.height; // if contentSizeHeight is larger than boundsSizeHeight (f.e. iPad in portrait mode) // we should not touch content offset at all if (boundsSizeHeight < contentSizeHeight) { let bottomOffset = CGPoint(x: 0, y: contentSizeHeight - boundsSizeHeight) self.scrollView.setContentOffset(bottomOffset, animated: true) } }) }) focusOnTheBottomOfScrollView.addDependency(updateCollectionViewHeightContraint) queue.addOperation(focusOnTheBottomOfScrollView) } } @IBAction func featuresIndexChanged(_ sender: Any) { switch featuresSegmentedControl.selectedSegmentIndex { case 0: self.accommodationProperties = self.featutesFilesArray case 1: self.accommodationProperties = self.advantagesFilesArray default: break; } // reload, update collection view height, focus on the bottom of scrollview self.accommodationPropertiesPostProcessOperations(focusOnTheBottomOfScrollView: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showAccommodationMap" { let controller = segue.destination as! AccommodationMapViewController controller.gpsLat = self.gpsLat controller.gpsLng = self.gpsLng controller.pinTitle = self.pinTitle controller.pinSubtitle = self.pinSubtitle } if segue.identifier == "showAccommodationGallery" { let controller = segue.destination as! AccommodationGalleryPageViewController // The sender argument will be the cell so we can get the indexPath from the cell, let cell = sender as! ImageCell let indexPaths = self.imageCollectionView!.indexPath(for: cell) controller.selectedPictureIndex = (indexPaths?.last)! as Int controller.picturesURLArray = self.largePicturesURLArray } } }
gpl-3.0
38fedc2b0a0f6a63fe4cb7ab5063fbf2
38.84
149
0.613812
5.83187
false
false
false
false
michaelsabo/hammer
Ham-it/ActionViewController.swift
1
2110
// // ActionViewController.swift // Ham-it // // Created by Mike Sabo on 12/19/15. // Copyright © 2015 FlyingDinosaurs. All rights reserved. // import UIKit import MobileCoreServices class ActionViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var url = "" override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(ActionViewController.done)) if let inputItem = extensionContext!.inputItems.first as? NSExtensionItem { if let itemProvider = inputItem.attachments?.first as? NSItemProvider { itemProvider.loadItem(forTypeIdentifier: kUTTypePropertyList as String, options: nil) { [unowned self] (dict, error) in let itemDictionary = dict as! NSDictionary let javaScriptValues = itemDictionary[NSExtensionJavaScriptPreprocessingResultsKey] as! NSDictionary self.url = javaScriptValues["URL"] as! String DispatchQueue.main.async { self.title = "Ham-it" } } } } } @IBOutlet weak var messageLabel: UILabel! @IBAction func addGif(_ sender: UIButton) { var imgurId = "" if (self.url.range(of: "imgur", options: .regularExpression) != nil) { if let match = self.url.range(of: "(\\w*)$", options: .regularExpression) { imgurId = self.url.substring(with: match) } } guard imgurId.characters.count > 1 else { self.messageLabel.text = "Wasn't able to parse the imgur id - #failed" return } let gifService = GifService() gifService.addGif(imgurId, completion: { [weak self] success in if success { self?.messageLabel.text = "Success" } }) } @IBAction func done() { // Return any edited content to the host app. // This template doesn't do anything, so we just echo the passed in items. self.extensionContext!.completeRequest(returningItems: self.extensionContext!.inputItems, completionHandler: nil) } }
mit
7ee7f8656b1ce66878b8170ee531a1cb
30.477612
143
0.661451
4.525751
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/Item.swift
3
738
// // Item.swift // MercadoPagoSDK // // Created by Matias Gualino on 31/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation public class Item : NSObject { public var _id : String! public var quantity : Int = 0 public var unitPrice : Double = 0 public init(_id: String, quantity: Int, unitPrice: Double) { super.init() self._id = _id self.quantity = quantity self.unitPrice = unitPrice } public func toJSONString() -> String { let obj:[String:AnyObject] = [ "id": self._id!, "quantity" : self.quantity, "unit_price" : self.unitPrice ] return JSON(obj).toString() } }
mit
9287f1a80d56b00cdbe9e2e0e72cc57c
22.83871
64
0.573171
3.946524
false
false
false
false
box/box-ios-sdk
Tests/Modules/RetentionPolicyModuleSpecs.swift
1
28250
// // RetentionPolicyModuleSpecs.swift // BoxSDK // // Created by Martina Stremenova on 01/09/2019. // Copyright © 2019 box. All rights reserved. // @testable import BoxSDK import Nimble import OHHTTPStubs import OHHTTPStubs.NSURLRequest_HTTPBodyTesting import Quick class RetentionPolicyModuleSpecs: QuickSpec { var sut: BoxClient! override func spec() { beforeEach { self.sut = BoxSDK.getClient(token: "asdads") } afterEach { OHHTTPStubs.removeAllStubs() } describe("Retention policy") { describe("get()") { it("should get retention policy object with provided id") { let id: String = "103" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policies/\(id)") && isMethodGET() ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetRetentionPolicy.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.retentionPolicy.get(policyId: id) { result in switch result { case let .success(retentionPolicy): expect(retentionPolicy.id).to(equal(id)) expect(retentionPolicy.name).to(equal("somePolicy")) expect(retentionPolicy.policyType).to(equal(.finite)) expect(retentionPolicy.retentionLength).to(equal(10)) expect(retentionPolicy.dispositionAction).to(equal(.permanentlyDelete)) expect(retentionPolicy.status).to(equal(.active)) expect(retentionPolicy.canOwnerExtendRetention).to(equal(true)) expect(retentionPolicy.areOwnersNotified).to(equal(true)) expect(retentionPolicy.customNotificationRecipients?.count).to(equal(2)) expect(retentionPolicy.customNotificationRecipients?.first?.id).to(equal("960")) expect(retentionPolicy.createdBy?.id).to(equal("958")) expect(retentionPolicy.retentionType).to(equal(.nonModifiable)) case let .failure(error): fail("Expected call to getRetentionPolicy to succeed, but instead got \(error)") } done() } } } } describe("create()") { it("should create retention policy object with provided parameters") { let user = try! User(json: [ "type": "user", "id": "12345", "name": "Example User", "login": "[email protected]" ]) stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policies") && isMethodPOST() && hasJsonBody([ "policy_name": "Tax Documents", "policy_type": "finite", "retention_length": 365, "disposition_action": "remove_retention", "can_owner_extend_retention": false, "are_owners_notified": true, "custom_notification_recipients": [user.rawData], "retention_type": "modifiable" ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("CreateRetentionPolicy.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.retentionPolicy.create( name: "Tax Documents", type: .finite, length: 365, dispositionAction: .removeRetention, canOwnerExtendRetention: false, areOwnersNotified: true, customNotificationRecipients: [user], retentionType: .modifiable ) { result in switch result { case let .success(retentionPolicy): expect(retentionPolicy.id).to(equal("123456789")) expect(retentionPolicy.name).to(equal("Tax Documents")) expect(retentionPolicy.policyType).to(equal(.finite)) expect(retentionPolicy.retentionLength).to(equal(365)) expect(retentionPolicy.dispositionAction).to(equal(.removeRetention)) expect(retentionPolicy.status).to(equal(.active)) expect(retentionPolicy.canOwnerExtendRetention).to(equal(false)) expect(retentionPolicy.areOwnersNotified).to(equal(true)) expect(retentionPolicy.customNotificationRecipients?.count).to(equal(1)) expect(retentionPolicy.customNotificationRecipients?.first?.id).to(equal("22222")) expect(retentionPolicy.createdBy?.id).to(equal("33333")) expect(retentionPolicy.retentionType).to(equal(.modifiable)) case let .failure(error): fail("Expected call to create to succeed, but instead got \(error)") } done() } } } } describe("update()") { it("should update existing retention policy object") { let id = "123456789" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policies/\(id)") && isMethodPUT() && hasJsonBody([ "policy_name": "Tax Documents", "disposition_action": "remove_retention", "status": "active" ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("UpdateRetentionPolicy.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.retentionPolicy.update( policyId: id, name: "Tax Documents", dispositionAction: .removeRetention, status: .active ) { result in switch result { case let .success(retentionPolicy): expect(retentionPolicy.id).to(equal(id)) expect(retentionPolicy.name).to(equal("Tax Documents")) expect(retentionPolicy.policyType).to(equal(.finite)) expect(retentionPolicy.retentionLength).to(equal(365)) expect(retentionPolicy.dispositionAction).to(equal(.removeRetention)) expect(retentionPolicy.status).to(equal(.active)) expect(retentionPolicy.createdBy?.id).to(equal("22222")) expect(retentionPolicy.retentionType).to(equal(.modifiable)) case let .failure(error): fail("Expected call to updateto succeed, but instead got \(error)") } done() } } } it("should update retention type to non_modifiable") { let id = "123456789" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policies/\(id)") && isMethodPUT() && hasJsonBody([ "retention_type": "non_modifiable" ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("UpdateRetentionPolicy.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.retentionPolicy.update( policyId: id, setRetentionTypeToNonModifiable: true ) { result in switch result { case let .success(retentionPolicy): expect(retentionPolicy.id).to(equal(id)) case let .failure(error): fail("Expected call to updateto succeed, but instead got \(error)") } done() } } } } describe("list()") { it("should get all of the retention policies for given enterprise") { stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policies") && containsQueryParams(["policy_name": "name", "policy_type": "finite", "created_by_user_id": "1234"]) && isMethodGET() ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetRetentionPolicies.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let iterator = self.sut.retentionPolicy.list( name: "name", type: .finite, createdByUserId: "1234" ) iterator.next { result in switch result { case let .success(page): let retentionPolicy = page.entries[0] expect(retentionPolicy.name).to(equal("Tax Documents")) expect(retentionPolicy.id).to(equal("123456789")) case let .failure(error): fail("Expected call to list to succeed, but instead got \(error)") } done() } } } } } describe("Retention policy assignment") { describe("getAssignment()") { it("should get retention policy assignment") { let id = "11446498" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policy_assignments/\(id)") && isMethodGET() ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetRetentionPolicyAssignment.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.retentionPolicy.getAssignment(assignmentId: id) { result in switch result { case let .success(retentionPolicyAssignment): expect(retentionPolicyAssignment.id).to(equal(id)) expect(retentionPolicyAssignment.retentionPolicy?.id).to(equal("11446498")) expect(retentionPolicyAssignment.retentionPolicy?.name).to(equal("Some Policy Name")) expect(retentionPolicyAssignment.assignedTo?.id).to(equal("11446498")) expect(retentionPolicyAssignment.assignedBy?.id).to(equal("11111")) expect(retentionPolicyAssignment.assignedBy?.name).to(equal("Test User")) expect(retentionPolicyAssignment.assignedBy?.login).to(equal("[email protected]")) case let .failure(error): fail("Expected call to getAssignment to succeed, but instead got \(error)") } done() } } } } describe("assign()") { it("should create new retention policy assignment") { let id = "11446498" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policy_assignments") && isMethodPOST() && hasJsonBody([ "policy_id": id, "assign_to": [ "id": id, "type": "folder" ], "filter_fields": [ [ "field": "test", "value": "test" ] ] ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("CreateRetentionPolicyAssignment.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.retentionPolicy.assign( policyId: id, assignedContentId: id, assignContentType: RetentionPolicyAssignmentItemType.folder, filterFields: [MetadataFieldFilter(field: "test", value: "test")] ) { result in switch result { case let .success(retentionPolicyAssignment): expect(retentionPolicyAssignment.id).to(equal(id)) expect(retentionPolicyAssignment.retentionPolicy?.id).to(equal("11446498")) expect(retentionPolicyAssignment.retentionPolicy?.name).to(equal("Some Policy Name")) expect(retentionPolicyAssignment.assignedTo?.id).to(equal("11446498")) expect(retentionPolicyAssignment.assignedBy?.id).to(equal("11111")) expect(retentionPolicyAssignment.assignedBy?.name).to(equal("Test User")) expect(retentionPolicyAssignment.assignedBy?.login).to(equal("[email protected]")) case let .failure(error): fail("Expected call to assign to succeed, but instead got \(error)") } done() } } } } describe("deleteAssignment()") { it("should delete retention policy assignment") { let id = "11446498" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policy_assignments/\(id)") && isMethodDELETE() ) { _ in OHHTTPStubsResponse(data: Data(), statusCode: 204, headers: [:]) } waitUntil(timeout: .seconds(10)) { done in self.sut.retentionPolicy.deleteAssignment(assignmentId: id) { response in switch response { case .success: break case let .failure(error): fail("Expected call to deleteAssignment to succeed, but instead got \(error)") } done() } } } } describe("listAssignments()") { it("should get a list of all retention policy assignments associated with a specified retention policy") { let id = "123456" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policies/\(id)/assignments") && isMethodGET() && containsQueryParams([ "policy_type": "finite" ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetRetentionPolicyAssignments.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let iterator = self.sut.retentionPolicy.listAssignments(policyId: id, type: .finite) iterator.next { result in switch result { case let .success(page): let retentionPolicy = page.entries[0] expect(retentionPolicy.id).to(equal("12345678")) case let .failure(error): fail("Expected call to listAssignments to succeed, but instead got \(error)") } done() } } } } } describe("Retention policy on file version") { describe("getFileVersionRetention()") { it("should get information about a file version retention policy.") { let id = "1234" stub( condition: isHost("api.box.com") && isPath("/2.0/file_version_retentions/\(id)") && isMethodGET() ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetFileVersionRetention.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in self.sut.files.getVersionRetention( retentionId: id ) { result in switch result { case let .success(fileVersionRetention): expect(fileVersionRetention.id).to(equal("112729")) expect(fileVersionRetention.winningRetentionPolicy?.id).to(equal("41173")) expect(fileVersionRetention.winningRetentionPolicy?.name).to(equal("Tax Documents")) expect(fileVersionRetention.fileVersion?.id).to(equal("124887629")) expect(fileVersionRetention.fileVersion?.sha1).to(equal("4262d6250b0e6f440dca43a2337bd4621bad9136")) expect(fileVersionRetention.file?.id).to(equal("5011706273")) expect(fileVersionRetention.file?.etag).to(equal("2")) case let .failure(error): fail("Expected call to getFileVersionRetention to succeed, but instead got \(error)") } done() } } } } describe("listVersionRetentions()") { it("should get all file version retentions for the given enterprise") { let dispositionBefore = Date() stub( condition: isHost("api.box.com") && isPath("/2.0/file_version_retentions") && isMethodGET() && containsQueryParams([ "file_id": "1234", "file_version_id": "1234", "policy_id": "1234", "disposition_action": "permanently_delete", "disposition_before": dispositionBefore.iso8601 ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetFileVersionRetentions.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let iterator = self.sut.files.listVersionRetentions( fileId: "1234", fileVersionId: "1234", policyId: "1234", dispositionAction: .permanentlyDelete, dispositionBefore: dispositionBefore ) iterator.next { result in switch result { case let .success(page): let retentionPolicy = page.entries[0] expect(retentionPolicy.id).to(equal("112725")) case let .failure(error): fail("Expected call to getFileVersionRetentions to succeed, but instead got \(error)") } done() } } } } describe("listFilesUnderRetentionForAssignment()") { it("should get all file version retentions for the given enterprise") { let retentionPolicyAssignmentId = "1234" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policy_assignments/\(retentionPolicyAssignmentId)/files_under_retention") && isMethodGET() && containsQueryParams([ "limit": "100" ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetFilesUnderRetentionForAssignment.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let iterator = self.sut.retentionPolicy.listFilesUnderRetentionForAssignment( retentionPolicyAssignmentId: retentionPolicyAssignmentId, limit: 100 ) iterator.next { result in switch result { case let .success(page): let fileUnderRetention = page.entries[0] expect(fileUnderRetention.id).to(equal("12345")) expect(fileUnderRetention.name).to(equal("Contract.pdf")) expect(fileUnderRetention.fileVersion?.id).to(equal("123456")) case let .failure(error): fail("Expected call to listFilesUnderRetentionForAssignment to succeed, but instead got \(error)") } done() } } } } describe("listFileVersionsUnderRetentionForAssignment()") { it("should get all file version retentions for the given enterprise") { let retentionPolicyAssignmentId = "1234" stub( condition: isHost("api.box.com") && isPath("/2.0/retention_policy_assignments/\(retentionPolicyAssignmentId)/file_versions_under_retention") && isMethodGET() && containsQueryParams([ "limit": "100" ]) ) { _ in OHHTTPStubsResponse( fileAtPath: OHPathForFile("GetFileVersionsUnderRetentionForAssignment.json", type(of: self))!, statusCode: 200, headers: ["Content-Type": "application/json"] ) } waitUntil(timeout: .seconds(10)) { done in let iterator = self.sut.retentionPolicy.listFileVersionsUnderRetentionForAssignment( retentionPolicyAssignmentId: retentionPolicyAssignmentId, limit: 100 ) iterator.next { result in switch result { case let .success(page): let fileUnderRetention = page.entries[0] expect(fileUnderRetention.id).to(equal("123456")) expect(fileUnderRetention.name).to(equal("Contract.pdf")) expect(fileUnderRetention.fileVersion?.id).to(equal("1234567")) case let .failure(error): fail("Expected call to listFilesUnderRetentionForAssignment to succeed, but instead got \(error)") } done() } } } } } } }
apache-2.0
ce4e3e65e1c93df0a6e80109e9f200d2
51.900749
135
0.418563
6.219507
false
false
false
false
benlangmuir/swift
test/expr/delayed-ident/optional_overload.swift
4
1681
// RUN: %target-typecheck-verify-swift -dump-ast > %t.dump // RUN: %FileCheck %s < %t.dump // https://github.com/apple/swift/issues/56212 extension Optional { func member1() -> S1? {} static func member2() -> S1? {} static func member3() -> S1? {} static var member_wrongType: Int { get {} } static var member_overload: S1 { get {} } init(overloaded: Void) {} } protocol P1 {} extension Optional: P1 where Wrapped: Equatable { static func member4() {} } struct S1 { static var member1: S1? = S1() static var member2: S1? = S1() static func member3() -> S1? {} static var member4: S1? { get {} } static var member_wrongType: S1? { get {} } static var member_overload: S1? { get {} } init(overloaded: Void) {} init?(failable: Void) {} init() {} } let _: S1? = .member1 let _: S1? = .member_wrongType let _: S1? = .init() let _: S1? = .member1() // expected-error {{instance member 'member1' cannot be used on type 'S1?'}} let _: S1? = .member2() let _: S1? = .init(S1()) let _: S1? = .init(overloaded: ()) // If members exist on Optional and Wrapped, always choose the one on optional // CHECK: declref_expr {{.*}} location={{.*}}optional_overload.swift:40 // CHECK-SAME: decl=optional_overload.(file).Optional extension.init(overloaded:) let _: S1? = .member_overload // Should choose the overload from Optional even if the Wrapped overload would otherwise have a better score // CHECK: member_ref_expr {{.*}} location={{.*}}optional_overload.swift:44 // CHECK-SAME: decl=optional_overload.(file).Optional extension.member_overload let _: S1? = .init(failable: ()) let _: S1? = .member3() let _: S1? = .member4
apache-2.0
9783b8cf196199310459fa2925efdd92
32.62
108
0.637716
3.276803
false
false
false
false
mozilla-mobile/firefox-ios
Tests/XCUITests/FxScreenGraph.swift
2
48472
// 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 MappaMundi import XCTest let FirstRun = "OptionalFirstRun" let TabTray = "TabTray" let PrivateTabTray = "PrivateTabTray" let NewTabScreen = "NewTabScreen" let URLBarOpen = "URLBarOpen" let URLBarLongPressMenu = "URLBarLongPressMenu" let ReloadLongPressMenu = "ReloadLongPressMenu" let PrivateURLBarOpen = "PrivateURLBarOpen" let BrowserTab = "BrowserTab" let PrivateBrowserTab = "PrivateBrowserTab" let BrowserTabMenu = "BrowserTabMenu" let ToolsMenu = "ToolsMenu" let FindInPage = "FindInPage" let SettingsScreen = "SettingsScreen" let SyncSettings = "SyncSettings" let FxASigninScreen = "FxASigninScreen" let FxCreateAccount = "FxCreateAccount" let FxAccountManagementPage = "FxAccountManagementPage" let Intro_FxASigninEmail = "Intro_FxASigninEmail" let HomeSettings = "HomeSettings" let SiriSettings = "SiriSettings" let SearchSettings = "SearchSettings" let NewTabSettings = "NewTabSettings" let ClearPrivateDataSettings = "ClearPrivateDataSettings" let WebsiteDataSettings = "WebsiteDataSettings" let WebsiteSearchDataSettings = "WebsiteSearchDataSettings" let LoginsSettings = "LoginsSettings" let OpenWithSettings = "OpenWithSettings" let ShowTourInSettings = "ShowTourInSettings" let TrackingProtectionSettings = "TrackingProtectionSettings" let Intro_FxASignin = "Intro_FxASignin" let WebImageContextMenu = "WebImageContextMenu" let WebLinkContextMenu = "WebLinkContextMenu" let CloseTabMenu = "CloseTabMenu" let AddCustomSearchSettings = "AddCustomSearchSettings" let TabTrayLongPressMenu = "TabTrayLongPressMenu" let HistoryRecentlyClosed = "HistoryRecentlyClosed" let TrackingProtectionContextMenuDetails = "TrackingProtectionContextMenuDetails" let DisplaySettings = "DisplaySettings" let HomePanel_Library = "HomePanel_Library" let MobileBookmarks = "MobileBookmarks" let MobileBookmarksEdit = "MobileBookmarksEdit" let MobileBookmarksAdd = "MobileBookmarksAdd" let EnterNewBookmarkTitleAndUrl = "EnterNewBookmarkTitleAndUrl" let RequestDesktopSite = "RequestDesktopSite" let RequestMobileSite = "RequestMobileSite" let m1Rosetta = "rosetta" let intel = "intel" // These are in the exact order they appear in the settings // screen. XCUIApplication loses them on small screens. // This list should only be for settings screens that can be navigated to // without changing userState. i.e. don't need conditional edges to be available let allSettingsScreens = [ SearchSettings, AddCustomSearchSettings, NewTabSettings, OpenWithSettings, DisplaySettings, ClearPrivateDataSettings, TrackingProtectionSettings, ] let HistoryPanelContextMenu = "HistoryPanelContextMenu" let TopSitesPanelContextMenu = "TopSitesPanelContextMenu" let BasicAuthDialog = "BasicAuthDialog" let BookmarksPanelContextMenu = "BookmarksPanelContextMenu" let Intro_Welcome = "Intro.Welcome" let Intro_Sync = "Intro.Sync" let allIntroPages = [ Intro_Welcome, Intro_Sync ] let HomePanelsScreen = "HomePanels" let PrivateHomePanelsScreen = "PrivateHomePanels" let HomePanel_TopSites = "HomePanel.TopSites.0" let LibraryPanel_Bookmarks = "LibraryPanel.Bookmarks.1" let LibraryPanel_History = "LibraryPanel.History.2" let LibraryPanel_ReadingList = "LibraryPanel.ReadingList.3" let LibraryPanel_Downloads = "LibraryPanel.Downloads.4" let allHomePanels = [ LibraryPanel_Bookmarks, LibraryPanel_History, LibraryPanel_ReadingList, LibraryPanel_Downloads ] let iOS_Settings = XCUIApplication(bundleIdentifier: "com.apple.Preferences") let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") class Action { static let LoadURL = "LoadURL" static let LoadURLByTyping = "LoadURLByTyping" static let LoadURLByPasting = "LoadURLByPasting" static let SetURL = "SetURL" static let SetURLByTyping = "SetURLByTyping" static let SetURLByPasting = "SetURLByPasting" static let TrackingProtectionContextMenu = "TrackingProtectionContextMenu" static let TrackingProtectionperSiteToggle = "TrackingProtectionperSiteToggle" static let ReloadURL = "ReloadURL" static let OpenNewTabFromTabTray = "OpenNewTabFromTabTray" static let AcceptRemovingAllTabs = "AcceptRemovingAllTabs" static let ToggleRegularMode = "ToggleRegularMode" static let TogglePrivateMode = "TogglePrivateBrowing" static let ToggleSyncMode = "ToggleSyncMode" static let TogglePrivateModeFromTabBarHomePanel = "TogglePrivateModeFromTabBarHomePanel" static let TogglePrivateModeFromTabBarBrowserTab = "TogglePrivateModeFromTabBarBrowserTab" static let TogglePrivateModeFromTabBarNewTab = "TogglePrivateModeFromTabBarNewTab" static let ToggleRequestDesktopSite = "ToggleRequestDesktopSite" static let ToggleNightMode = "ToggleNightMode" static let ToggleTrackingProtection = "ToggleTrackingProtection" static let ToggleNoImageMode = "ToggleNoImageMode" static let Bookmark = "Bookmark" static let BookmarkThreeDots = "BookmarkThreeDots" static let OpenPrivateTabLongPressTabsButton = "OpenPrivateTabLongPressTabsButton" static let OpenNewTabLongPressTabsButton = "OpenNewTabLongPressTabsButton" static let TogglePocketInNewTab = "TogglePocketInNewTab" static let ToggleHistoryInNewTab = "ToggleHistoryInNewTab" static let SelectNewTabAsBlankPage = "SelectNewTabAsBlankPage" static let SelectNewTabAsFirefoxHomePage = "SelectNewTabAsFirefoxHomePage" static let SelectNewTabAsCustomURL = "SelectNewTabAsCustomURL" static let SelectHomeAsFirefoxHomePage = "SelectHomeAsFirefoxHomePage" static let SelectHomeAsCustomURL = "SelectHomeAsCustomURL" static let SelectTopSitesRows = "SelectTopSitesRows" static let GoToHomePage = "GoToHomePage" static let OpenSiriFromSettings = "OpenSiriFromSettings" static let AcceptClearPrivateData = "AcceptClearPrivateData" static let AcceptClearAllWebsiteData = "AcceptClearAllWebsiteData" static let TapOnFilterWebsites = "TapOnFilterWebsites" static let ShowMoreWebsiteDataEntries = "ShowMoreWebsiteDataEntries" static let ClearRecentHistory = "ClearRecentHistory" static let ToggleTrackingProtectionPerTabEnabled = "ToggleTrackingProtectionPerTabEnabled" static let OpenSettingsFromTPMenu = "OpenSettingsFromTPMenu" static let SwitchETP = "SwitchETP" static let CloseTPContextMenu = "CloseTPContextMenu" static let EnableStrictMode = "EnableStrictMode" static let EnableStandardMode = "EnableStandardMode" static let CloseTab = "CloseTab" static let CloseTabFromTabTrayLongPressMenu = "CloseTabFromTabTrayLongPressMenu" static let OpenEmailToSignIn = "OpenEmailToSignIn" static let OpenEmailToQR = "OpenEmailToQR" static let FxATypeEmail = "FxATypeEmail" static let FxATypePassword = "FxATypePassword" static let FxATapOnSignInButton = "FxATapOnSignInButton" static let FxATapOnContinueButton = "FxATapOnContinueButton" static let PinToTopSitesPAM = "PinToTopSitesPAM" static let CopyAddressPAM = "CopyAddressPAM" static let ShareBrowserTabMenuOption = "ShareBrowserTabMenuOption" static let SentToDevice = "SentToDevice" static let AddToReadingListBrowserTabMenu = "AddToReadingListBrowserTabMenu" static let SelectAutomatically = "SelectAutomatically" static let SelectManually = "SelectManually" static let SystemThemeSwitch = "SystemThemeSwitch" static let AddCustomSearchEngine = "AddCustomSearchEngine" static let RemoveCustomSearchEngine = "RemoveCustomSearchEngine" static let ExitMobileBookmarksFolder = "ExitMobileBookmarksFolder" static let CloseBookmarkPanel = "CloseBookmarkPanel" static let CloseReadingListPanel = "CloseReadingListPanel" static let CloseHistoryListPanel = "CloseHistoryListPanel" static let CloseDownloadsPanel = "CloseDownloadsPanel" static let CloseSyncedTabsPanel = "CloseSyncedTabsPanel" static let AddNewBookmark = "AddNewBookmark" static let AddNewFolder = "AddNewFolder" static let AddNewSeparator = "AddNewSeparator" static let RemoveItemMobileBookmarks = "RemoveItemMobileBookmarks" static let ConfirmRemoveItemMobileBookmarks = "ConfirmRemoveItemMobileBookmarks" static let SaveCreatedBookmark = "SaveCreatedBookmark" static let OpenWhatsNewPage = "OpenWhatsNewPage" static let OpenSearchBarFromSearchButton = "OpenSearchBarFromSearchButton" static let CloseURLBarOpen = "CloseURLBarOpen" } @objcMembers class FxUserState: MMUserState { required init() { super.init() initialScreenState = FirstRun } var isPrivate = false var showIntro = false var showWhatsNew = false var waitForLoading = true var url: String? var requestDesktopSite = false var noImageMode = false var nightMode = false var pocketInNewTab = false var bookmarksInNewTab = true var historyInNewTab = true var fxaUsername: String? var fxaPassword: String? var numTabs: Int = 0 var numTopSitesRows: Int = 2 var trackingProtectionPerTabEnabled = true // TP can be shut off on a per-tab basis var trackingProtectionSettingOnNormalMode = true var trackingProtectionSettingOnPrivateMode = true var localeIsExpectedDifferent = false } private let defaultURL = "https://www.mozilla.org/en-US/book/" func createScreenGraph(for test: XCTestCase, with app: XCUIApplication) -> MMScreenGraph<FxUserState> { let map = MMScreenGraph(for: test, with: FxUserState.self) let navigationControllerBackAction = { app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap() } let cancelBackAction = { app.otherElements["PopoverDismissRegion"].tap() } let dismissContextMenuAction = { app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.25)).tap() } map.addScreenState(FirstRun) { screenState in screenState.noop(to: BrowserTab, if: "showIntro == false && showWhatsNew == true") screenState.noop(to: NewTabScreen, if: "showIntro == false && showWhatsNew == false") screenState.noop(to: allIntroPages[0], if: "showIntro == true") } // Add the intro screens. var i = 0 let introLast = allIntroPages.count - 1 for intro in allIntroPages { _ = i == 0 ? nil : allIntroPages[i - 1] let next = i == introLast ? nil : allIntroPages[i + 1] map.addScreenState(intro) { screenState in if let next = next { screenState.tap(app.buttons["nextOnboardingButton"], to: next) } else { let startBrowsingButton = app.buttons["startBrowsingOnboardingButton"] screenState.tap(startBrowsingButton, to: BrowserTab) } } i += 1 } // Some internally useful screen states. let WebPageLoading = "WebPageLoading" map.addScreenState(NewTabScreen) { screenState in screenState.noop(to: HomePanelsScreen) if isTablet { screenState.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray) } else { screenState.gesture(to: TabTray) { if app.buttons["TabToolbar.tabsButton"].exists { app.buttons["TabToolbar.tabsButton"].tap() } else { app.buttons["URLBarView.tabsButton"].tap() } } } makeURLBarAvailable(screenState) screenState.tap(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], to: BrowserTabMenu) if isTablet { screenState.tap(app.buttons["Private Mode"], forAction: Action.TogglePrivateModeFromTabBarNewTab) { userState in userState.isPrivate = !userState.isPrivate } } } map.addScreenState(URLBarLongPressMenu) { screenState in let menu = app.tables["Context Menu"].firstMatch if !(processIsTranslatedStr() == m1Rosetta) { if #unavailable(iOS 16) { screenState.gesture(forAction: Action.LoadURLByPasting, Action.LoadURL) { userState in UIPasteboard.general.string = userState.url ?? defaultURL menu.otherElements[ImageIdentifiers.pasteAndGo].firstMatch.tap() } } } screenState.gesture(forAction: Action.SetURLByPasting) { userState in UIPasteboard.general.string = userState.url ?? defaultURL menu.cells[ImageIdentifiers.paste].firstMatch.tap() } screenState.backAction = { if isTablet { // There is no Cancel option in iPad. app.otherElements["PopoverDismissRegion"].tap() } else { app.buttons["PhotonMenu.close"].tap() } } screenState.dismissOnUse = true } map.addScreenState(TrackingProtectionContextMenuDetails) { screenState in screenState.gesture(forAction: Action.TrackingProtectionperSiteToggle) { userState in app.tables.cells["tp.add-to-safelist"].tap() userState.trackingProtectionPerTabEnabled = !userState.trackingProtectionPerTabEnabled } screenState.gesture(forAction: Action.OpenSettingsFromTPMenu, transitionTo: TrackingProtectionSettings) { userState in app.cells["settings"].tap() } screenState.gesture(forAction: Action.CloseTPContextMenu) { userState in if isTablet { // There is no Cancel option in iPad. app.otherElements["PopoverDismissRegion"].tap() } else { app.buttons["PhotonMenu.close"].tap() } } } // URLBarOpen is dismissOnUse, which ScreenGraph interprets as "now we've done this action, then go back to the one before it" // but SetURL is an action than keeps us in URLBarOpen. So let's put it here. map.addScreenAction(Action.SetURL, transitionTo: URLBarOpen) map.addScreenState(URLBarOpen) { screenState in // This is used for opening BrowserTab with default mozilla URL // For custom URL, should use Navigator.openNewURL or Navigator.openURL. screenState.gesture(forAction: Action.LoadURLByTyping) { userState in let url = userState.url ?? defaultURL // Workaround BB iOS13 be sure tap happens on url bar app.textFields.firstMatch.tap() app.textFields.firstMatch.tap() app.textFields.firstMatch.typeText(url) app.textFields.firstMatch.typeText("\r") } screenState.gesture(forAction: Action.SetURLByTyping, Action.SetURL) { userState in let url = userState.url ?? defaultURL // Workaround BB iOS13 be sure tap happens on url bar sleep(1) app.textFields.firstMatch.tap() app.textFields.firstMatch.tap() app.textFields.firstMatch.typeText("\(url)") } screenState.noop(to: HomePanelsScreen) screenState.noop(to: HomePanel_TopSites) screenState.backAction = { app.buttons["urlBar-cancel"].tap() } screenState.dismissOnUse = true } // LoadURL points to WebPageLoading, which allows us to add additional // onEntryWaitFor requirements, which we don't need when we're returning to BrowserTab without // loading a webpage. // We do end up at WebPageLoading however, so should lead quickly back to BrowserTab. map.addScreenAction(Action.LoadURL, transitionTo: WebPageLoading) map.addScreenState(WebPageLoading) { screenState in screenState.dismissOnUse = true // Would like to use app.otherElements.deviceStatusBars.networkLoadingIndicators.element // but this means exposing some of SnapshotHelper to another target. /*if !(app.progressIndicators.element(boundBy: 0).exists) { screenState.onEnterWaitFor("exists != true", element: app.progressIndicators.element(boundBy: 0), if: "waitForLoading == true") } else { screenState.onEnterWaitFor(element: app.progressIndicators.element(boundBy: 0), if: "waitForLoading == false") }*/ screenState.noop(to: BrowserTab, if: "waitForLoading == true") screenState.noop(to: BasicAuthDialog, if: "waitForLoading == false") } map.addScreenState(BasicAuthDialog) { screenState in screenState.onEnterWaitFor(element: app.alerts.element(boundBy: 0)) screenState.backAction = { app.alerts.element(boundBy: 0).buttons.element(boundBy: 0).tap() } screenState.dismissOnUse = true } map.addScreenState(HomePanelsScreen) { screenState in if isTablet { screenState.tap(app.buttons["Private Mode"], forAction: Action.TogglePrivateModeFromTabBarHomePanel) { userState in userState.isPrivate = !userState.isPrivate } } // Workaround to bug Bug 1417522 if isTablet { screenState.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray) } else { screenState.gesture(to: TabTray) { // iPhone sim tabs button is called differently when in portrait or landscape if XCUIDevice.shared.orientation == UIDeviceOrientation.landscapeLeft { app.buttons["URLBarView.tabsButton"].tap() } else { app.buttons["TabToolbar.tabsButton"].tap() } } } screenState.gesture(forAction: Action.CloseURLBarOpen, transitionTo: HomePanelsScreen) {_ in app.buttons["urlBar-cancel"].tap() } } map.addScreenState(LibraryPanel_Bookmarks) { screenState in screenState.tap(app.cells.staticTexts["Mobile Bookmarks"], to: MobileBookmarks) screenState.gesture(forAction: Action.CloseBookmarkPanel, transitionTo: HomePanelsScreen) { userState in app.buttons["Done"].tap() } screenState.press(app.tables["Bookmarks List"].cells.element(boundBy: 4), to: BookmarksPanelContextMenu) } map.addScreenState(MobileBookmarks) { screenState in let bookmarksMenuNavigationBar = app.navigationBars["Mobile Bookmarks"] let bookmarksButton = bookmarksMenuNavigationBar.buttons["Bookmarks"] screenState.gesture(forAction: Action.ExitMobileBookmarksFolder, transitionTo: LibraryPanel_Bookmarks) { userState in bookmarksButton.tap() } screenState.tap(app.buttons["Edit"], to: MobileBookmarksEdit) } map.addScreenState(MobileBookmarksEdit) { screenState in screenState.tap(app.buttons["Add"], to: MobileBookmarksAdd) screenState.gesture(forAction: Action.RemoveItemMobileBookmarks) { userState in app.tables["Bookmarks List"].buttons.element(boundBy: 0).tap() } screenState.gesture(forAction: Action.ConfirmRemoveItemMobileBookmarks) { userState in app.buttons["Delete"].tap() } } map.addScreenState(MobileBookmarksAdd) { screenState in screenState.gesture(forAction: Action.AddNewBookmark, transitionTo: EnterNewBookmarkTitleAndUrl) { userState in app.tables.cells[ImageIdentifiers.actionAddBookmark].tap() } screenState.gesture(forAction: Action.AddNewFolder) { userState in app.tables.cells["bookmarkFolder"].tap() } screenState.gesture(forAction: Action.AddNewSeparator) { userState in app.tables.cells["nav-menu"].tap() } } map.addScreenState(EnterNewBookmarkTitleAndUrl) { screenState in screenState.gesture(forAction: Action.SaveCreatedBookmark) { userState in app.buttons["Save"].tap() } } map.addScreenState(HomePanel_TopSites) { screenState in let topSites = app.cells[AccessibilityIdentifiers.FirefoxHomepage.TopSites.itemCell] screenState.press(topSites.cells.matching(identifier: AccessibilityIdentifiers.FirefoxHomepage.TopSites.itemCell).element(boundBy: 0), to: TopSitesPanelContextMenu) } map.addScreenState(LibraryPanel_History) { screenState in screenState.press(app.tables[AccessibilityIdentifiers.LibraryPanels.HistoryPanel.tableView].cells.element(boundBy: 2), to: HistoryPanelContextMenu) screenState.tap(app.cells[AccessibilityIdentifiers.LibraryPanels.HistoryPanel.recentlyClosedCell], to: HistoryRecentlyClosed) screenState.gesture(forAction: Action.ClearRecentHistory) { userState in app.tables[AccessibilityIdentifiers.LibraryPanels.HistoryPanel.tableView] .cells .matching(identifier: AccessibilityIdentifiers.LibraryPanels.HistoryPanel.clearHistoryCell) .element(boundBy: 0) .tap() } screenState.gesture(forAction: Action.CloseHistoryListPanel, transitionTo: HomePanelsScreen) { userState in app.buttons["Done"].tap() } } map.addScreenState(LibraryPanel_ReadingList) { screenState in screenState.dismissOnUse = true screenState.gesture(forAction: Action.CloseReadingListPanel, transitionTo: HomePanelsScreen) { userState in app.buttons["Done"].tap() } } map.addScreenState(LibraryPanel_Downloads) { screenState in screenState.dismissOnUse = true screenState.gesture(forAction: Action.CloseDownloadsPanel, transitionTo: HomePanelsScreen) { userState in app.buttons["Done"].tap() } } map.addScreenState(HistoryRecentlyClosed) { screenState in screenState.dismissOnUse = true screenState.tap(app.buttons["libraryPanelTopLeftButton"].firstMatch, to: LibraryPanel_History) } map.addScreenState(HistoryPanelContextMenu) { screenState in screenState.dismissOnUse = true } map.addScreenState(BookmarksPanelContextMenu) { screenState in screenState.dismissOnUse = true } map.addScreenState(TopSitesPanelContextMenu) { screenState in screenState.dismissOnUse = true screenState.backAction = dismissContextMenuAction } map.addScreenState(SettingsScreen) { screenState in let table = app.tables.element(boundBy: 0) screenState.tap(table.cells["Sync"], to: SyncSettings, if: "fxaUsername != nil") screenState.tap(table.cells["SignInToSync"], to: Intro_FxASignin, if: "fxaUsername == nil") screenState.tap(table.cells[AccessibilityIdentifiers.Settings.Search.searchNavigationBar], to: SearchSettings) screenState.tap(table.cells["NewTab"], to: NewTabSettings) screenState.tap(table.cells[AccessibilityIdentifiers.Settings.Homepage.homeSettings], to: HomeSettings) screenState.tap(table.cells["OpenWith.Setting"], to: OpenWithSettings) screenState.tap(table.cells["DisplayThemeOption"], to: DisplaySettings) screenState.tap(table.cells["SiriSettings"], to: SiriSettings) screenState.tap(table.cells[AccessibilityIdentifiers.Settings.Logins.loginsSettings], to: LoginsSettings) screenState.tap(table.cells[AccessibilityIdentifiers.Settings.ClearData.clearPrivatedata], to: ClearPrivateDataSettings) screenState.tap(table.cells["TrackingProtection"], to: TrackingProtectionSettings) screenState.tap(table.cells["ShowTour"], to: ShowTourInSettings) screenState.backAction = navigationControllerBackAction } map.addScreenState(DisplaySettings) { screenState in screenState.gesture(forAction: Action.SelectAutomatically) { userState in app.cells.staticTexts["Automatically"].tap() } screenState.gesture(forAction: Action.SelectManually) { userState in app.cells.staticTexts["Manually"].tap() } screenState.gesture(forAction: Action.SystemThemeSwitch) { userState in app.switches["SystemThemeSwitchValue"].tap() } screenState.backAction = navigationControllerBackAction } map.addScreenState(SearchSettings) { screenState in let table = app.tables.element(boundBy: 0) screenState.tap(table.cells[AccessibilityIdentifiers.Settings.Search.customEngineViewButton], to: AddCustomSearchSettings) screenState.backAction = navigationControllerBackAction screenState.gesture(forAction: Action.RemoveCustomSearchEngine) {userSTate in // Screengraph will go back to main Settings screen. Manually tap on settings app.tables[AccessibilityIdentifiers.Settings.tableViewController].staticTexts["Google"].tap() app.navigationBars[AccessibilityIdentifiers.Settings.Search.searchNavigationBar].buttons["Edit"].tap() app.tables.buttons[AccessibilityIdentifiers.Settings.Search.deleteMozillaEngine].tap() app.tables.buttons[AccessibilityIdentifiers.Settings.Search.deleteButton].tap() } } map.addScreenState(SiriSettings) { screenState in screenState.gesture(forAction: Action.OpenSiriFromSettings) { userState in // Tap on Open New Tab to open Siri app.cells["SiriSettings"].staticTexts.element(boundBy: 0).tap() } screenState.backAction = navigationControllerBackAction } map.addScreenState(SyncSettings) { screenState in screenState.backAction = navigationControllerBackAction } map.addScreenState(FxASigninScreen) { screenState in screenState.backAction = navigationControllerBackAction screenState.gesture(forAction: Action.FxATypeEmail) { userState in if isTablet { app.webViews.textFields.firstMatch.tap() app.webViews.textFields.firstMatch.typeText(userState.fxaUsername!) } else { app.textFields[AccessibilityIdentifiers.Settings.FirefoxAccount.emailTextField].tap() app.textFields[AccessibilityIdentifiers.Settings.FirefoxAccount.emailTextField].typeText(userState.fxaUsername!) } } screenState.gesture(forAction: Action.FxATypePassword) { userState in app.secureTextFields.element(boundBy: 0).tap() app.secureTextFields.element(boundBy: 0).typeText(userState.fxaPassword!) } screenState.gesture(forAction: Action.FxATapOnContinueButton) { userState in app.webViews.buttons[AccessibilityIdentifiers.Settings.FirefoxAccount.continueButton].tap() } screenState.gesture(forAction: Action.FxATapOnSignInButton) { userState in app.webViews.buttons.element(boundBy: 0).tap() } screenState.tap(app.webViews.links["Create an account"].firstMatch, to: FxCreateAccount) } map.addScreenState(FxCreateAccount) { screenState in screenState.backAction = navigationControllerBackAction } map.addScreenState(AddCustomSearchSettings) { screenState in screenState.gesture(forAction: Action.AddCustomSearchEngine) { userState in app.tables.textViews["customEngineTitle"].staticTexts["Search Engine"].tap() app.typeText("Mozilla Engine") app.tables.textViews["customEngineUrl"].tap() UIPasteboard.general.string = "https://developer.mozilla.org/search?q=%s" let tablesQuery = app.tables let customengineurlTextView = tablesQuery.textViews["customEngineUrl"] sleep(1) customengineurlTextView.press(forDuration: 1.0) app.staticTexts["Paste"].tap() } screenState.backAction = navigationControllerBackAction } map.addScreenState(WebsiteDataSettings) { screenState in screenState.gesture(forAction: Action.AcceptClearAllWebsiteData) { userState in app.tables.cells["ClearAllWebsiteData"].tap() app.alerts.buttons["OK"].tap() } // The swipeDown() is a workaround for an intermittent issue that the search filed is not always in view. screenState.gesture(forAction: Action.TapOnFilterWebsites) { userState in app.searchFields["Filter Sites"].tap() } screenState.gesture(forAction: Action.ShowMoreWebsiteDataEntries) { userState in app.tables.cells["ShowMoreWebsiteData"].tap() } screenState.backAction = navigationControllerBackAction } map.addScreenState(NewTabSettings) { screenState in let table = app.tables.element(boundBy: 0) screenState.gesture(forAction: Action.SelectNewTabAsBlankPage) { UserState in table.cells["NewTabAsBlankPage"].tap() } screenState.gesture(forAction: Action.SelectNewTabAsFirefoxHomePage) { UserState in table.cells["NewTabAsFirefoxHome"].tap() } screenState.gesture(forAction: Action.SelectNewTabAsCustomURL) { UserState in table.cells["NewTabAsCustomURL"].tap() } screenState.backAction = navigationControllerBackAction } map.addScreenState(HomeSettings) { screenState in screenState.gesture(forAction: Action.SelectHomeAsFirefoxHomePage) { UserState in app.cells["HomeAsFirefoxHome"].tap() } screenState.gesture(forAction: Action.SelectHomeAsCustomURL) { UserState in app.cells["HomeAsCustomURL"].tap() } screenState.gesture(forAction: Action.TogglePocketInNewTab) { userState in userState.pocketInNewTab = !userState.pocketInNewTab app.switches["ASPocketStoriesVisible"].tap() } screenState.gesture(forAction: Action.SelectTopSitesRows) { userState in app.tables.cells["TopSitesRows"].tap() select(rows: userState.numTopSitesRows) app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap() } screenState.backAction = navigationControllerBackAction } func select(rows: Int) { app.staticTexts[String(rows)].firstMatch.tap() } func type(text: String) { text.forEach { char in app.keys[String(char)].tap() } } map.addScreenState(ClearPrivateDataSettings) { screenState in screenState.tap(app.cells["WebsiteData"], to: WebsiteDataSettings) screenState.gesture(forAction: Action.AcceptClearPrivateData) { userState in app.tables.cells["ClearPrivateData"].tap() app.alerts.buttons["OK"].tap() } screenState.backAction = navigationControllerBackAction } map.addScreenState(OpenWithSettings) { screenState in screenState.backAction = navigationControllerBackAction } map.addScreenState(ShowTourInSettings) { screenState in screenState.gesture(to: Intro_FxASignin) { let turnOnSyncButton = app.buttons["signInOnboardingButton"] turnOnSyncButton.tap() } } map.addScreenState(TrackingProtectionSettings) { screenState in screenState.backAction = navigationControllerBackAction screenState.tap(app.switches["prefkey.trackingprotection.normalbrowsing"], forAction: Action.SwitchETP) { userState in userState.trackingProtectionSettingOnNormalMode = !userState.trackingProtectionSettingOnNormalMode } screenState.tap(app.cells["Settings.TrackingProtectionOption.BlockListStrict"], forAction: Action.EnableStrictMode) { userState in userState.trackingProtectionPerTabEnabled = !userState.trackingProtectionPerTabEnabled } } map.addScreenState(Intro_FxASignin) { screenState in screenState.tap(app.buttons["EmailSignIn.button"], forAction: Action.OpenEmailToSignIn, transitionTo: FxASigninScreen) screenState.tap(app.buttons[AccessibilityIdentifiers.Settings.FirefoxAccount.qrButton], forAction: Action.OpenEmailToQR, transitionTo: Intro_FxASignin) screenState.tap(app.navigationBars.buttons.element(boundBy: 0), to: SettingsScreen) screenState.backAction = navigationControllerBackAction } map.addScreenState(TabTray) { screenState in // Both iPad and iPhone use the same accessibility identifiers for buttons, // even thought they may be in separate locations design wise. screenState.tap(app.buttons[AccessibilityIdentifiers.TabTray.newTabButton], forAction: Action.OpenNewTabFromTabTray, transitionTo: NewTabScreen) if isTablet { screenState.tap(app.navigationBars.buttons["closeAllTabsButtonTabTray"], to: CloseTabMenu) } else { screenState.tap(app.toolbars.buttons["closeAllTabsButtonTabTray"], to: CloseTabMenu) } var regularModeSelector: XCUIElement var privateModeSelector: XCUIElement var syncModeSelector: XCUIElement if isTablet { regularModeSelector = app.navigationBars.segmentedControls.buttons.element(boundBy: 0) privateModeSelector = app.navigationBars.segmentedControls.buttons.element(boundBy: 1) syncModeSelector = app.navigationBars.segmentedControls.buttons.element(boundBy: 2) } else { regularModeSelector = app.toolbars["Toolbar"] .segmentedControls[AccessibilityIdentifiers.TabTray.navBarSegmentedControl].buttons.element(boundBy: 0) privateModeSelector = app.toolbars["Toolbar"] .segmentedControls[AccessibilityIdentifiers.TabTray.navBarSegmentedControl].buttons.element(boundBy: 1) syncModeSelector = app.toolbars["Toolbar"] .segmentedControls[AccessibilityIdentifiers.TabTray.navBarSegmentedControl].buttons.element(boundBy: 2) } screenState.tap(regularModeSelector, forAction: Action.ToggleRegularMode) { userState in userState.isPrivate = !userState.isPrivate } screenState.tap(privateModeSelector, forAction: Action.TogglePrivateMode) { userState in userState.isPrivate = !userState.isPrivate } screenState.tap(syncModeSelector, forAction: Action.ToggleSyncMode) { userState in } screenState.onEnter { userState in if isTablet { userState.numTabs = Int(app.collectionViews["Top Tabs View"].cells.count) } else { userState.numTabs = Int(app.otherElements["Tabs Tray"].cells.count) } } } // This menu is only available for iPhone, NOT for iPad, no menu when long tapping on tabs button if !isTablet { map.addScreenState(TabTrayLongPressMenu) { screenState in screenState.dismissOnUse = true screenState.tap(app.otherElements[ImageIdentifiers.newTab], forAction: Action.OpenNewTabLongPressTabsButton, transitionTo: NewTabScreen) screenState.tap(app.otherElements["tab_close"], forAction: Action.CloseTabFromTabTrayLongPressMenu, Action.CloseTab, transitionTo: HomePanelsScreen) screenState.tap(app.otherElements["nav-tabcounter"], forAction: Action.OpenPrivateTabLongPressTabsButton, transitionTo: NewTabScreen) { userState in userState.isPrivate = !userState.isPrivate } } } map.addScreenState(CloseTabMenu) { screenState in screenState.tap(app.scrollViews.buttons[AccessibilityIdentifiers.TabTray.deleteCloseAllButton], forAction: Action.AcceptRemovingAllTabs, transitionTo: HomePanelsScreen) screenState.backAction = cancelBackAction } func makeURLBarAvailable(_ screenState: MMScreenStateNode<FxUserState>) { screenState.tap(app.textFields["url"], to: URLBarOpen) screenState.gesture(to: URLBarLongPressMenu) { sleep(1) app.textFields["url"].press(forDuration: 1.0) } } func makeToolBarAvailable(_ screenState: MMScreenStateNode<FxUserState>) { screenState.tap(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], to: BrowserTabMenu) if isTablet { screenState.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray) } else { screenState.gesture(to: TabTray) { if app.buttons["TabToolbar.tabsButton"].exists { app.buttons["TabToolbar.tabsButton"].tap() } else { app.buttons["URLBarView.tabsButton"].tap() } } } } map.addScreenState(BrowserTab) { screenState in makeURLBarAvailable(screenState) screenState.tap(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], to: BrowserTabMenu) screenState.tap(app.buttons[AccessibilityIdentifiers.Toolbar.trackingProtection], to: TrackingProtectionContextMenuDetails) screenState.tap(app.buttons[AccessibilityIdentifiers.Toolbar.homeButton], forAction: Action.GoToHomePage) { userState in } makeToolBarAvailable(screenState) let link = app.webViews.element(boundBy: 0).links.element(boundBy: 0) let image = app.webViews.element(boundBy: 0).images.element(boundBy: 0) screenState.press(link, to: WebLinkContextMenu) screenState.press(image, to: WebImageContextMenu) if !isTablet { let reloadButton = app.buttons[AccessibilityIdentifiers.Toolbar.reloadButton] screenState.press(reloadButton, to: ReloadLongPressMenu) screenState.tap(reloadButton, forAction: Action.ReloadURL, transitionTo: WebPageLoading) { _ in } } else { let reloadButton = app.buttons["Reload"] screenState.press(reloadButton, to: ReloadLongPressMenu) screenState.tap(reloadButton, forAction: Action.ReloadURL, transitionTo: WebPageLoading) { _ in } } // For iPad there is no long press on tabs button if !isTablet { let tabsButton = app.buttons["TabToolbar.tabsButton"] screenState.press(tabsButton, to: TabTrayLongPressMenu) } if isTablet { screenState.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray) } else { screenState.gesture(to: TabTray) { if app.buttons["TabToolbar.tabsButton"].exists { app.buttons["TabToolbar.tabsButton"].tap() } else { app.buttons["URLBarView.tabsButton"].tap() } } } screenState.tap(app.buttons["TopTabsViewController.privateModeButton"], forAction: Action.TogglePrivateModeFromTabBarBrowserTab) { userState in userState.isPrivate = !userState.isPrivate } } map.addScreenState(ReloadLongPressMenu) { screenState in screenState.backAction = cancelBackAction screenState.dismissOnUse = true let rdsButton = app.tables["Context Menu"].cells.element(boundBy: 0) screenState.tap(rdsButton, forAction: Action.ToggleRequestDesktopSite) { userState in userState.requestDesktopSite = !userState.requestDesktopSite } let trackingProtectionButton = app.tables["Context Menu"].cells.element(boundBy: 1) screenState.tap(trackingProtectionButton, forAction: Action.ToggleTrackingProtectionPerTabEnabled) { userState in userState.trackingProtectionPerTabEnabled = !userState.trackingProtectionPerTabEnabled } } [WebImageContextMenu, WebLinkContextMenu].forEach { item in map.addScreenState(item) { screenState in screenState.dismissOnUse = true screenState.backAction = { let window = XCUIApplication().windows.element(boundBy: 0) window.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap() } } } map.addScreenState(FxAccountManagementPage) { screenState in screenState.backAction = navigationControllerBackAction } map.addScreenState(FindInPage) { screenState in screenState.tap(app.buttons["FindInPage.close"], to: BrowserTab) } map.addScreenState(RequestDesktopSite) { _ in } map.addScreenState(RequestMobileSite) { _ in } map.addScreenState(HomePanel_Library) { screenState in screenState.dismissOnUse = true screenState.backAction = navigationControllerBackAction screenState.tap(app.segmentedControls["librarySegmentControl"].buttons.element(boundBy: 0), to: LibraryPanel_Bookmarks) screenState.tap(app.segmentedControls["librarySegmentControl"].buttons.element(boundBy: 1), to: LibraryPanel_History) screenState.tap(app.segmentedControls["librarySegmentControl"].buttons.element(boundBy: 2), to: LibraryPanel_Downloads) screenState.tap(app.segmentedControls["librarySegmentControl"].buttons.element(boundBy: 3), to: LibraryPanel_ReadingList) } map.addScreenState(LoginsSettings) { screenState in screenState.backAction = navigationControllerBackAction } map.addScreenState(BrowserTabMenu) { screenState in screenState.tap(app.tables.otherElements[ImageIdentifiers.settings], to: SettingsScreen) screenState.tap(app.tables.otherElements[ImageIdentifiers.sync], to: Intro_FxASignin, if: "fxaUsername == nil") screenState.tap(app.tables.otherElements[ImageIdentifiers.key], to: LoginsSettings) screenState.tap(app.tables.otherElements[ImageIdentifiers.bookmarks], to: LibraryPanel_Bookmarks) screenState.tap(app.tables.otherElements[ImageIdentifiers.history], to: LibraryPanel_History) screenState.tap(app.tables.otherElements[ImageIdentifiers.downloads], to: LibraryPanel_Downloads) screenState.tap(app.tables.otherElements[ImageIdentifiers.readingList], to: LibraryPanel_ReadingList) screenState.tap(app.tables.otherElements[ImageIdentifiers.placeholderAvatar], to: FxAccountManagementPage) screenState.tap(app.tables.otherElements[ImageIdentifiers.nightMode], forAction: Action.ToggleNightMode, transitionTo: BrowserTabMenu) { userState in userState.nightMode = !userState.nightMode } screenState.tap(app.tables.otherElements[ImageIdentifiers.whatsNew], forAction: Action.OpenWhatsNewPage) { userState in } screenState.tap(app.tables.otherElements[ImageIdentifiers.sendToDevice], forAction: Action.SentToDevice) { userState in } screenState.tap(app.tables.otherElements[ImageIdentifiers.share], forAction: Action.ShareBrowserTabMenuOption) { userState in } screenState.tap(app.tables.otherElements[ImageIdentifiers.requestDesktopSite], to: RequestDesktopSite) screenState.tap(app.tables.otherElements[ImageIdentifiers.requestMobileSite], to: RequestMobileSite) screenState.tap(app.tables.otherElements[ImageIdentifiers.findInPage], to: FindInPage) // TODO: Add new state // screenState.tap(app.tables["Context Menu"].otherElements[ImageIdentifiers.reportSiteIssue], to: ReportSiteIssue) screenState.tap(app.tables.otherElements[ImageIdentifiers.addShortcut], forAction: Action.PinToTopSitesPAM) screenState.tap(app.tables.otherElements[ImageIdentifiers.copyLink], forAction: Action.CopyAddressPAM) screenState.tap(app.tables.otherElements[ImageIdentifiers.addToBookmark], forAction: Action.BookmarkThreeDots, Action.Bookmark) screenState.tap(app.tables.otherElements[ImageIdentifiers.addToReadingList], forAction: Action.AddToReadingListBrowserTabMenu) screenState.dismissOnUse = true screenState.backAction = cancelBackAction } return map } extension MMNavigator where T == FxUserState { func openURL(_ urlString: String, waitForLoading: Bool = true) { UIPasteboard.general.string = urlString userState.url = urlString userState.waitForLoading = waitForLoading // Using LoadURLByTyping for Intel too on Xcode14 if processIsTranslatedStr() == m1Rosetta { performAction(Action.LoadURLByTyping) } else if #available (iOS 16, *) { performAction(Action.LoadURLByTyping) } else { performAction(Action.LoadURL) } } // Opens a URL in a new tab. func openNewURL(urlString: String) { let app = XCUIApplication() if isTablet { waitForExistence(app.buttons["TopTabsViewController.tabsButton"], timeout: 15) } else { waitForExistence(app.buttons["TabToolbar.tabsButton"], timeout: 10) } self.goto(TabTray) createNewTab() self.openURL(urlString) } // Add a new Tab from the New Tab option in Browser Tab Menu func createNewTab() { let app = XCUIApplication() self.goto(TabTray) app.buttons[AccessibilityIdentifiers.TabTray.newTabButton].tap() self.nowAt(NewTabScreen) } // Add Tab(s) from the Tab Tray func createSeveralTabsFromTabTray(numberTabs: Int) { let app = XCUIApplication() for _ in 1...numberTabs { if isTablet { waitForExistence(app.buttons["TopTabsViewController.tabsButton"], timeout: 5) } else { waitForExistence(app.buttons["TabToolbar.tabsButton"], timeout: 5) } self.goto(TabTray) self.goto(HomePanelsScreen) } } } // Temporary code to detect the MacOS where tests are running // and so load websites one way or the other as per the condition above // in the openURLBar method. This is due to issue: // https://github.com/mozilla-mobile/firefox-ios/issues/9910#issue-1120710818 let NATIVE_EXECUTION = Int32(0) let EMULATED_EXECUTION = Int32(1) func processIsTranslated() -> Int32 { var ret = Int32(0) var size = ret.bitWidth let result = sysctlbyname("sysctl.proc_translated", &ret, &size, nil, 0) if result == -1 { if errno == ENOENT { return 0 } return -1 } return ret } func processIsTranslatedStr() -> String { switch processIsTranslated() { case NATIVE_EXECUTION: return "native" case EMULATED_EXECUTION: return "rosetta" default: return "unkown" } } extension XCUIElement { /// For tables only: scroll the table downwards until /// the end is reached. /// Each time a whole screen has scrolled, the passed closure is /// executed with the index number of the screen. /// Care is taken to make sure that every cell is completely on screen /// at least once. func forEachScreen(_ eachScreen: (Int) -> Void) { guard self.elementType == .table else { return } func firstInvisibleCell(_ start: UInt) -> UInt { let cells = self.cells for i in start ..< UInt(cells.count) { let cell = cells.element(boundBy: Int(i)) // if the cell's bottom is beyond the table's bottom // i.e. if the cell isn't completely visible. if self.frame.maxY <= cell.frame.maxY { return i } } return UInt.min } var cellNum: UInt = 0 var screenNum = 0 while true { eachScreen(screenNum) let firstCell = self.cells.element(boundBy: Int(cellNum)) cellNum = firstInvisibleCell(cellNum) if cellNum == UInt.min { return } let lastCell = self.cells.element(boundBy: Int(cellNum)) let bottom: XCUICoordinate // If the cell is a little bit on the table. // We shouldn't drag from too close to the edge of the screen, // because Control Center gets summoned. if lastCell.frame.minY < self.frame.maxY * 0.95 { bottom = lastCell.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.0)) } else { bottom = self.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.95)) } let top = firstCell.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.0)) bottom.press(forDuration: 0.1, thenDragTo: top) screenNum += 1 } } }
mpl-2.0
830dee448f2c7a42ce49c893524996a7
42.086222
176
0.696794
4.951175
false
false
false
false
wangweicheng7/ClouldFisher
CloudFisher/Vendor/ZLSwifthRefresh/ZLSwiftHeadView.swift
1
2015
// // ZLSwiftHeadView.swift // ZLSwiftRefresh // // Created by 张磊 on 15-3-6. // Copyright (c) 2015年 com.zixue101.www. All rights reserved. // import UIKit class ZLSwiftHeadView: UIView { var headLabel: UILabel = UILabel() var headImageView : UIImageView = UIImageView() var title:String { set { headLabel.text = newValue } get { return headLabel.text! } } var imgName:String { set { self.headImageView.image = UIImage(named: "dropdown_anim__000\(newValue)") self.headLabel.isHidden = true } get { return self.imgName } } override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ let headImageView:UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) headImageView.center = CGPoint(x: self.frame.size.width * 0.5, y: self.frame.size.height * 0.5) headImageView.contentMode = .center headImageView.clipsToBounds = true; headImageView.image = UIImage(named: "dropdown_anim__0001.png") self.addSubview(headImageView) self.headImageView = headImageView } func startAnimation(){ // let results:[AnyObject] = [ // UIImage(named: "dropdown_loading_01.png")!, // UIImage(named: "dropdown_loading_02.png")!, // UIImage(named: "dropdown_loading_03.png")! // ] // self.headImageView.animationImages = results as [AnyObject]? as! [UIImage]? // self.headImageView.animationDuration = 0.6; // self.headImageView.animationRepeatCount = 0; // self.headImageView.startAnimating() } func stopAnimation(){ self.headImageView.stopAnimating() } }
mit
6a9c0890fa73f66705f46ffdc4619578
26.148649
103
0.578397
4.329741
false
false
false
false
malcommac/SwiftUnistroke
Pod/Classes/SwiftUnistroke.swift
1
19071
// // SwiftOneStroke.swift // SwiftOneStroke // ======================================= // // $1 Unistroke Implementation in Swift 2+ // // Created by Daniele Margutti on 02/10/15. // Copyright (c) 2015 Daniele Margutti. All Rights Reserved. // This code is distribuited under MIT license (https://en.wikipedia.org/wiki/MIT_License). // // Daniele Margutti // Web: http://www.danielemargutti.com // Mail: [email protected] // Twitter: @danielemargutti // // Original algorithm was developed by: // // Jacob Wobbrock, Andy Wilson, Yang Li // "Gestures without libraries, toolkits or Training: a $1.00 Recognizer for User Interface Prototypes" // ACM Symposium on User Interface Software and Technology (2007) // (p.159-168). // Web: https://depts.washington.edu/aimgroup/proj/dollar/ // // 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 import UIKit import Darwin /** Exceptions - MatchNotFound: No valid matches found for recognize method - EmptyTemplates: No templates array provided - TooFewPoints: Too few points for input path points */ public enum StrokeErrors: ErrorType { case MatchNotFound case EmptyTemplates case TooFewPoints } public class SwiftUnistroke { var points: [StrokePoint] = [] /** Initialize a new recognizer class. - parameter points: Input points array - returns: the instance of the recognizer */ public init(points: [StrokePoint]) { self.points = points } /** This method initiate the recognition task. Based upon passed templates it return the best score found or throws an exception if fails. You can also execute this method in another thread. - parameter templates: an arrat of SwiftUnistrokeTemplate objects - parameter useProtractor: use protractor method to compare angles (faster but less accurate) - parameter minThreshold: minimum accepted threshold to return found match (a value between 0 and 1; a 0.80 threshold is the default choice) - throws: throws an exception if templates aray is empty, passed input stroke points are not enough or match is not found. - returns: best match */ public func recognizeIn(templates: [SwiftUnistrokeTemplate]!, useProtractor: Bool = false, minThreshold: Double = 0.80) throws -> (template: SwiftUnistrokeTemplate?, distance: Double?) { if templates.count == 0 || points.count == 0 { throw StrokeErrors.EmptyTemplates } if points.count < 10 { throw StrokeErrors.TooFewPoints } self.points = StrokePoint.resample(points, totalPoints: StrokeConsts.numPoints) let radians = StrokePoint.indicativeAngle(self.points) self.points = StrokePoint.rotate(self.points, byRadians: -radians) self.points = StrokePoint.scale(self.points, toSize: StrokeConsts.squareSize) self.points = StrokePoint.translate(self.points, to: StrokePoint.zeroPoint()) let vector = StrokePoint.vectorize(self.points) var bestDistance = Double.infinity var bestTemplate: SwiftUnistrokeTemplate? for template in templates { var templateDistance: Double if useProtractor == true { templateDistance = StrokePoint.optimalCosineDistance(template.vector, v2: vector) } else { templateDistance = StrokePoint.distanceAtBestAngle(points, strokeTemplate: template.points, fromAngle: -StrokeConsts.angleRange, toAngle: StrokeConsts.angleRange, threshold: StrokeConsts.anglePrecision) } if templateDistance < bestDistance { bestDistance = templateDistance bestTemplate = template } } if bestTemplate != nil { bestDistance = (useProtractor == true ? 1.0 / bestDistance : 1.0 - bestDistance / StrokeConsts.halfDiagonal) if bestDistance < minThreshold { throw StrokeErrors.MatchNotFound } return (bestTemplate,bestDistance) } else { throw StrokeErrors.MatchNotFound } } } /// This class represent a stroke template. You pass a list of these objects to the the recognizer in order to perform a search /// You can allocate a new template starting from a list of CGPoints or StrokePoints (a variant of CGPoint which is more precise) public class SwiftUnistrokeTemplate : SwiftUnistroke { var name: String var vector: [Double] /** Initialize a new template object with a name and a list of stroke points - parameter name: name of the template - parameter points: list of points (must be a StrokePoint). Use convenince init to init from a list of CGPoint (ie. when you have points taken from touches inside an UIView subclass. - returns: a stroke template instance */ public init(name: String, points: [StrokePoint]) { self.name = name var initializedPoints = StrokePoint.resample(points, totalPoints: StrokeConsts.numPoints) let radians = StrokePoint.indicativeAngle(initializedPoints) initializedPoints = StrokePoint.rotate(initializedPoints, byRadians: -radians) initializedPoints = StrokePoint.scale(initializedPoints, toSize: StrokeConsts.squareSize) initializedPoints = StrokePoint.translate(initializedPoints, to: StrokePoint.zeroPoint()) self.vector = StrokePoint.vectorize(initializedPoints) super.init(points: initializedPoints) } /** Initialize a new template object by passing a list of CGPoints - parameter name: name of the template - parameter points: points array as CGPoint - returns: a stroke template instance */ public convenience init(name: String, points: [CGPoint]) { let strokePoints = StrokePoint.pointsArray(fromCGPoints: points) self.init(name: name, points: strokePoints) } } /** * StrokePoint is a class which represent a point, more or less is similar to CGPoint but uses double instead of float in order * to get a better precision. */ public struct StrokePoint { var x: Double var y: Double /** Initialize a new StrokePoint with passed pair of coordinates (x,y) - parameter x: x coordinate value - parameter y: y coordinate value - returns: a new StrokePoint */ public init(x: Double, y: Double) { self.x = x self.y = y } /** Initialize a new StrokePoint starting from a CGPoint - parameter point: source CGPoint - returns: strokePoint */ public init(point: CGPoint) { self.x = Double(point.x) self.y = Double(point.y) } /** Convert a StrokePoint to CGPoint - returns: CGPoint version of the object */ public func toPoint() -> CGPoint { return CGPointMake(CGFloat(self.x), CGFloat(self.y)) } /** An origin stroke point (something like CGPointZero) - returns: An origin based StrokePoint */ public static func zeroPoint() -> StrokePoint { return StrokePoint(point: CGPointZero) } /** Get an array of StrokePoints starting from an array of CGPoints - parameter cgPoints: CGPoint array - returns: a StrokePoint array */ public static func pointsArray(fromCGPoints cgPoints: [CGPoint]) -> [StrokePoint] { var strokePoints: [StrokePoint] = [] for point in cgPoints { strokePoints.append(StrokePoint(x: Double(point.x), y: Double(point.y))) } return strokePoints } } /** * This class is the CGRect variant based upon double data type */ public struct BoundingRect { var x: Double var y: Double var width: Double var height: Double public init(x: Double, y: Double, w: Double, h: Double) { self.x = x self.y = y self.width = w self.height = h } } /** * A list of constants used inside the Stroke Recognizer algorithm */ public struct StrokeConsts { public static let Phi: Double = (0.5 * (-1.0 + sqrt(5.0))) public static let numPoints: Int = 64 public static let squareSize: Double = 250.0 public static let diagonal = sqrt( squareSize * squareSize + squareSize * squareSize ) public static let halfDiagonal = (diagonal * 0.5) public static let angleRange: Double = Double(45.0).toRadians() public static let anglePrecision: Double = Double(2.0).toRadians() } /** * This class represent a mutable edge (rect) instance. */ public struct Edge { private var minX: Double private var minY: Double private var maxX: Double private var maxY: Double /** Initialize a new edges rect with passed minX,maxX,minY,maxY values - parameter minX: min x - parameter maxX: max x - parameter minY: min y - parameter maxY: max y - returns: a new rect edges structure */ init(minX: Double, maxX: Double, minY: Double, maxY: Double) { self.minX = minX self.minY = minY self.maxX = maxX self.maxY = maxY } /** Add a new point to the edge. Each point growth the size of the edge rect - parameter value: value to cumulate */ public mutating func addPoint(value: StrokePoint) { self.minX = min(self.minX,value.x) self.maxX = max(self.maxX,value.x) self.minY = min(self.minY,value.y) self.maxY = max(self.maxY,value.y) } } extension Double { /** Convert a degree value to radians - returns: radian */ public func toRadians() -> Double { let res = self * M_PI / 180.0 return res } } extension StrokePoint { /** Return the lenght of a path points - parameter points: array of points - returns: length of the segment */ public static func pathLength(points: [StrokePoint]) -> Double { var totalDistance:Double = 0.0 for var idx = 1; idx < points.count; ++idx { totalDistance += points[idx-1].distanceTo(points[idx]) } return totalDistance } /** Return the distance between two paths - parameter path1: path 1 - parameter path2: path 2 - returns: distance */ public static func pathDistance(path1: [StrokePoint], path2: [StrokePoint]) -> Double { var d: Double = 0.0 for (var idx = 0; idx < path1.count; ++idx) { d += path1[idx].distanceTo(path2[idx]) } return (d / Double(path1.count)) } /** Return the centroid of a path points - parameter points: path - returns: centroid point */ public static func centroid(points: [StrokePoint]) -> StrokePoint { var centroidPoint = StrokePoint.zeroPoint() for point in points { centroidPoint.x = centroidPoint.x + point.x centroidPoint.y = centroidPoint.y + point.y } let totalPoints = Double(points.count) centroidPoint.x = (centroidPoint.x / totalPoints) centroidPoint.y = (centroidPoint.y / totalPoints) return centroidPoint } /** Return the bounding rect which contains a set of points - parameter points: points array - returns: the rect (as BoundingRect) which contains all the points */ public static func boundingBox(points: [StrokePoint]) -> BoundingRect { var edge = Edge(minX: +Double.infinity, maxX: -Double.infinity, minY: +Double.infinity, maxY: -Double.infinity) for point in points { edge.addPoint(point) } let rect = BoundingRect(x: edge.minX, y: edge.minY, w: (edge.maxX - edge.minX), h: (edge.maxY - edge.minY) ) return rect } /** Return the distance of a point (self) from another point - parameter point: target point - returns: distance */ public func distanceTo(point: StrokePoint) -> Double { let dx = point.x - self.x let dy = point.y - self.y return sqrt( dx * dx + dy * dy ) } /** Rotate a path by given radians value and return the new set of paths - parameter points: origin points array - parameter radians: rotation radians - returns: rotated points path */ public static func rotate(points: [StrokePoint], byRadians radians: Double) -> [StrokePoint] { let centroid = StrokePoint.centroid(points) let cosvalue = cos(radians) let sinvalue = sin(radians) var newPoints: [StrokePoint] = [] for point in points { let qx = (point.x - centroid.x) * cosvalue - (point.y - centroid.y) * sinvalue + centroid.x let qy = (point.x - centroid.x) * sinvalue + (point.y - centroid.y) * cosvalue + centroid.y newPoints.append(StrokePoint(x: qx, y: qy)) } return newPoints } /** Perform a non-uniform scale of given path points - parameter points: origin path points - parameter size: new size - returns: scaled path points */ public static func scale(points: [StrokePoint], toSize size: Double) -> [StrokePoint] { let boundingBox = StrokePoint.boundingBox(points) var newPoints: [StrokePoint] = [] for point in points { let qx = point.x * (size / boundingBox.width) let qy = point.y * (size / boundingBox.height) newPoints.append(StrokePoint(x: qx, y: qy)) } return newPoints } /** Translate a set of path points by a given value expressed both for x and y coordinates - parameter points: path points - parameter pt: translation point - returns: translated path points */ public static func translate(points: [StrokePoint], to pt: StrokePoint) -> [StrokePoint] { let centroidPoint = StrokePoint.centroid(points) var newPoints: [StrokePoint] = [] for point in points { let qx = point.x + pt.x - centroidPoint.x let qy = point.y + pt.y - centroidPoint.y newPoints.append(StrokePoint(x: qx, y: qy)) } return newPoints } /** Generate a vector representation for the gesture. The procedure takes two parameters: points are resampled points from Step 1, and oSensitive specifies whether the gesture should be treated orientation sensitive or invariant. The procedure first translates the gesture so that its centroid is the origin, and then rotates the gesture to align its indicative angle with a base orientation. VECTORIZE returns a normalized vector with a length of 2n. - parameter points: points - returns: a vector array of doubles */ public static func vectorize(points: [StrokePoint]) -> [Double] { var sum: Double = 0.0 var vector: [Double] = [] for point in points { vector.append(point.x) vector.append(point.y) sum += (point.x * point.x) + (point.y * point.y) } let magnitude = sqrt(sum) for (var i = 0; i < vector.count; ++i) { vector[i] = vector[i] / magnitude } return vector } /** This method return the optimal cosine distance; provides a closed-form solution to find the minimum cosine distance between the vectors of a template and the unknown gesture by only rotating the template once. More on protactor: https://depts.washington.edu/aimgroup/proj/dollar/protractor.pdf - parameter v1: vector 1 - parameter v2: vector 2 - returns: minimum cosine distance between two vectors */ public static func optimalCosineDistance(v1: [Double], v2: [Double]) -> Double { var a: Double = 0.0 var b: Double = 0.0 for (var i = 0; i < v1.count; i+=2) { a += v1[i] * v2[i] + v1[i+1] * v2[i+1] b += v1[i] * v2[i+1] - v1[i+1] * v2[i] } let angle = atan(b / a) let res = acos(a * cos(angle) + b * sin(angle)) return res } /** Return the distance at best angle between two path points - parameter points: input path points - parameter strokeTemplate: comparisor template path points - parameter fromAngle: min angle - parameter toAngle: max angle - parameter threshold: accepted threshold - returns: min distance */ public static func distanceAtBestAngle(points: [StrokePoint], strokeTemplate: [StrokePoint], var fromAngle: Double, var toAngle: Double, threshold: Double) -> Double { var x1 = StrokeConsts.Phi * fromAngle + (1.0 - StrokeConsts.Phi) * toAngle var f1 = StrokePoint.distanceAtAngle(points, strokeTemplate: strokeTemplate, radians: x1) var x2 = (1.0 - StrokeConsts.Phi) * fromAngle + StrokeConsts.Phi * toAngle var f2 = StrokePoint.distanceAtAngle(points, strokeTemplate: strokeTemplate, radians: x2) while ( abs(toAngle-fromAngle) > threshold ) { if f1 < f2 { toAngle = x2 x2 = x1 f2 = f1 x1 = StrokeConsts.Phi * fromAngle + (1.0 - StrokeConsts.Phi) * toAngle f1 = StrokePoint.distanceAtAngle(points, strokeTemplate: strokeTemplate, radians: x1) } else { fromAngle = x1 x1 = x2 f1 = f2 x2 = (1.0 - StrokeConsts.Phi) * fromAngle + StrokeConsts.Phi * toAngle f2 = StrokePoint.distanceAtAngle(points, strokeTemplate: strokeTemplate, radians: x2) } } return min(f1,f2) } /** Distance of a path points with another one at given angle - parameter points: input path points - parameter strokeTemplate: comparisor template path points - parameter radians: value of the angle - returns: distance at given angle between path points */ public static func distanceAtAngle(points: [StrokePoint], strokeTemplate: [StrokePoint], radians: Double) -> Double { let newPoints = StrokePoint.rotate(points, byRadians: radians) return StrokePoint.pathDistance(newPoints, path2: strokeTemplate) } /** Return indicative angle for a given set of path points - parameter points: points - returns: rotation indicative angle of the path */ public static func indicativeAngle(points: [StrokePoint]) -> Double { let centroid = StrokePoint.centroid(points) return atan2(centroid.y - points.first!.y, centroid.x - points.first!.x) } /** Resample the points of a gesture into n evenly spaced points. Protractor uses the same resampling method as the $1 recognizer3 does, although Protractor only needs n = 16 points to perform optimally. - parameter points: path points array - parameter totalPoints: number of points of the output resampled points array - returns: resampled points array */ private static func resample(points: [StrokePoint], totalPoints: Int) -> [StrokePoint] { var initialPoints = points let interval = StrokePoint.pathLength(initialPoints) / Double(totalPoints - 1) var totalLength: Double = 0.0 var newPoints: [StrokePoint] = [points.first!] for var i = 1; i < initialPoints.count; ++i { let currentLength = initialPoints[i-1].distanceTo(initialPoints[i]) if ( (totalLength+currentLength) >= interval) { let qx = initialPoints[i-1].x + ((interval - totalLength) / currentLength) * (initialPoints[i].x - initialPoints[i-1].x) let qy = initialPoints[i-1].y + ((interval - totalLength) / currentLength) * (initialPoints[i].y - initialPoints[i-1].y) let q = StrokePoint(x: qx, y: qy) newPoints.append(q) initialPoints.insert(q, atIndex: i) totalLength = 0.0 } else { totalLength += currentLength } } if newPoints.count == totalPoints-1 { newPoints.append(points.last!) } return newPoints } }
mit
e493144e0fb1bc9dc164c42fd1e4d6d9
30.628524
226
0.713701
3.509569
false
false
false
false
yarshure/Surf
Surf-Today/RequestsWindowController.swift
1
10875
// // RequestsWindowController.swift // Surf // // Created by networkextension on 24/11/2016. // Copyright © 2016 yarshure. All rights reserved. // import Cocoa import SwiftyJSON import NetworkExtension import SFSocket import XProxy class RequestsWindowController: NSWindowController,NSTableViewDelegate,NSTableViewDataSource{ public var results:[SFRequestInfo] = [] public var dbURL:URL? @IBOutlet public weak var tableView:NSTableView! //var vc:RequestsVC! override func windowDidLoad() { super.windowDidLoad() //dbURL = RequestHelper.shared.openForApp() //recent() Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(RequestsWindowController.refreshRequest(_:)), userInfo: nil, repeats: true) // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. // let st = NSStoryboard.init(name: NSStoryboard.Name(rawValue: "RequestBasic"), bundle: nil) // let vc = st.instantiateInitialController() as! RequestsVC // self.window?.contentView = vc.view } @objc func refreshRequest(_ t:Timer){ // Send a simple IPC message to the provider, handle the response. //AxLogger.log("send Hello Provider") if let m = SFVPNManager.shared.manager { let date = NSDate() let me = SFVPNXPSCommand.RECNETREQ.rawValue + "|\(date)" if let session = m.connection as? NETunnelProviderSession, let message = me.data(using: .utf8), m.connection.status == .connected { do { try session.sendProviderMessage(message) {[weak self] response in guard let s = self else {return} if response != nil { //let responseString = NSString(data: response!, encoding: NSUTF8StringEncoding) //mylog("Received response from the provider: \(responseString)") s.processData(data: response!) //self.registerStatus() } else { //s.alertMessageAction("Got a nil response from the provider",complete: nil) print("resp nil") } } } catch { print("send msg fail!") //alertMessageAction("Failed to send a message to the provider",complete: nil) } } } } public func processData(data:Data) { let oldresults = results results.removeAll() let obj = try! JSON.init(data: data) if obj.error == nil { let count = obj["count"] if count.intValue != 0 { let result = obj["data"] if result.type == .array { for item in result { let json = item.1 let r = SFRequestInfo.init(rID: 0) r.map(json) let rr = oldresults.filter({ info -> Bool in if info.reqID == r.reqID && info.subID == r.subID { return true } return false }) if rr.isEmpty { results.append(r) r.speedtraffice = r.traffice }else { let old = rr.first! if r.traffice.rx > old.traffice.rx { //sub id reset r.speedtraffice.rx = r.traffice.rx - old.traffice.rx } if r.traffice.tx > old.traffice.tx{ //? r.speedtraffice.tx = r.traffice.tx - old.traffice.tx } results.append(r) } } } if results.count > 0 { results.sort(by: { $0.reqID < $1.reqID }) } } } tableView.reloadData() } public func numberOfRows(in tableView: NSTableView) -> Int { return results.count } public func tableView(_ tableView: NSTableView , objectValueFor tableColumn: NSTableColumn? , row: Int) -> Any? { let result = results[row] if (tableColumn?.identifier)!.rawValue == "Icon" { switch result.rule.policy{ case .Direct: return NSImage(named:"NSStatusPartiallyAvailable") case .Proxy: return NSImage(named:"NSStatusAvailable") case .Reject: return NSImage(named:"NSStatusUnavailable") default: break } } return nil } public func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let iden = tableColumn!.identifier.rawValue let result = results[row] let cell:NSTableCellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView if iden == "Index" { cell.textField?.stringValue = "\(result.reqID) \(result.subID)" }else if iden == "App" { cell.textField?.attributedStringValue = result.detailString() }else if iden == "Url" { if result.mode == .HTTP { if let u = URL(string: result.url){ if let h = u.host { cell.textField?.stringValue = h }else { cell.textField?.stringValue = u.description } }else { if let req = result.reqHeader{ cell.textField?.stringValue = req.Host } } }else { cell.textField?.stringValue = result.url } }else if iden == "Rule" { }else if iden == "Date" { cell.textField?.stringValue = result.dataDesc(result.sTime) }else if iden == "Status" { let n = Date() let a = result.activeTime let idle = n.timeIntervalSince(a) if idle > 1 { cell.textField?.stringValue = "idle \(Int(idle))" }else { cell.textField?.stringValue = result.status.description } }else if iden == "Policy" { let rule = result.rule cell.textField?.stringValue = rule.policy.description + " (" + rule.type.description + ":" + rule.name + ")" //(\(rule.type.description):\(rule.name) ProxyName:\(rule.proxyName))" //cell.textField?.stringValue = "Demo"//result.status.description }else if iden == "Up" { let tx = result.speedtraffice.tx cell.textField?.stringValue = self.toString(x: tx,label:"",speed: true) }else if iden == "Down" { let rx = result.speedtraffice.rx cell.textField?.stringValue = self.toString(x: rx,label:"",speed: true) }else if iden == "Method" { if result.mode == .TCP{ cell.textField?.stringValue = "TCP" }else { if let req = result.reqHeader { if req.method == .CONNECT { cell.textField?.stringValue = "HTTPS" }else { cell.textField?.stringValue = req.method.rawValue } } } }else if iden == "Icon" { switch result.rule.policy{ case .Direct: cell.imageView?.objectValue = NSImage(named:"NSStatusPartiallyAvailable") case .Proxy: cell.imageView?.objectValue = NSImage(named:"NSStatusAvailable") case .Reject: cell.imageView?.objectValue = NSImage(named:"NSStatusUnavailable") default: break } }else if iden == "DNS" { if !result.rule.ipAddress.isEmpty { cell.textField?.stringValue = result.rule.ipAddress }else { if !result.remoteIPaddress.isEmpty{ let x = result.remoteIPaddress.components(separatedBy: " ") if x.count > 1 { cell.textField?.stringValue = x.last! }else { cell.textField?.stringValue = x.first! } }else { if !result.rule.name.isEmpty { cell.textField?.stringValue = result.rule.name }else { let x = "NONE" let s = NSMutableAttributedString(string:x ) let r = NSMakeRange(0, 4); s.addAttributes([NSAttributedString.Key.foregroundColor:NSColor.red,NSAttributedString.Key.backgroundColor:NSColor.white], range: r) cell.textField?.attributedStringValue = s } } } } if row % 2 == 0 { cell.backgroundStyle = .dark }else { cell.backgroundStyle = .light } return cell } public func toString(x:UInt,label:String,speed:Bool) ->String { var s = "/s" if !speed { s = "" } if x < 1024{ return label + " \(x) B" + s }else if x >= 1024 && x < 1024*1024 { return label + String(format: "%0.2f KB", Float(x)/1024.0) + s }else if x >= 1024*1024 && x < 1024*1024*1024 { return label + String(format: "%0.2f MB", Float(x)/1024/1024) + s }else { return label + String(format: "%0.2f GB", Float(x)/1024/1024/1024) + s } } }
bsd-3-clause
1d72079d070bd01180d2db72564ac0fb
37.154386
157
0.458617
5.155998
false
false
false
false
aleclarson/dispatcher
DispatchGroup.swift
3
1144
import CoreGraphics import Dispatch public typealias Group = DispatchGroup public class DispatchGroup { public init (_ tasks: Int = 0) { for _ in 0..<tasks { ++self } } public private(set) var tasks = 0 public let dispatch_group = dispatch_group_create() public func done (callback: Void -> Void) { dispatch_group_notify(dispatch_group, gcd.current.dispatch_queue, callback) } public func wait (delay: CGFloat, _ callback: Void -> Void) { dispatch_group_wait(dispatch_group, dispatch_time(DISPATCH_TIME_NOW, Int64(delay * CGFloat(NSEC_PER_SEC)))) } deinit { assert(tasks == 0, "A DispatchGroup cannot be deallocated when tasks is greater than zero!") } } public prefix func ++ (group: DispatchGroup) { objc_sync_enter(group) group.tasks += 1 dispatch_group_enter(group.dispatch_group) objc_sync_exit(group) } public prefix func -- (group: DispatchGroup) { objc_sync_enter(group) group.tasks -= 1 dispatch_group_leave(group.dispatch_group) objc_sync_exit(group) } public postfix func ++ (group: DispatchGroup) { ++group } public postfix func -- (group: DispatchGroup) { --group }
mit
1ff4391cb05a8eaf205c4641dac71109
22.833333
111
0.696678
3.620253
false
false
false
false
wickwirew/FluentLayout
FluentLayout/Layout.swift
2
4775
import Foundation open class Layout: UIStackView { public init() { super.init(frame: .zero) initializeView() } public override init(frame: CGRect) { super.init(frame: frame) } public required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func initializeView() { axis = .vertical alignment = .fill distribution = .fill spacing = LayoutDefaults.spacing } // Serves no other purpose as a syntax helper public func create(axis: UILayoutConstraintAxis = .vertical, alignment: UIStackViewAlignment = .fill, distribution: UIStackViewDistribution = .fill, spacing: CGFloat = LayoutDefaults.spacing, create: ((Layout) -> Void)?) { self.axis = axis self.alignment = alignment self.distribution = distribution self.spacing = spacing if let c = create { c(self) } } // MARK: Sections public func addSection(title: String? = nil, axis: UILayoutConstraintAxis = .vertical, alignment: UIStackViewAlignment = .fill, distribution: UIStackViewDistribution = .fill, spacing: CGFloat = LayoutDefaults.sectionSpacing, create: ((LayoutSection) -> Void)? = nil) { let section = LayoutSection() section.layout.axis = axis section.layout.alignment = alignment section.layout.distribution = distribution section.layout.spacing = spacing if let t = title { section.addTitleLabel(text: t) } if let c = create { c(section) } addArrangedSubview(section) } // MARK: UI Components @discardableResult public func add<TView: UIView>(view: TView) -> TView { addArrangedSubview(view) return view } @discardableResult public func addLabel(text: String) -> UILabel { let label = LayoutDefaults.defaultControls.createLabel() label.text = text addArrangedSubview(label) return label } @discardableResult public func addTitleLabel(text: String) -> UILabel { let label = LayoutDefaults.defaultControls.createTitleLabel() label.text = text return add(view: label) } @discardableResult public func addTextField(text: String? = nil, placeholder: String? = nil) -> UITextField { let field = LayoutDefaults.defaultControls.createTextField() field.text = text field.placeholder = placeholder return add(view: field) } @discardableResult public func addButton(title: String? = nil, image: String? = nil) -> UIButton { let button = LayoutDefaults.defaultControls.createButton() if let t = title { button.setTitle(t, for: .normal) } if let i = image { button.setImage(UIImage(named: i), for: .normal) } return add(view: button) } @discardableResult public func addImage(named: String? = nil, contentMode: UIViewContentMode = .scaleAspectFit) -> UIImageView { let image = LayoutDefaults.defaultControls.createImage() image.contentMode = contentMode add(view: image) if let i = named { image.image = UIImage(named: i) } return image } @discardableResult public func addTextView() -> UITextView { let text = LayoutDefaults.defaultControls.createTextView() return add(view: text) } @discardableResult public func addFelxibleSpacing() -> UIView { let spacing = UIView() spacing.clipsToBounds = true spacing.backgroundColor = .clear spacing.setContentCompressionResistancePriority(1, for: .horizontal) spacing.setContentCompressionResistancePriority(1, for: .vertical) return add(view: spacing) } // MARK: Stacks @discardableResult public func addStack(axis: UILayoutConstraintAxis = .horizontal, alignment: UIStackViewAlignment = .fill, distribution: UIStackViewDistribution = .fill, spacing: CGFloat = LayoutDefaults.spacing, create: ((Layout) -> Void)?) -> Layout { let group = Layout() group.axis = axis group.alignment = alignment group.distribution = distribution group.spacing = spacing add(view: group) if let c = create { c(group) } return group } }
mit
d77af80ff219c2ed400878bd92a8a1a4
26.761628
272
0.587016
5.241493
false
false
false
false
brian-tran16/Fusuma
Sources/FSVideoCameraView.swift
1
12489
// // FSVideoCameraView.swift // Fusuma // // Created by Brendan Kirchner on 3/18/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import AVFoundation @objc protocol FSVideoCameraViewDelegate: class { func videoFinished(withFileURL fileURL: URL) } final class FSVideoCameraView: UIView { @IBOutlet weak var previewViewContainer: UIView! @IBOutlet weak var shotButton: UIButton! @IBOutlet weak var flashButton: UIButton! @IBOutlet weak var flipButton: UIButton! weak var delegate: FSVideoCameraViewDelegate? = nil var session: AVCaptureSession? var device: AVCaptureDevice? var videoInput: AVCaptureDeviceInput? var videoOutput: AVCaptureMovieFileOutput? var focusView: UIView? var flashOffImage: UIImage? var flashOnImage: UIImage? var videoStartImage: UIImage? var videoStopImage: UIImage? fileprivate var isRecording = false static func instance() -> FSVideoCameraView { return UINib(nibName: "FSVideoCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSVideoCameraView } func initialize() { if session != nil { return } self.backgroundColor = fusumaBackgroundColor self.isHidden = false // AVCapture session = AVCaptureSession() for device in AVCaptureDevice.devices() { if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back { self.device = device } } do { if let session = session { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) videoOutput = AVCaptureMovieFileOutput() let totalSeconds = 60.0 //Total Seconds of capture time let timeScale: Int32 = 30 //FPS let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale) videoOutput?.maxRecordedDuration = maxDuration videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024 //SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME if session.canAddOutput(videoOutput) { session.addOutput(videoOutput) } let videoLayer = AVCaptureVideoPreviewLayer(session: session) videoLayer?.frame = self.previewViewContainer.bounds videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill self.previewViewContainer.layer.addSublayer(videoLayer!) session.startRunning() } // Focus View self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90)) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(FSVideoCameraView.focus(_:))) self.previewViewContainer.addGestureRecognizer(tapRecognizer) } catch { } let bundle = Bundle(for: self.classForCoder) flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil) flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil) let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil) videoStartImage = fusumaVideoStartImage != nil ? fusumaVideoStartImage : UIImage(named: "video_button", in: bundle, compatibleWith: nil) videoStopImage = fusumaVideoStopImage != nil ? fusumaVideoStopImage : UIImage(named: "video_button_rec", in: bundle, compatibleWith: nil) if(fusumaTintIcons) { flashButton.tintColor = fusumaBaseTintColor flipButton.tintColor = fusumaBaseTintColor shotButton.tintColor = fusumaBaseTintColor flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) shotButton.setImage(videoStartImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) } else { flashButton.setImage(flashOffImage, for: UIControlState()) flipButton.setImage(flipImage, for: UIControlState()) shotButton.setImage(videoStartImage, for: UIControlState()) } flashConfiguration() self.startCamera() } deinit { NotificationCenter.default.removeObserver(self) } func startCamera() { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == AVAuthorizationStatus.authorized { session?.startRunning() } else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted { session?.stopRunning() } } func stopCamera() { if self.isRecording { self.toggleRecording() } session?.stopRunning() } @IBAction func shotButtonPressed(_ sender: UIButton) { self.toggleRecording() } fileprivate func toggleRecording() { guard let videoOutput = videoOutput else { return } self.isRecording = !self.isRecording let shotImage: UIImage? if self.isRecording { shotImage = videoStopImage } else { shotImage = videoStartImage } self.shotButton.setImage(shotImage, for: UIControlState()) if self.isRecording { let outputPath = "\(NSTemporaryDirectory())output.mov" let outputURL = URL(fileURLWithPath: outputPath) let fileManager = FileManager.default if fileManager.fileExists(atPath: outputPath) { do { try fileManager.removeItem(atPath: outputPath) } catch { print("error removing item at path: \(outputPath)") self.isRecording = false return } } self.flipButton.isEnabled = false self.flashButton.isEnabled = false videoOutput.startRecording(toOutputFileURL: outputURL, recordingDelegate: self) } else { videoOutput.stopRecording() self.flipButton.isEnabled = true self.flashButton.isEnabled = true } return } @IBAction func flipButtonPressed(_ sender: UIButton) { session?.stopRunning() do { session?.beginConfiguration() if let session = session { for input in session.inputs { session.removeInput(input as! AVCaptureInput) } let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) { if let device = device as? AVCaptureDevice , device.position == position { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) } } } session?.commitConfiguration() } catch { } session?.startRunning() } @IBAction func flashButtonPressed(_ sender: UIButton) { do { if let device = device { try device.lockForConfiguration() let mode = device.flashMode if mode == AVCaptureFlashMode.off { device.flashMode = AVCaptureFlashMode.on flashButton.setImage(flashOnImage, for: UIControlState()) } else if mode == AVCaptureFlashMode.on { device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) } device.unlockForConfiguration() } } catch _ { flashButton.setImage(flashOffImage, for: UIControlState()) return } } } extension FSVideoCameraView: AVCaptureFileOutputRecordingDelegate { func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) { print("started recording to: \(fileURL)") } func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { print("finished recording to: \(outputFileURL)") self.delegate?.videoFinished(withFileURL: outputFileURL) } } extension FSVideoCameraView { func focus(_ recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: self) let viewsize = self.bounds.size let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width) let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { try device?.lockForConfiguration() } catch _ { return } if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true { device?.focusMode = AVCaptureFocusMode.autoFocus device?.focusPointOfInterest = newPoint } if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true { device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure device?.exposurePointOfInterest = newPoint } device?.unlockForConfiguration() self.focusView?.alpha = 0.0 self.focusView?.center = point self.focusView?.backgroundColor = UIColor.clear self.focusView?.layer.borderColor = UIColor.black.cgColor self.focusView?.layer.borderWidth = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.addSubview(self.focusView!) UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState animations: { self.focusView!.alpha = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) }, completion: {(finished) in self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.focusView!.removeFromSuperview() }) } func flashConfiguration() { do { if let device = device { try device.lockForConfiguration() device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) device.unlockForConfiguration() } } catch _ { return } } }
mit
e46f10dd68cdf12cb4b7bc315caf105f
33.213699
163
0.558536
6.36818
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
weibo/weibo/Classes/Home/View/Cell/HomeTableViewCell.swift
1
3633
// // HomeTableViewCell.swift // weibo // // Created by mada on 15/10/10. // Copyright © 2015年 MD. All rights reserved. // import UIKit import SnapKit import SDWebImage public enum JSJCellReusableIdentifier : String { case normalCell = "normalCell" case forwardCell = "forwardCell" /** 根据对应的模型返回对应cell的唯一标识 */ static func reusableIdentifier(status: Status) -> String { // .rawValue用于获取枚举的原始值 return status.retweeted_status != nil ? JSJCellReusableIdentifier.forwardCell.rawValue : JSJCellReusableIdentifier.normalCell.rawValue } } class HomeTableViewCell: UITableViewCell { var status: Status? { didSet{ // 设置顶部视图数据 topView.status = status // 设置正文 contentLabel.text = status?.text // 配置配图 pictureView.status = status } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // 设置子控件 setupChildUI() } func setupChildUI() { // 添加子控件 contentView.addSubview(topView) contentView.addSubview(contentLabel) contentView.addSubview(pictureView) contentView.addSubview(footBarView) /* 布局子控件 */ // 布局头部控件 topView.snp_makeConstraints { (make) -> Void in make.left.equalTo(contentView) make.top.equalTo(contentView) make.right.equalTo(contentView) } // 布局微博内容 contentLabel.snp_makeConstraints { (make) -> Void in make.left.equalTo(topView).offset(10) make.top.equalTo(topView.snp_bottom).offset(15) make.width.equalTo(UIScreen.mainScreen().bounds.width - 20) } // 布局配图 // pictureView.snp_makeConstraints { (make) -> Void in // make.left.equalTo(contentLabel) // make.top.equalTo(contentLabel.snp_bottom).offset(10) // } // 布局底部条 footBarView.snp_makeConstraints { (make) -> Void in make.top.equalTo(pictureView.snp_bottom).offset(10) // make.bottom.equalTo(contentView.snp_bottom).offset(-10) make.height.equalTo(44) make.left.equalTo(contentView) make.right.equalTo(contentView) } } // 计算cell的高度 func rowHeight(status: Status) -> CGFloat { // 先给微博模型赋值 self.status = status // 强制更新 layoutIfNeeded() // 返回底部最大视图 return CGRectGetMaxY(footBarView.frame) } // MARK: - 懒加载 // 头部 private lazy var topView: HomeStatusTopView = HomeStatusTopView() // 正文 lazy var contentLabel: UILabel = { let label = UILabel() label.text = "银河系漫游权威指南" label.numberOfLines = 0 return label }() // 配图 lazy var pictureView: HomeStatusPictureView = HomeStatusPictureView() // 底部条 private lazy var footBarView: HomeStatusFooterView = { let footBar = HomeStatusFooterView() footBar.backgroundColor = UIColor.lightGrayColor() return footBar }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
e8661c20a0aac4f8101e28a133b88638
25.421875
143
0.583974
4.533512
false
false
false
false
pksprojects/ElasticSwift
Sources/ElasticSwiftQueryDSL/Queries/SpanQueries.swift
1
23492
// // SpanQueries.swift // ElasticSwift // // Created by Prafull Kumar Soni on 4/14/18. // import ElasticSwiftCore import Foundation // MARK: - Span Query public protocol SpanQuery: Query {} // MARK: - Span Term Query public struct SpanTermQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanTerm public let field: String public let value: String public var name: String? public var boost: Decimal? public init(field: String, value: String, boost: Decimal? = nil, name: String? = nil) { self.field = field self.value = value self.boost = boost self.name = name } internal init(withBuilder builder: SpanTermQueryBuilder) throws { guard builder.field != nil else { throw QueryBuilderError.missingRequiredField("field") } guard builder.value != nil else { throw QueryBuilderError.missingRequiredField("value") } self.init(field: builder.field!, value: builder.value!, boost: builder.boost, name: builder.name) } } public extension SpanTermQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard nested.allKeys.count == 1 else { throw Swift.DecodingError.typeMismatch(SpanTermQuery.self, .init(codingPath: nested.codingPath, debugDescription: "Unable to find field name in key(s) expect: 1 key found: \(nested.allKeys.count).")) } field = nested.allKeys.first!.stringValue if let fieldContainer = try? nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) { if fieldContainer.allKeys.contains(.term) { value = try fieldContainer.decodeString(forKey: .term) } else { value = try fieldContainer.decodeString(forKey: .value) } boost = try fieldContainer.decodeDecimalIfPresent(forKey: .boost) name = try fieldContainer.decodeStringIfPresent(forKey: .name) } else { value = try nested.decodeString(forKey: .key(named: field)) boost = nil name = nil } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: .key(named: queryType)) guard boost != nil else { try nested.encode(value, forKey: .key(named: field)) return } var fieldContainer = nested.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: field)) try fieldContainer.encode(value, forKey: .value) try fieldContainer.encodeIfPresent(boost, forKey: .boost) try fieldContainer.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case value case term case boost case name } } extension SpanTermQuery: Equatable { public static func == (lhs: SpanTermQuery, rhs: SpanTermQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.field == rhs.field && lhs.value == rhs.value && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span Multi Term Query public struct SpanMultiTermQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanMulti public let match: MultiTermQuery public var boost: Decimal? public var name: String? public init(_ match: MultiTermQuery, boost: Decimal? = nil, name: String? = nil) { self.match = match self.boost = boost self.name = name } internal init(withBuilder builder: SpanMultiTermQueryBuilder) throws { guard let match = builder.match else { throw QueryBuilderError.missingRequiredField("match") } self.init(match, boost: builder.boost, name: builder.name) } } public extension SpanMultiTermQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) guard let multiTermQuery = try nested.decodeQuery(forKey: .match) as? MultiTermQuery else { throw Swift.DecodingError.dataCorruptedError(forKey: .match, in: nested, debugDescription: "Unable to decode MultiTermQuery") } match = multiTermQuery boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(match, forKey: .match) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case match case boost case name } } extension SpanMultiTermQuery: Equatable { public static func == (lhs: SpanMultiTermQuery, rhs: SpanMultiTermQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.match.isEqualTo(rhs.match) && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span First Query public struct SpanFirstQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanFirst public let match: SpanQuery public let end: Int public var boost: Decimal? public var name: String? public init(_ match: SpanQuery, end: Int, boost: Decimal? = nil, name: String? = nil) { self.match = match self.end = end self.boost = boost self.name = name } internal init(withBuilder builder: SpanFirstQueryBuilder) throws { guard let match = builder.match else { throw QueryBuilderError.missingRequiredField("match") } guard let end = builder.end else { throw QueryBuilderError.missingRequiredField("end") } self.init(match, end: end, boost: builder.boost, name: builder.name) } } public extension SpanFirstQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) end = try nested.decodeInt(forKey: .end) let query = try nested.decodeQuery(forKey: .match) guard let spanQuery = query as? SpanQuery else { throw Swift.DecodingError.dataCorruptedError(forKey: .match, in: nested, debugDescription: "Unable to decode SpanQuery") } match = spanQuery boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(match, forKey: .match) try nested.encode(end, forKey: .end) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case match case end case boost case name } } extension SpanFirstQuery: Equatable { public static func == (lhs: SpanFirstQuery, rhs: SpanFirstQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.match.isEqualTo(rhs.match) && lhs.end == rhs.end && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span Near Query public struct SpanNearQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanNear public let clauses: [SpanQuery] public var slop: Int? public var inOrder: Bool? public var boost: Decimal? public var name: String? public init(_ clauses: [SpanQuery], slop: Int? = nil, inOrder: Bool? = nil, boost: Decimal? = nil, name: String? = nil) { self.clauses = clauses self.slop = slop self.inOrder = inOrder self.boost = boost self.name = name } public init(_ clauses: SpanQuery..., slop: Int? = nil, inOrder: Bool? = nil, boost: Decimal? = nil, name: String? = nil) { self.init(clauses, slop: slop, inOrder: inOrder, boost: boost, name: name) } internal init(withBuilder builder: SpanNearQueryBuilder) throws { guard let clauses = builder.clauses, !clauses.isEmpty else { throw QueryBuilderError.atlestOneElementRequired("clauses") } self.init(clauses, slop: builder.slop, inOrder: builder.inOrder, boost: builder.boost, name: builder.name) } } public extension SpanNearQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) let queries = try nested.decodeQueries(forKey: .clauses) guard let spanQueries = queries as? [SpanQuery] else { throw Swift.DecodingError.dataCorruptedError(forKey: .clauses, in: nested, debugDescription: "Unable to decode SpanQueries") } clauses = spanQueries slop = try nested.decodeIntIfPresent(forKey: .slop) inOrder = try nested.decodeBoolIfPresent(forKey: .inOrder) boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(clauses, forKey: .clauses) try nested.encodeIfPresent(slop, forKey: .slop) try nested.encodeIfPresent(inOrder, forKey: .inOrder) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case clauses case slop case inOrder = "in_order" case boost case name } } extension SpanNearQuery: Equatable { public static func == (lhs: SpanNearQuery, rhs: SpanNearQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.slop == rhs.slop && lhs.inOrder == rhs.inOrder && lhs.clauses.count == rhs.clauses.count && !zip(lhs.clauses, rhs.clauses).contains { !$0.isEqualTo($1) } && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span Or Query public struct SpanOrQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanOr public let clauses: [SpanQuery] public var boost: Decimal? public var name: String? public init(_ clauses: [SpanQuery], boost: Decimal? = nil, name: String? = nil) { self.clauses = clauses self.boost = boost self.name = name } internal init(withBuilder builder: SpanOrQueryBuilder) throws { guard let clauses = builder.clauses, !clauses.isEmpty else { throw QueryBuilderError.atlestOneElementRequired("clauses") } self.init(clauses, boost: builder.boost, name: builder.name) } } public extension SpanOrQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) let queries = try nested.decodeQueries(forKey: .clauses) guard let spanQueries = queries as? [SpanQuery] else { throw Swift.DecodingError.dataCorruptedError(forKey: .clauses, in: nested, debugDescription: "Unable to decode SpanQueries") } clauses = spanQueries boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(clauses, forKey: .clauses) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case clauses case boost case name } } extension SpanOrQuery: Equatable { public static func == (lhs: SpanOrQuery, rhs: SpanOrQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.clauses.count == rhs.clauses.count && !zip(lhs.clauses, rhs.clauses).contains { !$0.isEqualTo($1) } && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span Not Query public struct SpanNotQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanNot public let include: SpanQuery public let exclude: SpanQuery public var pre: Int? public var post: Int? public var boost: Decimal? public var name: String? public init(include: SpanQuery, exclude: SpanQuery, pre: Int? = nil, post: Int? = nil, boost: Decimal? = nil, name: String? = nil) { self.include = include self.exclude = exclude self.pre = pre self.post = post self.boost = boost self.name = name } internal init(withBuilder builder: SpanNotQueryBuilder) throws { guard let include = builder.include else { throw QueryBuilderError.missingRequiredField("include") } guard let exclude = builder.exclude else { throw QueryBuilderError.missingRequiredField("exclude") } self.init(include: include, exclude: exclude, pre: builder.pre, post: builder.post, boost: builder.boost, name: builder.name) } } public extension SpanNotQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) include = try nested.decodeQuery(forKey: .include) as! SpanQuery exclude = try nested.decodeQuery(forKey: .exclude) as! SpanQuery if nested.allKeys.contains(.dist) { let dist = try nested.decodeInt(forKey: .dist) pre = dist post = dist } else { pre = try nested.decodeIntIfPresent(forKey: .pre) post = try nested.decodeIntIfPresent(forKey: .post) } boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(include, forKey: .include) try nested.encode(exclude, forKey: .exclude) try nested.encodeIfPresent(pre, forKey: .pre) try nested.encodeIfPresent(post, forKey: .post) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case include case exclude case pre case post case dist case boost case name } } extension SpanNotQuery: Equatable { public static func == (lhs: SpanNotQuery, rhs: SpanNotQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.include.isEqualTo(rhs.include) && lhs.exclude.isEqualTo(rhs.exclude) && lhs.pre == rhs.pre && lhs.post == rhs.post && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span Containing Query public struct SpanContainingQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanContaining public let big: SpanQuery public let little: SpanQuery public var boost: Decimal? public var name: String? public init(big: SpanQuery, little: SpanQuery, boost: Decimal? = nil, name: String? = nil) { self.big = big self.little = little self.boost = boost self.name = name } internal init(withBuilder builder: SpanContainingQueryBuilder) throws { guard let big = builder.big else { throw QueryBuilderError.missingRequiredField("big") } guard let little = builder.little else { throw QueryBuilderError.missingRequiredField("little") } self.init(big: big, little: little, boost: builder.boost, name: builder.name) } } public extension SpanContainingQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) big = try nested.decodeQuery(forKey: .big) as! SpanQuery little = try nested.decodeQuery(forKey: .little) as! SpanQuery boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(big, forKey: .big) try nested.encode(little, forKey: .little) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case big case little case boost case name } } extension SpanContainingQuery: Equatable { public static func == (lhs: SpanContainingQuery, rhs: SpanContainingQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.big.isEqualTo(rhs.big) && lhs.little.isEqualTo(rhs.little) && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span Within Query public struct SpanWithinQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanWithin public let big: SpanQuery public let little: SpanQuery public var boost: Decimal? public var name: String? public init(big: SpanQuery, little: SpanQuery, boost _: Decimal? = nil, name _: String? = nil) { self.big = big self.little = little } internal init(withBuilder builder: SpanWithinQueryBuilder) throws { guard let big = builder.big else { throw QueryBuilderError.missingRequiredField("big") } guard let little = builder.little else { throw QueryBuilderError.missingRequiredField("little") } self.init(big: big, little: little, boost: builder.boost, name: builder.name) } } public extension SpanWithinQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) big = try nested.decodeQuery(forKey: .big) as! SpanQuery little = try nested.decodeQuery(forKey: .little) as! SpanQuery } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(big, forKey: .big) try nested.encode(little, forKey: .little) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case big case little case boost case name } } extension SpanWithinQuery: Equatable { public static func == (lhs: SpanWithinQuery, rhs: SpanWithinQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.big.isEqualTo(rhs.big) && lhs.little.isEqualTo(rhs.little) && lhs.boost == rhs.boost && lhs.name == rhs.name } } // MARK: - Span Field Masking Query public struct SpanFieldMaskingQuery: SpanQuery { public let queryType: QueryType = QueryTypes.spanFieldMasking public let query: SpanQuery public let field: String public var boost: Decimal? public var name: String? public init(field: String, query: SpanQuery, boost: Decimal? = nil, name: String? = nil) { self.field = field self.query = query self.boost = boost self.name = name } internal init(withBuilder builder: SpanFieldMaskingQueryBuilder) throws { guard let query = builder.query else { throw QueryBuilderError.missingRequiredField("query") } guard let field = builder.field else { throw QueryBuilderError.missingRequiredField("field") } self.init(field: field, query: query, boost: builder.boost, name: builder.name) } } public extension SpanFieldMaskingQuery { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DynamicCodingKeys.self) let nested = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) query = try nested.decodeQuery(forKey: .query) as! SpanQuery field = try nested.decodeString(forKey: .field) boost = try nested.decodeDecimalIfPresent(forKey: .boost) name = try nested.decodeStringIfPresent(forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DynamicCodingKeys.self) var nested = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .key(named: queryType)) try nested.encode(query, forKey: .query) try nested.encode(field, forKey: .field) try nested.encodeIfPresent(boost, forKey: .boost) try nested.encodeIfPresent(name, forKey: .name) } internal enum CodingKeys: String, CodingKey { case field case query case boost case name } } extension SpanFieldMaskingQuery: Equatable { public static func == (lhs: SpanFieldMaskingQuery, rhs: SpanFieldMaskingQuery) -> Bool { return lhs.queryType.isEqualTo(rhs.queryType) && lhs.query.isEqualTo(rhs.query) && lhs.field == rhs.field && lhs.boost == rhs.boost && lhs.name == rhs.name } }
mit
edea32eb42744278a664c3150db16338
35.5919
211
0.651754
4.333518
false
false
false
false
daaavid/TIY-Assignments
34--Contacts/Contacts/Contacts/MainViewController.swift
1
14434
// // ViewController.swift // Contacts // // Created by david on 11/20/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import RealmSwift protocol ContactsProtocol { func profileWasChosen(chosenProfile: Contact) func profileWasChosenForDeletion(chosenProfile: Contact) } var youName = "David" var firstContact = false var contacts: Results <Contact>! class MainViewController: UIViewController, UISearchBarDelegate, ContactsProtocol, UITextFieldDelegate { @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var containerView: UIView! @IBOutlet weak var addContactButtonView: UIView! @IBOutlet weak var editContactButtonView: UIView! @IBOutlet weak var editButton: UIButton! @IBOutlet weak var navLabel: UILabel! let realm = try! Realm() var chosenContact: Contact? var currentCreateAction: UIAlertAction! var validName = false var newContact = false weak var currentViewController: UIViewController? override func viewDidLoad() { super.viewDidLoad() contacts = realm.objects(Contact).sorted("name") if contacts.first != nil { segmentChanged(segmentedControl) } else { firstContact = true segmentedControl.hidden = true addContact() } } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { manageChildContents(true) } //MARK: - Action Handlers @IBAction func segmentChanged(sender: UISegmentedControl) { sender.setTitle("You", forSegmentAtIndex: 2) switch sender.selectedSegmentIndex { case 0: manageNavLabelAndSearchBar("Contacts") cycleViewController("Contacts") case 1: manageNavLabelAndSearchBar("Favorites") cycleViewController("Contacts") case 2: manageNavLabelAndSearchBar("Profile") cycleViewController("Profile") default: print("nothing to see here") } } @IBAction func addButtonTapped(sender: UIButton) { addContact() } //MARK: - Editing @IBAction func editButtonTapped(sender: UIButton) { if let contactsVC = self.childViewControllers[0] as? ContactsViewController { contactsVC.delegate = self let tableView = contactsVC.tableView let edit = !tableView.editing tableView.editing = edit let spinView = self.editContactButtonView spinView.rotate360Degrees() tableView.alpha = 0.4 UIView.animateWithDuration(0.4, animations: { () -> Void in tableView.alpha = 1 }) } } func profileWasChosenForDeletion(chosenProfile: Contact) { if chosenProfile.name != youName { try! realm.write { () -> Void in self.realm.delete(chosenProfile) } } editButtonTapped(editButton) cycleViewController("Contacts") } //MARK: - Child VCs and subviews func cycleViewController(identifier: String) { manageAddButtonView(identifier) let newVC = storyboard!.instantiateViewControllerWithIdentifier(identifier) newVC.view.translatesAutoresizingMaskIntoConstraints = false addChildViewController(newVC) addSubview(newVC.view, toView: containerView) newVC.view.alpha = 0 UIView.animateWithDuration(0.4, animations: { () -> Void in newVC.view.alpha = 1 if let currentVC = self.currentViewController { currentVC.view.alpha = 0 currentVC.view.removeFromSuperview() currentVC.removeFromParentViewController() } } ) currentViewController = newVC if !newContact { manageChildContents(false) } } func addSubview(subView: UIView, toView parentView: UIView) { parentView.addSubview(subView) var viewBindingsDict = [String: AnyObject]() viewBindingsDict["subView"] = subView parentView .addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) parentView .addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) } //MARK: - Manage Content func profileWasChosen(chosenProfile: Contact) { print("profileWasChosen") chosenContact = chosenProfile segmentedControl.selectedSegmentIndex = 2 segmentChanged(segmentedControl) } func manageChildContents(isSearch: Bool) { if let contactsVC = self.childViewControllers[0] as? ContactsViewController { contactsVC.delegate = self contactsVC.shownContacts.removeAll() switch segmentedControl.selectedSegmentIndex { case 0: //Contacts if isSearch { for contact in contacts { if searchBar.text != "" && contact.name.lowercaseString.containsString(searchBar.text!.lowercaseString) { contactsVC.shownContacts.append(contact) } else if searchBar.text == "" { contactsVC.shownContacts.append(contact) } } } else { for contact in contacts { contactsVC.shownContacts.append(contact) } } case 1: //Favorites if isSearch { for contact in contacts { if searchBar.text != "" && contact.favorite && contact.name.lowercaseString.containsString(searchBar.text!.lowercaseString) { contactsVC.shownContacts.append(contact) } else if searchBar.text == "" && contact.favorite { contactsVC.shownContacts.append(contact) } } } else { for contact in contacts { if contact.favorite { contactsVC.shownContacts.append(contact) } } } default: print("wrong vc.") } contactsVC.tableView.reloadData() } else if let profileVC = self.childViewControllers[0] as? ProfileViewController { //this code sucks if let _ = chosenContact { profileVC.contact = chosenContact let title = chosenContact!.name.componentsSeparatedByString(" ")[0] if title != youName { segmentedControl.setTitle(title, forSegmentAtIndex: 2) } profileVC.setContact() } else if !profileVC.newContact { let contacts = realm.objects(Contact).filter("name == %@", youName) profileVC.contact = contacts.first profileVC.setContact() } self.chosenContact = nil } } func manageAddButtonView(identifier: String) { if identifier != "Profile" { if addContactButtonView.hidden { self.addContactButtonView.hidden = false self.editContactButtonView.hidden = false self.addContactButtonView.alpha = 0 self.editContactButtonView.alpha = 0 UIView.animateWithDuration(0.4, animations: { () -> Void in self.addContactButtonView.alpha = 1 self.editContactButtonView.alpha = 1 } ) } } else { self.addContactButtonView.hidden = true self.editContactButtonView.hidden = true } } func manageNavLabelAndSearchBar(text: String) { self.navLabel.text = text self.navLabel.alpha = 0 self.navLabel.center.x -= self.navLabel.frame.width UIView.animateWithDuration(0.25) { () -> Void in self.navLabel.alpha = 1 self.navLabel.center.x += self.navLabel.frame.width } searchBar.resignFirstResponder() let searchTextField = searchBar.valueForKey("searchField") as! UITextField if text == "Profile" { searchBar.text = "" searchBar.alpha = 0.8 searchTextField.enabled = false } else { searchTextField.enabled = true searchBar.alpha = 1 } } //MARK: - Add Friend func addContact() { newContact = true cycleViewController("Profile") if let profileVC = self.childViewControllers[0] as? ProfileViewController { profileVC.newContact = true profileVC.editContact() segmentedControl.selectedSegmentIndex = 2 segmentedControl.setTitle("New", forSegmentAtIndex: 2) } newContact = false } //MARK: - Deprecated func ContactNameFieldDidChange(sender: UITextField) { /* let validator = Validator() if validator.validate("name", string: sender.text!) { validName = true } else { validName = false } */ } /* func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { //http://stackoverflow.com/questions/27609104/xcode-swift-formatting-text-as-phone-number if textField == textField.viewWithTag(2) as! UITextField { let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) let decimalString = components.joinWithSeparator("") as NSString let length = decimalString.length let hasLeadingOne = length > 0 && decimalString.characterAtIndex(0) == (1 as unichar) if length == 0 || (length > 10 && !hasLeadingOne) || length > 11 { let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int return (newLength > 10) ? false : true } var index = 0 let formattedString = NSMutableString() if hasLeadingOne { formattedString.appendString("1 ") index += 1 } if (length - index) > 3 { let areaCode = decimalString.substringWithRange(NSMakeRange(index, 3)) formattedString.appendFormat("(%@) ", areaCode) index += 3 } if length - index > 3 { let prefix = decimalString.substringWithRange(NSMakeRange(index, 3)) formattedString.appendFormat("%@-", prefix) index += 3 } let remainder = decimalString.substringFromIndex(index) formattedString.appendString(remainder) textField.text = formattedString as String let validator = Validator() if validator.validate("phone", string: textField.text!) && validName { self.currentCreateAction.enabled = true } return false } else { print("else") return true } } */ func alertController() { /* let alertController = UIAlertController(title: "Add Contact", message: "Add some info for this contact.", preferredStyle: .Alert) // .Alert and .ActionSheet currentCreateAction = UIAlertAction(title: "Create", style: .Default) { (action) -> Void in let newContact = Contact() let name = alertController.textFields?.first?.text let number = alertController.textFields?[1].text newContact.name = name! newContact.number = number! try! self.realm.write({ () -> Void in self.realm.add(newContact) self.cycleViewController("Contacts") self.validName = false }) } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alertController.addAction(cancelAction) alertController.addAction(currentCreateAction) currentCreateAction.enabled = false alertController.addTextFieldWithConfigurationHandler{ (textField) -> Void in textField.placeholder = "Name" textField.tag = 1 textField.addTarget(self, action: "ContactNameFieldDidChange:", forControlEvents: .EditingChanged) } alertController.addTextFieldWithConfigurationHandler{ (textField) -> Void in textField.placeholder = "Number" textField.tag = 2 textField.delegate = self } self.presentViewController(alertController, animated: true, completion: nil) */ } }
cc0-1.0
85b45cc44b553819fabf7bbb3256d93c
30.5131
147
0.542784
5.738767
false
false
false
false
madcato/OSFramework
Sources/OSFramework/Observable.swift
1
2141
// // Observable.swift // TestObservable // // Created by Daniel Vela on 13/03/2018. // Copyright © 2018 veladan. All rights reserved. // // // https://colindrake.me/post/an-observable-pattern-implementation-in-swift/ // typealias ObserverBlock<T> = (_ newValue: T, _ oldValue: T) -> Void protocol ObservableProtocol { associatedtype AType var value: AType { get set } func subscribe(_ observer: AnyObject, block: @escaping ObserverBlock<AType>) func unsubscribe(_ observer: AnyObject) } /*! Observable class pattern Sample implementation: class ConcreteImplementation2 { func run() { let initial = 3 var v = initial let obs = Observable(initial) obs.subscribe(self) { (newValue, oldValue) in print("Object updated!") v = newValue } obs.onChange { (newValue, oldValue) in print("Object changed!") } obs.value = 4 // Trigger update. print(v) // 4! } } */ public final class Observable<T>: ObservableProtocol { typealias ObserversEntry = (observer: AnyObject, block: ObserverBlock<T>) var value: T { didSet { observers.forEach { (entry) in let (_, block) = entry block(value, oldValue) } } } var observers: [ObserversEntry] = [] init(_ value: T) { self.value = value } /// If you use this method, object can't be unsubscribed func onChange(block: @escaping ObserverBlock<T>) { subscribe(Observable<Int>(0), block: block) } func subscribe(_ observer: AnyObject, block: @escaping ObserverBlock<T>) { let entry: ObserversEntry = (observer: observer, block: block) observers.append(entry) } func unsubscribe(_ observer: AnyObject) { observers = observers.filter { entry in let (owner, _) = entry return owner !== observer } } static func << <T>(_ this: Observable<T>, _ value: T) { this.value = value } }
mit
d751e613d89ad21e0457df9788b31726
26.792208
80
0.570093
4.349593
false
false
false
false
Pluto-Y/SwiftyEcharts
iOS_Example/DemoControllers/BaseDemoController.swift
1
2358
// // BaseDemoController.swift // SwiftyEcharts // // Created by Pluto Y on 25/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import UIKit import SwiftyEcharts class BaseDemoController: UIViewController, UITableViewDelegate, UITableViewDataSource { var menuTableView: UITableView! var echartsView: EchartsView! var option: Option! { didSet { echartsView.option = option echartsView.loadEcharts() } } var menus: [String] = [] var optionClosures: [() -> Option] = [] override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white let width = self.view.frame.width let height = self.view.frame.height menuTableView = UITableView(frame: CGRect(x: 0, y: 0, width: width, height: height - 300)) menuTableView.delegate = self menuTableView.dataSource = self menuTableView.register(UITableViewCell.self, forCellReuseIdentifier: "DemoCell") self.view.addSubview(menuTableView) let line = UIView(frame: CGRect(x: 0, y: height - 300, width: width, height: 1)) line.backgroundColor = UIColor(red: 239/255.0, green: 239/255.0, blue: 245/255.0, alpha: 1.0) self.view.addSubview(line) echartsView = EchartsView(frame: CGRect(x: 0, y: height - 299, width: width, height: 300)) self.view.addSubview(echartsView!) Mapper.ignoreNil = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) option = optionClosures[0]() } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menus.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DemoCell", for: indexPath) cell.textLabel?.text = menus[indexPath.row] cell.selectionStyle = .none return cell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { echartsView.reset() option = optionClosures[indexPath.row]() } }
mit
930f64f49992526f38dbd660df6529ba
31.287671
101
0.638524
4.541426
false
false
false
false
lstomberg/swift-PerformanceTestKit
Sources/Extensions/Codable.swift
1
687
// // Created by Lucas Stomberg on 3/3/18. // Copyright © 2018 Epic. All rights reserved. // import Foundation //: Decodable Extension public extension Decodable { // example let people = try [Person].decode(JSONData: data) static func decode(fromJSON data: Data) throws -> Self { let decoder: JSONDecoder = JSONDecoder() return try decoder.decode(Self.self, from: data) } } //: Encodable Extension public extension Encodable { //example let jsonData = try people.encode() func encodeJSON() throws -> Data { let encoder: JSONEncoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted return try encoder.encode(self) } }
mit
9206bc6d8a82be28ed0f1cc51f617362
21.129032
62
0.682216
4.182927
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Browser/Tabs/TabTableViewCell.swift
1
4459
/* 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 UIKit import Shared import SnapKit class TabTableViewCell: UITableViewCell, Themeable { static let identifier = "tabCell" var screenshotView: UIImageView? var websiteTitle: UILabel? var urlLabel: UILabel? lazy var closeButton: UIButton = { let button = UIButton() button.setImage(UIImage.templateImageNamed("tab_close"), for: []) button.accessibilityIdentifier = "closeTabButtonTabTray" button.tintColor = UIColor.theme.tabTray.cellCloseButton button.sizeToFit() return button }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) guard let imageView = imageView, let title = textLabel, let label = detailTextLabel else { return } self.screenshotView = imageView self.websiteTitle = title self.urlLabel = label viewSetup() applyTheme() } private func viewSetup() { guard let websiteTitle = websiteTitle, let screenshotView = screenshotView, let urlLabel = urlLabel else { return } screenshotView.contentMode = .scaleAspectFill screenshotView.clipsToBounds = true screenshotView.layer.cornerRadius = TabTrayV2ControllerUX.cornerRadius screenshotView.layer.borderWidth = 1 screenshotView.layer.borderColor = UIColor.Photon.Grey30.cgColor screenshotView.snp.makeConstraints { make in make.height.width.equalTo(100) make.leading.equalToSuperview().offset(TabTrayV2ControllerUX.screenshotMarginLeftRight) make.top.equalToSuperview().offset(TabTrayV2ControllerUX.screenshotMarginTopBottom) make.bottom.equalToSuperview().offset(-TabTrayV2ControllerUX.screenshotMarginTopBottom) } websiteTitle.numberOfLines = 2 websiteTitle.snp.makeConstraints { make in make.leading.equalTo(screenshotView.snp.trailing).offset(TabTrayV2ControllerUX.screenshotMarginLeftRight) make.top.equalToSuperview().offset(TabTrayV2ControllerUX.textMarginTopBottom) make.bottom.equalTo(urlLabel.snp.top) make.trailing.equalToSuperview().offset(-16) } urlLabel.snp.makeConstraints { make in make.leading.equalTo(screenshotView.snp.trailing).offset(TabTrayV2ControllerUX.screenshotMarginLeftRight) make.trailing.equalToSuperview() make.top.equalTo(websiteTitle.snp.bottom).offset(3) make.bottom.equalToSuperview().offset(-TabTrayV2ControllerUX.textMarginTopBottom * CGFloat(websiteTitle.numberOfLines)) } } // Helper method to remake title constraint func remakeTitleConstraint() { guard let websiteTitle = websiteTitle, let text = websiteTitle.text, !text.isEmpty, let screenshotView = screenshotView, let urlLabel = urlLabel else { return } websiteTitle.numberOfLines = 2 websiteTitle.snp.remakeConstraints { make in make.leading.equalTo(screenshotView.snp.trailing).offset(TabTrayV2ControllerUX.screenshotMarginLeftRight) make.top.equalToSuperview().offset(TabTrayV2ControllerUX.textMarginTopBottom) make.bottom.equalTo(urlLabel.snp.top) make.trailing.equalToSuperview().offset(-16) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() applyTheme() } func applyTheme() { if #available(iOS 13.0, *) { backgroundColor = UIColor.secondarySystemGroupedBackground textLabel?.textColor = UIColor.label detailTextLabel?.textColor = UIColor.secondaryLabel closeButton.tintColor = UIColor.secondaryLabel } else { backgroundColor = UIColor.theme.tableView.rowBackground textLabel?.textColor = UIColor.theme.tableView.rowText detailTextLabel?.textColor = UIColor.theme.tableView.rowDetailText closeButton.tintColor = UIColor.theme.tabTray.cellCloseButton } } }
mpl-2.0
fce5d6e6e3e5512f78fe0e705f3d74e4
42.291262
168
0.687598
5.090183
false
false
false
false
roambotics/swift
test/SILGen/scalar_to_tuple_args.swift
2
4010
// RUN: %target-swift-emit-silgen -module-name scalar_to_tuple_args %s | %FileCheck %s func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {} func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {} func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {} func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {} func tupleWithDefaults(x: (Int, Int), y: Int = 0, z: Int = 0) {} func variadicFirst(_ x: Int...) {} func variadicSecond(_ x: Int, _ y: Int...) {} var x = 0 // CHECK: [[X_ADDR:%.*]] = global_addr @$s20scalar_to_tuple_args1xSivp : $*Int // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args17inoutWithDefaults_1y1zySiz_S2itF // CHECK: apply [[INOUT_WITH_DEFAULTS]]([[WRITE]], [[DEFAULT_Y]], [[DEFAULT_Z]]) inoutWithDefaults(&x) // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args27inoutWithCallerSideDefaults_1yySiz_SitF // CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[WRITE]], [[LINE]]) inoutWithCallerSideDefaults(&x) // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A12WithDefaults_1y1zySi_S2itF // CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]]) scalarWithDefaults(x) // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A22WithCallerSideDefaults_1yySi_SitF // CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]]) scalarWithCallerSideDefaults(x) // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X1:%.*]] = load [trivial] [[READ]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X2:%.*]] = load [trivial] [[READ]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0C12WithDefaults1x1y1zySi_Sit_S2itF // CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]]) tupleWithDefaults(x: (x,x)) // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]] // CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: copy_addr [[READ]] to [init] [[ADDR]] // CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF // CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Int>([[ARRAY]]) // CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @$s20scalar_to_tuple_args13variadicFirstyySid_tF // CHECK: apply [[VARIADIC_FIRST]]([[FIN_ARR]]) variadicFirst(x) // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]] // CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @$s20scalar_to_tuple_args14variadicSecondyySi_SidtF // CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]]) variadicSecond(x)
apache-2.0
676ec0bc6fb13dab093d0e21ac1844ee
53.90411
126
0.600798
3.13615
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/WindowPaneController.swift
1
3495
// // WindowPaneController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2014-04-18. // // --------------------------------------------------------------------------- // // © 2014-2020 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa final class WindowPaneController: NSViewController { // MARK: Private Properties private lazy var titleForRespectSystemSetting: String = self.tabbingOptionMenu!.items.first!.title @IBOutlet private weak var tabbingOptionMenu: NSMenu? @IBOutlet private weak var pageGuideColumnField: NSTextField? @IBOutlet private weak var overscrollField: NSTextField? @IBOutlet private weak var editorOpacityField: NSTextField? @IBOutlet private weak var ltrWritingDirectionButton: NSButton? @IBOutlet private weak var rtlWritingDirectionButton: NSButton? @IBOutlet private weak var verticalWritingDirectionButton: NSButton? // MARK: - // MARK: View Controller Methods override func viewDidLoad() { super.viewDidLoad() // set initial values as fields' placeholder self.pageGuideColumnField?.bindNullPlaceholderToUserDefaults() self.overscrollField?.bindNullPlaceholderToUserDefaults() self.editorOpacityField?.bindNullPlaceholderToUserDefaults() } override func viewWillAppear() { super.viewWillAppear() // display the current systemwide user setting for window tabbing in "Respect System Setting" menu item. let menu = self.tabbingOptionMenu! let systemSettingLabel = menu.item(withTag: NSWindow.userTabbingPreference.rawValue)!.title let attributes: [NSAttributedString.Key: Any] = [.font: menu.font].compactMapValues { $0 } let attrLabel = NSAttributedString(string: self.titleForRespectSystemSetting, attributes: attributes) let userSettingLabel = NSAttributedString(string: String(format: " (%@)".localized, systemSettingLabel), attributes: [.foregroundColor: NSColor.secondaryLabelColor].merging(attributes) { $1 }) menu.items.first!.attributedTitle = attrLabel + userSettingLabel // select one of writing direction radio buttons switch UserDefaults.standard[.writingDirection] { case .leftToRight: self.ltrWritingDirectionButton?.state = .on case .rightToLeft: self.rtlWritingDirectionButton?.state = .on case .vertical: self.verticalWritingDirectionButton?.state = .on } } // MARK: Action Messages /// A radio button of writingDirection was clicked @IBAction func updateWritingDirectionSetting(_ sender: NSControl) { UserDefaults.standard[.writingDirection] = WritingDirection(rawValue: sender.tag)! } }
apache-2.0
f18238f58580a05d8cf905c6b2df9071
35.778947
137
0.662851
5.049133
false
false
false
false
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/CMAC.swift
2
3875
// // CryptoSwift // // Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // public class CMAC: Authenticator { public enum Error: Swift.Error { case wrongKeyLength } internal let key: SecureBytes internal static let BlockSize: Int = 16 internal static let Zero: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] private static let Rb: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87] public init(key: Array<UInt8>) throws { self.key = SecureBytes(bytes: key) } // MARK: Authenticator // AES-CMAC public func authenticate(_ bytes: Array<UInt8>) throws -> Array<UInt8> { let cipher = try AES(key: Array(key), blockMode: CBC(iv: CMAC.Zero), padding: .noPadding) return try self.authenticate(bytes, cipher: cipher) } // CMAC using a Cipher public func authenticate(_ bytes: Array<UInt8>, cipher: Cipher) throws -> Array<UInt8> { let l = try cipher.encrypt(CMAC.Zero) var subKey1 = self.leftShiftOneBit(l) if (l[0] & 0x80) != 0 { subKey1 = xor(CMAC.Rb, subKey1) } var subKey2 = self.leftShiftOneBit(subKey1) if (subKey1[0] & 0x80) != 0 { subKey2 = xor(CMAC.Rb, subKey2) } let lastBlockComplete: Bool let blockCount = (bytes.count + CMAC.BlockSize - 1) / CMAC.BlockSize if blockCount == 0 { lastBlockComplete = false } else { lastBlockComplete = bytes.count % CMAC.BlockSize == 0 } var paddedBytes = bytes if !lastBlockComplete { bitPadding(to: &paddedBytes, blockSize: CMAC.BlockSize) } var blocks = Array(paddedBytes.batched(by: CMAC.BlockSize)) var lastBlock = blocks.popLast()! if lastBlockComplete { lastBlock = xor(lastBlock, subKey1) } else { lastBlock = xor(lastBlock, subKey2) } var x = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize) var y = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize) for block in blocks { y = xor(block, x) x = try cipher.encrypt(y) } // the difference between CMAC and CBC-MAC is that CMAC xors the final block with a secret value y = self.process(lastBlock: lastBlock, with: x) return try cipher.encrypt(y) } func process(lastBlock: ArraySlice<UInt8>, with x: [UInt8]) -> [UInt8] { xor(lastBlock, x) } // MARK: Helper methods /** Performs left shift by one bit to the bit string aquired after concatenating al bytes in the byte array - parameters: - bytes: byte array - returns: bit shifted bit string split again in array of bytes */ private func leftShiftOneBit(_ bytes: Array<UInt8>) -> Array<UInt8> { var shifted = Array<UInt8>(repeating: 0x00, count: bytes.count) let last = bytes.count - 1 for index in 0..<last { shifted[index] = bytes[index] << 1 if (bytes[index + 1] & 0x80) != 0 { shifted[index] += 0x01 } } shifted[last] = bytes[last] << 1 return shifted } }
mit
5fe8e9de18bc95b698ec0cdcba0961b1
35.54717
217
0.675529
3.410211
false
false
false
false
lukejmann/FBLA2017
FBLA2017/CameraViewController.swift
1
3432
// // CameraViewController.swift // FBLA2017 // // Created by Luke Mann on 4/8/17. // Copyright © 2017 Luke Mann. All rights reserved. import UIKit import AVFoundation import Foundation class CameraViewController: UIViewController { @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var imgOverlay: UIImageView! @IBOutlet weak var btnCapture: UIButton! let captureSession = AVCaptureSession() let stillImageOutput = AVCaptureStillImageOutput() var previewLayer: AVCaptureVideoPreviewLayer? // If we find a device we'll store it here for later use var captureDevice: AVCaptureDevice? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. captureSession.sessionPreset = AVCaptureSessionPresetHigh if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] { // Loop through all the capture devices on this phone for device in devices { // Make sure this particular device supports video if (device.hasMediaType(AVMediaTypeVideo)) { // Finally check the position and confirm we've got the back camera if(device.position == AVCaptureDevicePosition.front) { captureDevice = device if captureDevice != nil { print("Capture device found") beginSession() } } } } } } @IBAction func actionCameraCapture(_ sender: AnyObject) { print("Camera button pressed") saveToCamera() } func beginSession() { do { try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice)) stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] if captureSession.canAddOutput(stillImageOutput) { captureSession.addOutput(stillImageOutput) } } catch { print("error: \(error.localizedDescription)") } guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else { print("no preview layer") return } self.view.layer.addSublayer(previewLayer) previewLayer.frame = self.view.layer.frame captureSession.startRunning() self.view.addSubview(navigationBar) self.view.addSubview(imgOverlay) self.view.addSubview(btnCapture) } func saveToCamera() { if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) { stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (CMSampleBuffer, _) in if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(CMSampleBuffer) { if let cameraImage = UIImage(data: imageData) { for i in 0...10_000 { UIImageWriteToSavedPhotosAlbum(cameraImage, nil, nil, nil) } } } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
33c8f11f2334491c7a1177fdeb12edaf
31.990385
127
0.609735
6.051146
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01858-llvm-densemap-swift-valuedecl.swift
11
1079
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -parse struct d<T where g: A where g, f<T) -> T -> String { let c { class p == { protocol f { return self[" } class k , b { (Any, m.init(j, i l, b class B, AnyObject) -> T { u m h: k<T> String { } } } func b> String = T> d<T where T: Int = [1 j : A> Any) + seq struct C<T) -> { } func b() -> i<l y ed) -> { f : A { func f.m) func a typealias B == g.E ()-> { } protocol f d{ se } ) func d<T return d.i : Array<T>) } protocol d = b.C<T.Type) -> U) -> Any) { } case .c(() -> t.f = g, o>>(b func g<l p : () func a: b } return { enum a!)) -> { enum A { let n1: (p: P> T { struct c(r: c, l lk: NSObject { enum g : Array<h == [u, (n<h { } typealias e = [q(() func f: (x: B) -> : c> (g.p, d<q "))) } o
apache-2.0
b865245741cf2db94dc404fec1bd466e
19.358491
78
0.585728
2.538824
false
false
false
false
superk589/DereGuide
DereGuide/View/IndicatorScrollView.swift
2
1382
// // IndicatorScrollView.swift // DereGuide // // Created by zzk on 2017/6/3. // Copyright © 2017 zzk. All rights reserved. // import UIKit class IndicatorScrollView: UIScrollView { let indicator = ScrollViewIndicator(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) lazy var debouncer: Debouncer = { return Debouncer.init(interval: 3, callback: { [weak self] in if self?.indicator.panGesture.state == .possible { self?.indicator.hide() } else { self?.debouncer.call() } }) }() override var contentOffset: CGPoint { set { super.contentOffset = newValue debouncer.call() indicator.adjustFrameInScrollView() } get { return super.contentOffset } } @objc func handlePanGestureInside(_ pan: UIPanGestureRecognizer) { if pan.state == .began { indicator.show(to: self) } } override init(frame: CGRect) { super.init(frame: frame) showsVerticalScrollIndicator = false delaysContentTouches = false panGestureRecognizer.addTarget(self, action: #selector(handlePanGestureInside(_:))) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
9c604aba63bba7f856b767f91a91155e
25.557692
91
0.581463
4.729452
false
false
false
false
envoyproxy/envoy
mobile/library/swift/grpc/GRPCStreamPrototype.swift
2
6815
import Foundation /// A type representing a gRPC stream that has not yet been started. /// /// Constructed via `GRPCClient`, and used to assign response callbacks /// prior to starting a `GRPCStream` by calling `start()`. @objcMembers public final class GRPCStreamPrototype: NSObject { private let underlyingStream: StreamPrototype /// Initialize a new instance of the inactive gRPC stream. /// /// - parameter underlyingStream: The underlying stream to use. required init(underlyingStream: StreamPrototype) { self.underlyingStream = underlyingStream super.init() } // MARK: - Public /// Start a new gRPC stream. /// /// - parameter queue: Queue on which to receive callback events. /// /// - returns: The new gRPC stream. public func start(queue: DispatchQueue = .main) -> GRPCStream { let stream = self.underlyingStream.start(queue: queue) return GRPCStream(underlyingStream: stream) } /// Specify a callback for when response headers are received by the stream. /// /// - parameter closure: Closure which will receive the headers /// and flag indicating if the stream is headers-only. /// /// - returns: This stream, for chaining syntax. @discardableResult public func setOnResponseHeaders( closure: @escaping (_ headers: ResponseHeaders, _ endStream: Bool, _ streamIntel: StreamIntel) -> Void ) -> GRPCStreamPrototype { self.underlyingStream.setOnResponseHeaders(closure: closure) return self } /// Specify a callback for when a new message has been received by the stream. /// /// - parameter closure: Closure which will receive messages on the stream. /// /// - returns: This handler, which may be used for chaining syntax. @discardableResult public func setOnResponseMessage( _ closure: @escaping (_ message: Data, _ streamIntel: StreamIntel) -> Void ) -> GRPCStreamPrototype { var buffer = Data() var state = GRPCMessageProcessor.State.expectingCompressionFlag self.underlyingStream.setOnResponseData { chunk, _, streamIntel in // Appending might result in extra copying that can be optimized in the future. buffer.append(chunk) // gRPC always sends trailers, so the stream will not complete here. GRPCMessageProcessor.processBuffer(&buffer, state: &state, streamIntel: streamIntel, onMessage: closure) } return self } /// Specify a callback for when trailers are received by the stream. /// If the closure is called, the stream is complete. /// /// - parameter closure: Closure which will receive the trailers. /// /// - returns: This handler, which may be used for chaining syntax. @discardableResult public func setOnResponseTrailers(_ closure: @escaping (_ trailers: ResponseTrailers, _ streamIntel: StreamIntel) -> Void ) -> GRPCStreamPrototype { self.underlyingStream.setOnResponseTrailers(closure: closure) return self } /// Specify a callback for when an internal Envoy exception occurs with the stream. /// If the closure is called, the stream is complete. /// /// - parameter closure: Closure which will be called when an error occurs. /// /// - returns: This handler, which may be used for chaining syntax. @discardableResult public func setOnError( _ closure: @escaping (_ error: EnvoyError, _ streamIntel: FinalStreamIntel) -> Void ) -> GRPCStreamPrototype { self.underlyingStream.setOnError(closure: closure) return self } /// Specify a callback for when the stream is canceled. /// If the closure is called, the stream is complete. /// /// - parameter closure: Closure which will be called when the stream is canceled. /// /// - returns: This stream, for chaining syntax. @discardableResult public func setOnCancel( closure: @escaping (_ streamIntel: FinalStreamIntel) -> Void ) -> GRPCStreamPrototype { self.underlyingStream.setOnCancel(closure: closure) return self } /// Specify a callback for when the stream completes gracefully. /// If the closure is called, the stream is complete. /// /// - parameter closure: Closure which will be called when the stream is closed. /// /// - returns: This stream, for chaining syntax. @discardableResult public func setOnComplete( closure: @escaping (_ streamIntel: FinalStreamIntel) -> Void ) -> GRPCStreamPrototype { self.underlyingStream.setOnComplete(closure: closure) return self } } private enum GRPCMessageProcessor { /// Represents the state of a response stream's body data. enum State { /// Awaiting a gRPC compression flag. case expectingCompressionFlag /// Awaiting the length specification of the next message. case expectingMessageLength /// Awaiting a message with the specified length. case expectingMessage(messageLength: UInt32) } /// Recursively processes a buffer of data, buffering it into messages based on state. /// When a message has been fully buffered, `onMessage` will be called with the message. /// /// - parameter buffer: The buffer of data from which to determine state and messages. /// - parameter state: The current state of the buffering. /// - parameter streamIntel: Internal HTTP stream metrics, context, and other details. /// - parameter onMessage: Closure to call when a new message is available. static func processBuffer(_ buffer: inout Data, state: inout State, streamIntel: StreamIntel, onMessage: (_ message: Data, _ streamIntel: StreamIntel) -> Void) { switch state { case .expectingCompressionFlag: guard let compressionFlag: UInt8 = buffer.integer(atIndex: 0) else { return } guard compressionFlag == 0 else { // TODO: Support gRPC compression https://github.com/envoyproxy/envoy-mobile/issues/501 buffer.removeAll() state = .expectingCompressionFlag return } state = .expectingMessageLength case .expectingMessageLength: guard let messageLength: UInt32 = buffer.integer(atIndex: 1) else { return } state = .expectingMessage(messageLength: CFSwapInt32BigToHost(messageLength)) case .expectingMessage(let messageLength): let prefixedLength = kGRPCPrefixLength + Int(messageLength) if buffer.count < prefixedLength { return } if messageLength > 0 { onMessage(buffer.subdata(in: kGRPCPrefixLength..<prefixedLength), streamIntel) } else { onMessage(Data(), streamIntel) } buffer.removeSubrange(0..<prefixedLength) state = .expectingCompressionFlag } self.processBuffer(&buffer, state: &state, streamIntel: streamIntel, onMessage: onMessage) } }
apache-2.0
9f73a718d080cccccedde4eba5b78ce9
35.639785
95
0.692443
4.696761
false
false
false
false
rcobelli/GameOfficials
SwiftyJSON.swift
1
41526
// SwiftyJSON.swift // // Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang // // 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: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } catch let aError as NSError { if error != nil { error?.pointee = aError } self.init(jsonObject: NSNull()) } } /** Creates a JSON object - parameter object: the object - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - returns: the created JSON object */ public init(_ object: Any) { switch object { case let object as [JSON] where object.count > 0: self.init(array: object) case let object as [String: JSON] where object.count > 0: self.init(dictionary: object) case let object as Data: self.init(data: object) default: self.init(jsonObject: object) } } /** Parses the JSON string into a JSON object - parameter json: the JSON string - returns: the created JSON object */ public init(parseJSON jsonString: String) { if let data = jsonString.data(using: .utf8) { self.init(data) } else { self.init(NSNull()) } } /** Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ fileprivate init(jsonObject: Any) { self.object = jsonObject } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ fileprivate init(array: [JSON]) { self.init(array.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ fileprivate init(dictionary: [String: JSON]) { var newDictionary = [String: Any](minimumCapacity: dictionary.count) for (key, json) in dictionary { newDictionary[key] = json.object } self.init(newDictionary) } /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - parameter other: The JSON which gets merged into this JSON - returns: New merged JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) return merged } // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON(self.arrayValue + other.arrayValue) default: self = other } } else { if typecheck { throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) } else { self = other } } } /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String : Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false /// Private type fileprivate var _type: Type = .null /// prviate error fileprivate var _error: NSError? = nil /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .bool self.rawBool = number.boolValue } else { _type = .number self.rawNumber = number } case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null case _ as [JSON]: _type = .array case nil: _type = .null case let array as [Any]: _type = .array self.rawArray = array case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// JSON type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } public enum Index<T: Any>: Comparable { case array(Int) case dictionary(DictionaryIndex<String, T>) case null static public func ==(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } static public func <(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } } public typealias JSONIndex = Index<JSON> public typealias JSONRawIndex = Index<Any> extension JSON: Collection { public typealias Index = JSONRawIndex public var startIndex: Index { switch type { case .array: return .array(rawArray.startIndex) case .dictionary: return .dictionary(rawDictionary.startIndex) default: return .null } } public var endIndex: Index { switch type { case .array: return .array(rawArray.endIndex) case .dictionary: return .dictionary(rawDictionary.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): let (key, value) = self.rawDictionary[idx] return (key, JSON(value)) default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let array = elements self.init(dictionaryLiteral: array) } public init(dictionaryLiteral elements: [(String, Any)]) { let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in if let value = dictionary[key] { return (key, value) } return nil } return JSON(dictionaryLiteral: initializeElement) } var dict = [String : Any](minimumCapacity: elements.count) for element in elements { let elementToSet: Any if let json = element.1 as? JSON { elementToSet = json.object } else if let jsonArray = element.1 as? [JSON] { elementToSet = JSON(jsonArray).object } else if let dictionary = element.1 as? [String : Any] { elementToSet = jsonFromDictionaryLiteral(dictionary).object } else if let dictArray = element.1 as? [[String : Any]] { let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } elementToSet = JSON(jsonArray).object } else { elementToSet = element.1 } dict[element.0] = elementToSet } self.init(dict) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.ExpressibleByNilLiteral { @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } public func rawString(_ options: [writtingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } fileprivate func _rawString( _ encoding: String.Encoding = .utf8, options: [writtingOptionsKeys: Any], maxObjectDepth: Int = 10 ) throws -> String? { if (maxObjectDepth < 0) { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) } switch self.type { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let dict = self.object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in guard let value = dict[key] else { return "\"\(key)\": null" } guard let unwrappedValue = value else { return "\"\(key)\": null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return "\"\(key)\": \(nestedString)" } } return "{\(body.joined(separator: ","))}" } catch _ { return nil } case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let array = self.object as? [Any?] else { return nil } let body = try array.map { value throws -> String in guard let unwrappedValue = value else { return "null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return nestedString } } return "[\(body.joined(separator: ","))]" } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [Any] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { var d = [String : JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { d[key] = JSON(value) } return d } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return ["true", "y", "t"].contains() { (truthyString) in return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame } default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool{ if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { return false } return true } } //MARK: - URL extension JSON { //Optional URL public var url: URL? { get { switch self.type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character if let _ = self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) { return Foundation.URL(string: self.rawString) } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: Int(newValue)) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: Int(newValue)) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ return true } else { return false } } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } } public enum writtingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth case encoding }
mit
9530fd7809dd8b96c2bb8248c8f84775
26.963636
265
0.54667
4.657992
false
false
false
false
NikitaAsabin/pdpDecember
Pods/FSHelpers+Swift/Swift/Helpers/FSExtensions/FSE+UIView.swift
1
1731
// // FSExtensions+UIView.swift // SwiftHelpers // // Created by Kruperfone on 31.07.15. // Copyright (c) 2015 FlatStack. All rights reserved. // import UIKit public extension UIView { //MARK: - Set size var fs_size: CGSize { set (value) {self.frame.size = value} get {return self.frame.size} } var fs_width:CGFloat { set (value) {self.fs_size = CGSizeMake(value, frame.size.height)} get {return self.frame.size.width} } var fs_height:CGFloat { set (value) {self.fs_size = CGSizeMake(frame.size.width, value)} get {return self.frame.size.height} } //MARK: - Set origin var fs_origin: CGPoint { set (value) {self.frame.origin = value} get {return self.frame.origin} } var fs_x: CGFloat { set (value) {self.fs_origin = CGPointMake(value, frame.origin.y)} get {return self.frame.origin.x} } var fs_y: CGFloat { set (value) {self.fs_origin = CGPointMake(frame.origin.x, value)} get {return self.frame.origin.y} } //MARK: - Other func fs_findAndResignFirstResponder () -> Bool { if self.isFirstResponder() { self.resignFirstResponder() return true } for view in subviews { if view.fs_findAndResignFirstResponder() { return true } } return false } var fs_allSubviews: [UIView] { var arr:[UIView] = [self] for view in subviews { arr += view.fs_allSubviews } return arr } }
mit
5bf60706aa9f3585c63ee3f00d2ba6ff
22.712329
73
0.523975
3.997691
false
false
false
false
BennyKJohnson/OpenCloudKit
Sources/CKRecordZoneNotification.swift
1
1464
// // CKRecordZoneNotification.swift // OpenCloudKit // // Created by Benjamin Johnson on 20/1/17. // // import Foundation public class CKRecordZoneNotification : CKNotification { public var recordZoneID: CKRecordZoneID? public var databaseScope: CKDatabaseScope = .public override init(fromRemoteNotificationDictionary notificationDictionary: [AnyHashable : Any]) { super.init(fromRemoteNotificationDictionary: notificationDictionary) notificationType = CKNotificationType.recordZone if let cloudDictionary = notificationDictionary["ck"] as? [String: Any] { if let zoneDictionary = cloudDictionary["fet"] as? [String: Any] { // Set RecordZoneID if let zoneName = zoneDictionary["zid"] as? String { let zoneID = CKRecordZoneID(zoneName: zoneName, ownerName: "__defaultOwner__") recordZoneID = zoneID } // Set Database Scope if let dbs = zoneDictionary["dbs"] as? NSNumber, let scope = CKDatabaseScope(rawValue: dbs.intValue) { databaseScope = scope } // Set Subscription ID if let sid = zoneDictionary["sid"] as? String { subscriptionID = sid } } } } }
mit
ec48bc2be971b540a82735e69ffb7b11
31.533333
118
0.556011
5.674419
false
false
false
false
benlangmuir/swift
test/attr/global_actor.swift
4
4931
// RUN: %target-swift-frontend -typecheck -verify %s -disable-availability-checking // REQUIRES: concurrency actor SomeActor { } // ----------------------------------------------------------------------- // @globalActor attribute itself. // ----------------------------------------------------------------------- // Well-formed global actor. @globalActor struct GA1 { static let shared = SomeActor() } @globalActor struct GenericGlobalActor<T> { static var shared: SomeActor { SomeActor() } } // Ill-formed global actors. @globalActor final class GA2 { // expected-error{{type 'GA2' does not conform to protocol 'GlobalActor'}} } @globalActor struct GA3 { // expected-error{{type 'GA3' does not conform to protocol 'GlobalActor'}} let shared = SomeActor() } @globalActor struct GA4 { private static let shared = SomeActor() // expected-error{{property 'shared' must be as accessible as its enclosing type because it matches a requirement in protocol 'GlobalActor'}} // expected-note@-1{{mark the static property as 'internal' to satisfy the requirement}} } @globalActor open class GA5 { // expected-error{{non-final class 'GA5' cannot be a global actor}} static let shared = SomeActor() // expected-error{{property 'shared' must be declared public because it matches a requirement in public protocol 'GlobalActor'}} // expected-note@-1{{mark the static property as 'public' to satisfy the requirement}} } @globalActor struct GA6<T> { // expected-error{{type 'GA6<T>' does not conform to protocol 'GlobalActor'}} } extension GA6 where T: Equatable { static var shared: SomeActor { SomeActor() } } @globalActor final class GA7 { // expected-error{{type 'GA7' does not conform to protocol 'GlobalActor'}} static let shared = 5 // expected-note{{candidate would match and infer 'ActorType' = 'Int' if 'Int' conformed to 'Actor'}} } // ----------------------------------------------------------------------- // Applying global actors to entities. // ----------------------------------------------------------------------- @globalActor struct OtherGlobalActor { static let shared = SomeActor() } @GA1 func f() { @GA1 let x = 17 // expected-error{{local variable 'x' cannot have a global actor}} _ = x } @GA1 struct X { @GA1 var member: Int // expected-warning {{stored property 'member' within struct cannot have a global actor; this is an error in Swift 6}} } struct Y { @GA1 subscript(i: Int) -> Int { i } } @GA1 extension Y { } @GA1 func g() { } class SomeClass { @GA1 init() { } @GA1 deinit { } // expected-error{{deinitializer cannot have a global actor}} } @GA1 typealias Integer = Int // expected-error{{type alias cannot have a global actor}} @GA1 actor ActorInTooManyPlaces { } // expected-error{{actor 'ActorInTooManyPlaces' cannot have a global actor}} @GA1 @OtherGlobalActor func twoGlobalActors() { } // expected-error{{declaration can not have multiple global actor attributes ('OtherGlobalActor' and 'GA1')}} struct Container { // FIXME: Diagnostic could be improved to show the generic arguments. @GenericGlobalActor<Int> @GenericGlobalActor<String> func twoGenericGlobalActors() { } // expected-error{{declaration can not have multiple global actor attributes ('GenericGlobalActor' and 'GenericGlobalActor')}} } // ----------------------------------------------------------------------- // Redundant attributes // ----------------------------------------------------------------------- extension SomeActor { @GA1 nonisolated func conflict1() { } // expected-error 3{{instance method 'conflict1()' has multiple actor-isolation attributes ('nonisolated' and 'GA1')}} } // ----------------------------------------------------------------------- // Access // ----------------------------------------------------------------------- @globalActor private struct PrivateGA { // expected-note 2 {{type declared here}} actor Actor {} static let shared = Actor() } @globalActor internal struct InternalGA { // expected-note 1 {{type declared here}} actor Actor {} static let shared = Actor() } @globalActor public struct PublicGA { public actor Actor {} public static let shared = Actor() } @PrivateGA private struct PrivateStructPrivateGA {} @InternalGA private struct PrivateStructInternalGA {} @PublicGA private struct PrivateStructPublicGA {} @PrivateGA internal struct InternalStructPrivateGA {} // expected-error {{internal struct 'InternalStructPrivateGA' cannot have private global actor 'PrivateGA'}} @InternalGA internal struct InternalStructInternalGA {} @PublicGA internal struct InternalStructPublicGA {} @PrivateGA open class OpenClassPrivateGA {} // expected-error {{open class 'OpenClassPrivateGA' cannot have private global actor 'PrivateGA'}} @InternalGA open class OpenClassInternalGA {} // expected-error {{open class 'OpenClassInternalGA' cannot have internal global actor 'InternalGA'}} @PublicGA open class OpenClassPublicGA {}
apache-2.0
d735cd7b9f48afa9f6adc31f5d295173
34.992701
213
0.649564
4.462443
false
false
false
false
SunChJ/functional-swift
Fundational-Swift/Map,Filter,Reduce/MapFilterReduce.playground/Contents.swift
1
2332
//: Playground - noun: a place where people can play import UIKit // 每项+1 func incrementArray(xs: [Int]) -> [Int] { var result: [Int] = [] for x in xs { result.append(x + 1) } return result } incrementArray(xs: Array(repeating: 1, count: 5)) // 每项*2 func doubleArray1(xs: [Int]) -> [Int] { var result: [Int] = [] for x in xs { result.append(x * 2) } return result } doubleArray1(xs: Array(repeating: 1, count: 5)) // 无论每项 +1 | *2 ,两个函数定义的时候都有大量相同的代码, 提取有区别的地方,并抽象出来 func computeIntArray(xs: [Int], transform: (Int) -> Int) -> [Int] { var result: [Int] = [] for x in xs { result.append(transform(x)) } return result } func doubleArray2(xs: [Int]) -> [Int] { return computeIntArray(xs: xs, transform: {x in x*2}) } func increamentArray2(xs: [Int]) -> [Int] { return computeIntArray(xs: xs, transform: {x in x+1}) } increamentArray2(xs: Array(repeating: 1, count: 5)) doubleArray2(xs: Array(repeating: 1, count: 5)) // 由于扩展性不佳, 我们使用范型。 // computeBoolArray和computeIntArray的定义是相同的,唯一的区别在于类型签名(type signature)。 func genericComputeArray1<T>(xs: [Int], transform: (Int) -> T) -> [T] { var result: [T] = [] for x in xs { result.append(transform(x)) } return result } func genericComputeArray<T>(xs: [Int], transform: (Int) -> T) -> [T] { return xs.map(transform) } let result = genericComputeArray(xs: Array(repeating: 1, count: 5), transform: {x in x+1}) print(result) struct City { let name: String let population: Int } let paris = City(name: "Paris", population: 2241) let madrid = City(name: "Madrid", population: 3165) let amsterdam = City(name: "Amsterdam", population: 827) let berlin = City(name: "Berlin", population: 3562) let cities = [paris, madrid, amsterdam, berlin] extension City { func cityByScalingPopulation() -> City { return City(name: name, population: population * 1000) } } [1,2,3].reduce(1, *) let display = cities.filter{$0.population > 1000} .map{$0.cityByScalingPopulation()} .reduce("Citi: Population"){ result, c in return result + "\n" + "\(c.name): \(c.population)" } print(display)
mit
3923b2a5aa427d20f227431e2615be89
23.681818
90
0.631676
2.971272
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Knowledge Groups/Interactor Tests/DefaultKnowledgeGroupsInteractorTests.swift
1
4014
@testable import Eurofurence import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class CapturingKnowledgeGroupsListViewModelDelegate: KnowledgeGroupsListViewModelDelegate { private(set) var capturedViewModels: [KnowledgeListGroupViewModel] = [] func knowledgeGroupsViewModelsDidUpdate(to viewModels: [KnowledgeListGroupViewModel]) { capturedViewModels = viewModels } } class DefaultKnowledgeGroupsInteractorTests: XCTestCase { private func expectedViewModelForGroup(_ group: KnowledgeGroup) -> KnowledgeListGroupViewModel { let entriesViewModels = group.entries.map(expectedViewModelForEntry) return KnowledgeListGroupViewModel(title: group.title, fontAwesomeCharacter: group.fontAwesomeCharacterAddress, groupDescription: group.groupDescription, knowledgeEntries: entriesViewModels) } private func expectedViewModelForEntry(_ entry: KnowledgeEntry) -> KnowledgeListEntryViewModel { return KnowledgeListEntryViewModel(title: entry.title) } func testKnowledgeGroupsFromServiceAreTurnedIntoExpectedViewModels() { let service = StubKnowledgeService() let interactor = DefaultKnowledgeGroupsInteractor(service: service) var viewModel: KnowledgeGroupsListViewModel? interactor.prepareViewModel { viewModel = $0 } let delegate = CapturingKnowledgeGroupsListViewModelDelegate() viewModel?.setDelegate(delegate) let models: [FakeKnowledgeGroup] = .random let expected = models.map(expectedViewModelForGroup) service.simulateFetchSucceeded(models) XCTAssertEqual(expected, delegate.capturedViewModels) } func testLateBoundViewModelDelegateProvidedWithExpectedViewModels() { let service = StubKnowledgeService() let interactor = DefaultKnowledgeGroupsInteractor(service: service) var viewModel: KnowledgeGroupsListViewModel? interactor.prepareViewModel { viewModel = $0 } let models: [FakeKnowledgeGroup] = .random let expected = models.map(expectedViewModelForGroup) service.simulateFetchSucceeded(models) let delegate = CapturingKnowledgeGroupsListViewModelDelegate() viewModel?.setDelegate(delegate) XCTAssertEqual(expected, delegate.capturedViewModels) } func testProvideExpectedKnowledgeGroupByIndex() { let service = StubKnowledgeService() let interactor = DefaultKnowledgeGroupsInteractor(service: service) var viewModel: KnowledgeGroupsListViewModel? interactor.prepareViewModel { viewModel = $0 } let models: [FakeKnowledgeGroup] = .random service.simulateFetchSucceeded(models) let randomGroup = models.randomElement() let expected = randomGroup.element.identifier let visitor = CapturingKnowledgeGroupsListViewModelVisitor() viewModel?.describeContentsOfKnowledgeItem(at: randomGroup.index, visitor: visitor) XCTAssertEqual(expected, visitor.visitedKnowledgeGroup) XCTAssertNil(visitor.visitedKnowledgeEntry) } func testGroupWithSingleEntryVisitsEntryInsteadOfGroup() { let service = StubKnowledgeService() let interactor = DefaultKnowledgeGroupsInteractor(service: service) var viewModel: KnowledgeGroupsListViewModel? interactor.prepareViewModel { viewModel = $0 } let group = FakeKnowledgeGroup.random let entry = FakeKnowledgeEntry.random group.entries = [entry] service.simulateFetchSucceeded([group]) let visitor = CapturingKnowledgeGroupsListViewModelVisitor() viewModel?.describeContentsOfKnowledgeItem(at: 0, visitor: visitor) let expected = entry.identifier XCTAssertEqual(expected, visitor.visitedKnowledgeEntry) XCTAssertNil(visitor.visitedKnowledgeGroup) } }
mit
f4d70fe39581913a876f90e113a5338f
41.702128
100
0.724714
5.982116
false
true
false
false
mdznr/Keyboard
KeyboardExtension/StringExtensions.swift
1
2741
// // StringExtensions.swift // Keyboard // // Created by Matt Zanchelli on 6/15/14. // Copyright (c) 2014 Matt Zanchelli. All rights reserved. // import Foundation extension String { func isFirstLetterCapitalized() -> Bool { // Get the first character as a string. let firstLetter = self.substringToIndex(advance(self.startIndex, 1)) // See if the uppercase version of the string is the same. return !firstLetter.isEmpty && firstLetter == firstLetter.uppercaseString && firstLetter != firstLetter.lowercaseString } func numberOfElementsToDeleteToDeleteLastWord() -> Int { // All the chunks in the word. var chunks = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) // The total number of elements and chunks to delete var numberOfElementsToDelete = 0 var numberOfChunksToDelete = 0; // The current chunk we're looking at. var chunk: String // Delete trailing whitespace and one non-whitespace chunk. do { numberOfChunksToDelete++ if ( numberOfChunksToDelete > chunks.count ) { break; } chunk = chunks[chunks.count - numberOfChunksToDelete] var numElements = max(countElements(chunk), 1) numberOfElementsToDelete += numElements } while ( countElements(chunk) == 0 ) return numberOfElementsToDelete } func numberOfElementsToDeleteToDeleteFirstWord() -> Int { // All the chunks in the word. var chunks = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) // The total number of elements and chunks to delete var numberOfElementsToDelete = 0 var numberOfChunksToDelete = 0; // The current chunk we're looking at. var chunk: String // Delete trailing whitespace and one non-whitespace chunk. do { if ( numberOfChunksToDelete > chunks.count - 1 ) { break; } chunk = chunks[numberOfChunksToDelete++] var numElementsInChunk = max(countElements(chunk), 1) numberOfElementsToDelete += numElementsInChunk } while ( countElements(chunk) == 0 ) return numberOfElementsToDelete } var isAtBeginningOfPotentialWord: Bool { get { if self.isEmpty { return true } // ORIGINAL REGEX: ^.*( |/|—)$ if let match = self.rangeOfString("^.*( |/|—)$", options: .RegularExpressionSearch) { if !(match.isEmpty) { return true } } return false } } var isAtBeginningOfPotentialSentence: Bool { get { if self.isEmpty { return true } // ORIGINAL REGEX: ^.*[\.\!\?][")]?\s+$ if let match = self.rangeOfString("^.*[\\.\\!\\?][\")]?\\s+$", options: .RegularExpressionSearch) { if !(match.isEmpty) { return true } } return false } } }
mit
7b8d154612b2a676690406387d434857
25.066667
107
0.685057
3.926829
false
false
false
false
Dev1an/Bond
Bond/iOS/Bond+UISegmentedControl.swift
1
3344
// // Bond+UISegmentedControl.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Austin Cooley (@adcooley) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class SegmentedControlDynamicHelper { weak var control: UISegmentedControl? var listener: (UIControlEvents -> Void)? init(control: UISegmentedControl) { self.control = control control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: UIControlEvents.ValueChanged) } func valueChanged(control: UISegmentedControl) { self.listener?(.ValueChanged) } deinit { control?.removeTarget(self, action: nil, forControlEvents: .AllEvents) } } class SegmentedControlDynamic<T>: InternalDynamic<UIControlEvents> { let helper: SegmentedControlDynamicHelper init(control: UISegmentedControl) { self.helper = SegmentedControlDynamicHelper(control: control) super.init() self.helper.listener = { [unowned self] in self.value = $0 } } } private var eventDynamicHandleUISegmentedControl: UInt8 = 0; extension UISegmentedControl /*: Dynamical, Bondable */ { public var dynEvent: Dynamic<UIControlEvents> { if let d: AnyObject = objc_getAssociatedObject(self, &eventDynamicHandleUISegmentedControl) { return (d as? Dynamic<UIControlEvents>)! } else { let d = SegmentedControlDynamic<UIControlEvents>(control: self) objc_setAssociatedObject(self, &eventDynamicHandleUISegmentedControl, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } public var designatedDynamic: Dynamic<UIControlEvents> { return self.dynEvent } public var designatedBond: Bond<UIControlEvents> { return self.dynEvent.valueBond } } public func ->> (left: UISegmentedControl, right: Bond<UIControlEvents>) { left.designatedDynamic ->> right } public func ->> <U: Bondable where U.BondType == UIControlEvents>(left: UISegmentedControl, right: U) { left.designatedDynamic ->> right.designatedBond } public func ->> <T: Dynamical where T.DynamicType == UIControlEvents>(left: T, right: UISegmentedControl) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: Dynamic<UIControlEvents>, right: UISegmentedControl) { left ->> right.designatedBond }
mit
0ce2b05358c134d93a5176b0f7dac566
32.108911
136
0.737141
4.518919
false
false
false
false
SoneeJohn/WWDC
WWDC/GeneralPreferencesViewController.swift
1
4149
// // GeneralPreferencesViewController.swift // WWDC // // Created by Guilherme Rambo on 28/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa class GeneralPreferencesViewController: NSViewController { static func loadFromStoryboard() -> GeneralPreferencesViewController { let vc = NSStoryboard(name: NSStoryboard.Name(rawValue: "Preferences"), bundle: nil).instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "GeneralPreferencesViewController")) return vc as! GeneralPreferencesViewController } @IBOutlet weak var searchInTranscriptsSwitch: ITSwitch! @IBOutlet weak var searchInBookmarksSwitch: ITSwitch! @IBOutlet weak var refreshPeriodicallySwitch: ITSwitch! @IBOutlet weak var skipBackAndForwardBy30SecondsSwitch: ITSwitch! @IBOutlet weak var downloadsFolderLabel: NSTextField! @IBOutlet weak var downloadsFolderIntroLabel: NSTextField! @IBOutlet weak var searchIntroLabel: NSTextField! @IBOutlet weak var includeBookmarksLabel: NSTextField! @IBOutlet weak var includeTranscriptsLabel: NSTextField! @IBOutlet weak var refreshAutomaticallyLabel: NSTextField! @IBOutlet weak var skipBackAndForwardBy30SecondsLabel: NSTextField! @IBOutlet weak var dividerA: NSBox! @IBOutlet weak var dividerB: NSBox! @IBOutlet weak var dividerC: NSBox! override func viewDidLoad() { super.viewDidLoad() downloadsFolderIntroLabel.textColor = .prefsPrimaryText searchIntroLabel.textColor = .prefsPrimaryText includeBookmarksLabel.textColor = .prefsPrimaryText includeTranscriptsLabel.textColor = .prefsPrimaryText refreshAutomaticallyLabel.textColor = .prefsPrimaryText skipBackAndForwardBy30SecondsLabel.textColor = .prefsPrimaryText downloadsFolderLabel.textColor = .prefsSecondaryText dividerA.fillColor = .darkGridColor dividerB.fillColor = .darkGridColor dividerC.fillColor = .darkGridColor searchInTranscriptsSwitch.tintColor = .primary searchInBookmarksSwitch.tintColor = .primary refreshPeriodicallySwitch.tintColor = .primary skipBackAndForwardBy30SecondsSwitch.tintColor = .primary searchInTranscriptsSwitch.checked = Preferences.shared.searchInTranscripts searchInBookmarksSwitch.checked = Preferences.shared.searchInBookmarks refreshPeriodicallySwitch.checked = Preferences.shared.refreshPeriodically skipBackAndForwardBy30SecondsSwitch.checked = Preferences.shared.skipBackAndForwardBy30Seconds downloadsFolderLabel.stringValue = Preferences.shared.localVideoStorageURL.path } @IBAction func searchInTranscriptsSwitchAction(_ sender: Any) { Preferences.shared.searchInTranscripts = searchInTranscriptsSwitch.checked } @IBAction func searchInBookmarksSwitchAction(_ sender: Any) { Preferences.shared.searchInBookmarks = searchInBookmarksSwitch.checked } @IBAction func refreshPeriodicallySwitchAction(_ sender: Any) { Preferences.shared.refreshPeriodically = refreshPeriodicallySwitch.checked } @IBAction func skipBackAndForwardBy30SecondsSwitchAction(_ sender: Any) { Preferences.shared.skipBackAndForwardBy30Seconds = skipBackAndForwardBy30SecondsSwitch.checked } @IBAction func revealDownloadsFolderInFinder(_ sender: NSButton) { let url = Preferences.shared.localVideoStorageURL NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: url.path) } @IBAction func selectDownloadsFolder(_ sender: NSButton) { let panel = NSOpenPanel() panel.title = "Change Downloads Folder" panel.prompt = "Select" panel.canChooseDirectories = true panel.canChooseFiles = false panel.runModal() guard let url = panel.url else { return } Preferences.shared.localVideoStorageURL = url downloadsFolderLabel.stringValue = url.path } }
bsd-2-clause
e0e9d608b82f79489c983c3fb4903bae
39.666667
206
0.730714
5.250633
false
false
false
false
armcknight/pkpassgenerator
ImagesSizeChecker/Definitions.swift
1
1109
// // Definitions.swift // ImagesSizeChecker // // Created by Andrew McKnight on 5/1/16. // // import AppKit import Foundation enum PassType: String { case Generic = "generic" case BoardingPass = "boardingPass" case Coupon = "coupon" case EventTicket = "eventTicket" case StoreCard = "storeCard" static var allTypes: [PassType] = [.Generic, .BoardingPass, .Coupon, .EventTicket, .StoreCard] } struct Pass { var type: PassType var images: PassImages var formatVersion: Int var barcode: BarCode? } enum BarCodeFormat: String { case PKBarcodeFormatQR case PKBarcodeFormatPDF417 case PKBarcodeFormatAztec } struct BarCode { var message: String var format: BarCodeFormat } struct PassImages { var background: ImageSet? var footer: ImageSet? var icon: ImageSet? var logo: ImageSet? var strip: ImageSet? var thumbnail: ImageSet? } struct ImageSet { var single: CIImage var double: CIImage var triple: CIImage } enum Scale: String { case Single = "1x" case Double = "2x" case Triple = "3x" }
mit
ebeece438e6f5bf44e9f5cc59a1d425f
17.483333
98
0.671776
3.672185
false
false
false
false
JSafaiyeh/kiqit
ios/kiqit/Event.swift
1
574
// // Event.swift // kiqit // // Created by Jason Safaiyeh on 7/26/16. // Copyright © 2016 Jason Safaiyeh. All rights reserved. // import Foundation class Event { let title: String let description: String let location: String let startTime: String let endTime: String init(title: String, description: String, location: String, startTime: String, endTime: String) { self.title = title self.description = description self.location = location self.startTime = startTime self.endTime = endTime } }
mit
4b1a034a3f6bfdc8f41c357cc676b4de
21.92
100
0.649215
3.951724
false
false
false
false
honghaoz/UW-Info-Session-iOS
UW-Info-Session/UW-Info-Session/Sources/Components/ListView/DetailView/DetailViewController.swift
2
7981
// // DetailViewController.swift // UW-Info-Session // // Created by Honghao Zhang on 2017-01-01. // Copyright © 2017 Honghaoz. All rights reserved. // import UIKit import ChouTi import Then import SafariServices class DetailViewController: BaseViewController { let infoSession: InfoSession var infoSessionDataEntries: [InfoSessionDataEntry] { var models: [InfoSessionDataEntry] = [] models.append( InfoSessionDataEntry( title: "Date", content: infoSession.startDate?.string(format: .custom("EEEE, MMM d, y")) ) ) models.append( InfoSessionDataEntry( title: "Time", content: [infoSession.startDate?.string(format: .custom("h:mm a")), infoSession.endDate?.string(format: .custom("h:mm a"))].flatMap{ $0 }.joined(separator: " - ") ) ) models.append( InfoSessionDataEntry( title: "Location", content: infoSession.location ) ) models.append( InfoSessionDataEntry( title: "Website", content: infoSession.website ).then { $0.cellSelectAction = { _, _, _ in guard let urlString = self.infoSession.website, let url = URL(string: urlString) else { return } let svc = SFSafariViewController(url: url) svc.preferredControlTintColor = UIColor.primary self.present(svc, animated: true, completion: nil) } } ) models.append( InfoSessionDataEntry( title: "Students", content: infoSession.audience ) ) models.append( InfoSessionDataEntry( title: "Programs", content: infoSession.programs ) ) models.append( InfoSessionDataEntry( title: "Descriptions", content: infoSession.description ) ) models = models.filter { $0.content?.isEmpty == false } return models } let topOverlayView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) let bottomOverlayView = GradientView().then { $0.translatesAutoresizingMaskIntoConstraints = false $0.isUserInteractionEnabled = false $0.gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.0).cgColor, UIColor.white.cgColor] $0.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5) $0.gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0) } let backButton = Button(type: .system).then { $0.translatesAutoresizingMaskIntoConstraints = false $0.setImage(R.image.back()?.withRenderingMode(.alwaysTemplate), for: .normal) $0.tintColor = UIColor.primary let buttonSize: CGFloat = 32.0 // Setup background color $0.backgroundColor = UIColor.white $0.layer.cornerRadius = buttonSize / 2.0 $0.imageView?.contentMode = .scaleAspectFit $0.widthAnchor.constrain(to: $0.heightAnchor) $0.widthAnchor.constrain(to: buttonSize) } weak var hideBackButtonDelayedTask: Task? override func preferredPresentationStyle() -> PresentationStyle? { return .embedded } required init(infoSession: InfoSession) { self.infoSession = infoSession super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let tableView = UITableView().then { $0.translatesAutoresizingMaskIntoConstraints = false $0.backgroundColor = UIColor.clear $0.separatorStyle = .none $0.rowHeight = UITableViewAutomaticDimension $0.sectionHeaderHeight = 32 TitleAccessoryButtonTableViewCell.registerInTableView($0) TitleContentTableViewCell.registerInTableView($0) } override func commonInit() { super.commonInit() title = infoSession.employer } override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() } private func setupViews() { view.backgroundColor = UIColor.white view.addSubview(tableView) tableView.dataSource = self tableView.delegate = self view.addSubview(topOverlayView) topOverlayView.frame = UIApplication.shared.statusBarFrame view.addSubview(bottomOverlayView) view.addSubview(backButton) backButton.addTarget(controlEvents: .touchUpInside) { button in let _ = self.navigationController?.popViewController(animated: true) } backButton.setHidden(true, animated: false) } private func setupConstraints() { tableView.constrainToFullSizeInSuperview() bottomOverlayView.leadingAnchor.constrain(to: view.leadingAnchor) bottomOverlayView.trailingAnchor.constrain(to: view.trailingAnchor) bottomOverlayView.bottomAnchor.constrain(to: view.bottomAnchor) bottomOverlayView.heightAnchor.constrain(to: view.heightAnchor, multiplier: 0.25) backButton.leadingAnchor.constrain(to: view.leadingAnchor, constant: 16) backButton.topAnchor.constrain(to: view.topAnchor, constant: UIApplication.shared.statusBarFrame.height + 16) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) enableSwipBackGesture() } } extension DetailViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 + infoSessionDataEntries.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withClass: TitleAccessoryButtonTableViewCell.self, forIndexPath: indexPath) cell.selectionStyle = .none cell.configure(with: infoSession) return cell } else { let cell = tableView.dequeueReusableCell(withClass: TitleContentTableViewCell.self, forIndexPath: indexPath) cell.contentView.layoutMargins = UIEdgeInsets(top: 16, left: 16, bottom: 8, right: 16) let model = infoSessionDataEntries[indexPath.row - 1] cell.configure(with: model) cell.selectionStyle = model.cellSelectAction == nil ? .none : .default return cell } } } extension DetailViewController: UITableViewDelegate { // MARK: - Rows func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return TitleAccessoryButtonTableViewCell.estimatedHeight() } else { return TitleContentTableViewCell.estimatedHeight() } } // MARK: - Selections func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.row == 0 { return } else { let dataEntry = infoSessionDataEntries[indexPath.row - 1] dataEntry.cellSelectAction?(indexPath, nil, tableView) } } } // MARK: - UIScrollViewDelegate extension DetailViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { updateBottomOverlayView(scrollView) updateBackButton(scrollView) } private func updateBottomOverlayView(_ scrollView: UIScrollView) { // TableView first appears if scrollView.contentSize.width == 0.0 { bottomOverlayView.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5) return } let bottomPosition = scrollView.contentOffset.y + scrollView.height let bottomSpacing = scrollView.contentSize.height - bottomPosition // Scrolls excceeds boundary guard bottomSpacing >= 0 else { bottomOverlayView.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.99) return } if bottomSpacing < bottomOverlayView.height { bottomOverlayView.gradientLayer.startPoint = CGPoint(x: 0.5, y: min(1.0 - bottomSpacing / bottomOverlayView.height, 0.99)) } else { bottomOverlayView.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5) } } private func updateBackButton(_ scrollView: UIScrollView) { // TableView first appears if scrollView.contentSize.width == 0.0 { return } // Scrolls to the top, hide back button if scrollView.contentOffset.y == -scrollView.contentInset.top { hideBackButtonDelayedTask?.cancel() hideBackButtonDelayedTask = delay(1.2) { self.backButton.setHidden(true, animated: true, duration: 0.33) } } else { backButton.setHidden(false, animated: true, duration: 0.33) } } }
gpl-3.0
904b7a4433e310f81457b7043a52ffdf
27.19788
166
0.72995
3.873786
false
false
false
false
zvonicek/SpriteKit-Pong
TDT4240-pong/SKTUtils/CGPoint+Extensions.swift
12
6559
/* * Copyright (c) 2013-2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import CoreGraphics import SpriteKit public extension CGPoint { /** * Creates a new CGPoint given a CGVector. */ public init(vector: CGVector) { self.init(x: vector.dx, y: vector.dy) } /** * Given an angle in radians, creates a vector of length 1.0 and returns the * result as a new CGPoint. An angle of 0 is assumed to point to the right. */ public init(angle: CGFloat) { self.init(x: cos(angle), y: sin(angle)) } /** * Adds (dx, dy) to the point. */ public mutating func offset(#dx: CGFloat, dy: CGFloat) -> CGPoint { x += dx y += dy return self } /** * Returns the length (magnitude) of the vector described by the CGPoint. */ public func length() -> CGFloat { return sqrt(x*x + y*y) } /** * Returns the squared length of the vector described by the CGPoint. */ public func lengthSquared() -> CGFloat { return x*x + y*y } /** * Normalizes the vector described by the CGPoint to length 1.0 and returns * the result as a new CGPoint. */ func normalized() -> CGPoint { let len = length() return len>0 ? self / len : CGPoint.zeroPoint } /** * Normalizes the vector described by the CGPoint to length 1.0. */ public mutating func normalize() -> CGPoint { self = normalized() return self } /** * Calculates the distance between two CGPoints. Pythagoras! */ public func distanceTo(point: CGPoint) -> CGFloat { return (self - point).length() } /** * Returns the angle in radians of the vector described by the CGPoint. * The range of the angle is -π to π; an angle of 0 points to the right. */ public var angle: CGFloat { return atan2(y, x) } } /** * Adds two CGPoint values and returns the result as a new CGPoint. */ public func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } /** * Increments a CGPoint with the value of another. */ public func += (inout left: CGPoint, right: CGPoint) { left = left + right } /** * Adds a CGVector to this CGPoint and returns the result as a new CGPoint. */ public func + (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x + right.dx, y: left.y + right.dy) } /** * Increments a CGPoint with the value of a CGVector. */ public func += (inout left: CGPoint, right: CGVector) { left = left + right } /** * Subtracts two CGPoint values and returns the result as a new CGPoint. */ public func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } /** * Decrements a CGPoint with the value of another. */ public func -= (inout left: CGPoint, right: CGPoint) { left = left - right } /** * Subtracts a CGVector from a CGPoint and returns the result as a new CGPoint. */ public func - (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x - right.dx, y: left.y - right.dy) } /** * Decrements a CGPoint with the value of a CGVector. */ public func -= (inout left: CGPoint, right: CGVector) { left = left - right } /** * Multiplies two CGPoint values and returns the result as a new CGPoint. */ public func * (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x * right.x, y: left.y * right.y) } /** * Multiplies a CGPoint with another. */ public func *= (inout left: CGPoint, right: CGPoint) { left = left * right } /** * Multiplies the x and y fields of a CGPoint with the same scalar value and * returns the result as a new CGPoint. */ public func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } /** * Multiplies the x and y fields of a CGPoint with the same scalar value. */ public func *= (inout point: CGPoint, scalar: CGFloat) { point = point * scalar } /** * Multiplies a CGPoint with a CGVector and returns the result as a new CGPoint. */ public func * (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x * right.dx, y: left.y * right.dy) } /** * Multiplies a CGPoint with a CGVector. */ public func *= (inout left: CGPoint, right: CGVector) { left = left * right } /** * Divides two CGPoint values and returns the result as a new CGPoint. */ public func / (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x / right.x, y: left.y / right.y) } /** * Divides a CGPoint by another. */ public func /= (inout left: CGPoint, right: CGPoint) { left = left / right } /** * Divides the x and y fields of a CGPoint by the same scalar value and returns * the result as a new CGPoint. */ public func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } /** * Divides the x and y fields of a CGPoint by the same scalar value. */ public func /= (inout point: CGPoint, scalar: CGFloat) { point = point / scalar } /** * Divides a CGPoint by a CGVector and returns the result as a new CGPoint. */ public func / (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x / right.dx, y: left.y / right.dy) } /** * Divides a CGPoint by a CGVector. */ public func /= (inout left: CGPoint, right: CGVector) { left = left / right } /** * Performs a linear interpolation between two CGPoint values. */ public func lerp(#start: CGPoint, #end: CGPoint, #t: CGFloat) -> CGPoint { return start + (end - start) * t }
mit
fc694ac299d3d96561a861273c572e1f
25.763265
80
0.667531
3.673389
false
false
false
false
pj4533/OpenPics
Pods/SKPhotoBrowser/SKPhotoBrowser/SKPhotoBrowser.swift
1
30150
// // SKPhotoBrowser.swift // SKViewExample // // Created by suzuki_keishi on 2015/10/01. // Copyright © 2015 suzuki_keishi. All rights reserved. // import UIKit @objc public protocol SKPhotoBrowserDelegate { func didShowPhotoAtIndex(index:Int) optional func willDismissAtPageIndex(index:Int) optional func didDismissAtPageIndex(index:Int) } public let SKPHOTO_LOADING_DID_END_NOTIFICATION = "photoLoadingDidEndNotification" // MARK: - SKPhotoBrowser public class SKPhotoBrowser: UIViewController, UIScrollViewDelegate{ final let pageIndexTagOffset:Int = 1000 // animation property final let animationDuration:Double = 0.35 // device property final let screenBound = UIScreen.mainScreen().bounds var screenWidth :CGFloat { return screenBound.size.width } var screenHeight:CGFloat { return screenBound.size.height } // custom abilities public var displayToolbar:Bool = true public var displayCounterLabel:Bool = true public var displayBackAndForwardButton:Bool = true public var disableVerticalSwipe:Bool = false public var isForceStatusBarHidden:Bool = false // tool for controls private var applicationWindow:UIWindow! private var toolBar:UIToolbar! private var toolCounterLabel:UILabel! private var toolCounterButton:UIBarButtonItem! private var toolPreviousButton:UIBarButtonItem! private var toolNextButton:UIBarButtonItem! private var pagingScrollView:UIScrollView! private var panGesture:UIPanGestureRecognizer! private var doneButton:UIButton! private var doneButtonShowFrame:CGRect = CGRectMake(5, 5, 44, 44) private var doneButtonHideFrame:CGRect = CGRectMake(5, -20, 44, 44) // photo's paging private var visiblePages:Set<SKZoomingScrollView> = Set() private var initialPageIndex:Int = 0 private var currentPageIndex:Int = 0 // senderView's property private var senderViewForAnimation:UIView? private var senderViewOriginalFrame:CGRect = CGRectZero private var senderOriginImage:UIImage! private var resizableImageView:UIImageView = UIImageView() // for status check property private var isDraggingPhoto:Bool = false private var isViewActive:Bool = false private var isPerformingLayout:Bool = false private var isStatusBarOriginallyHidden:Bool = false // scroll property private var firstX:CGFloat = 0.0 private var firstY:CGFloat = 0.0 // timer private var controlVisibilityTimer:NSTimer! // delegate public weak var delegate: SKPhotoBrowserDelegate? // photos var photos:[SKPhotoProtocol] = [SKPhotoProtocol]() var numberOfPhotos:Int{ return photos.count } // MARK - Initializer required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nil, bundle: nil) setup() } public convenience init(photos:[AnyObject]) { self.init(nibName: nil, bundle: nil) for anyObject in photos{ if let photo = anyObject as? SKPhotoProtocol { photo.checkCache() self.photos.append(photo) } } } public convenience init(originImage:UIImage, photos:[AnyObject], animatedFromView:UIView) { self.init(nibName: nil, bundle: nil) self.senderOriginImage = originImage self.senderViewForAnimation = animatedFromView for anyObject in photos{ if let photo = anyObject as? SKPhotoProtocol { photo.checkCache() self.photos.append(photo) } } } func setup() { applicationWindow = (UIApplication.sharedApplication().delegate?.window)! modalPresentationStyle = UIModalPresentationStyle.Custom modalPresentationCapturesStatusBarAppearance = true modalTransitionStyle = UIModalTransitionStyle.CrossDissolve NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleSKPhotoLoadingDidEndNotification:", name: SKPHOTO_LOADING_DID_END_NOTIFICATION, object: nil) } // MARK: - override public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() view.clipsToBounds = true // setup paging let pagingScrollViewFrame = frameForPagingScrollView() pagingScrollView = UIScrollView(frame: pagingScrollViewFrame) pagingScrollView.pagingEnabled = true pagingScrollView.delegate = self pagingScrollView.showsHorizontalScrollIndicator = true pagingScrollView.showsVerticalScrollIndicator = true pagingScrollView.backgroundColor = UIColor.blackColor() pagingScrollView.contentSize = contentSizeForPagingScrollView() view.addSubview(pagingScrollView) // toolbar toolBar = UIToolbar(frame: frameForToolbarAtOrientation()) toolBar.backgroundColor = UIColor.clearColor() toolBar.clipsToBounds = true toolBar.translucent = true toolBar.setBackgroundImage(UIImage(), forToolbarPosition: .Any, barMetrics: .Default) view.addSubview(toolBar) if !displayToolbar { toolBar.hidden = true } // arrows:back let bundle = NSBundle(forClass: SKPhotoBrowser.self) let previousBtn = UIButton(type: .Custom) let previousImage = UIImage(named: "SKPhotoBrowser.bundle/images/btn_common_back_wh", inBundle: bundle, compatibleWithTraitCollection: nil) ?? UIImage() previousBtn.frame = CGRectMake(0, 0, 44, 44) previousBtn.imageEdgeInsets = UIEdgeInsetsMake(13.25, 17.25, 13.25, 17.25) previousBtn.setImage(previousImage, forState: .Normal) previousBtn.addTarget(self, action: "gotoPreviousPage", forControlEvents: .TouchUpInside) previousBtn.contentMode = .Center toolPreviousButton = UIBarButtonItem(customView: previousBtn) // arrows:next let nextBtn = UIButton(type: .Custom) let nextImage = UIImage(named: "SKPhotoBrowser.bundle/images/btn_common_forward_wh", inBundle: bundle, compatibleWithTraitCollection: nil) ?? UIImage() nextBtn.frame = CGRectMake(0, 0, 44, 44) nextBtn.imageEdgeInsets = UIEdgeInsetsMake(13.25, 17.25, 13.25, 17.25) nextBtn.setImage(nextImage, forState: .Normal) nextBtn.addTarget(self, action: "gotoNextPage", forControlEvents: .TouchUpInside) nextBtn.contentMode = .Center toolNextButton = UIBarButtonItem(customView: nextBtn) toolCounterLabel = UILabel(frame: CGRectMake(0, 0, 95, 40)) toolCounterLabel.textAlignment = .Center toolCounterLabel.backgroundColor = UIColor.clearColor() toolCounterLabel.font = UIFont(name: "Helvetica", size: 16.0) toolCounterLabel.textColor = UIColor.whiteColor() toolCounterLabel.shadowColor = UIColor.darkTextColor() toolCounterLabel.shadowOffset = CGSizeMake(0.0, 1.0) toolCounterButton = UIBarButtonItem(customView: toolCounterLabel) // close let doneImage = UIImage(named: "SKPhotoBrowser.bundle/images/btn_common_close_wh", inBundle: bundle, compatibleWithTraitCollection: nil) ?? UIImage() doneButton = UIButton(type: UIButtonType.Custom) doneButton.setImage(doneImage, forState: UIControlState.Normal) doneButton.frame = doneButtonHideFrame doneButton.imageEdgeInsets = UIEdgeInsetsMake(15.25, 15.25, 15.25, 15.25) doneButton.backgroundColor = UIColor.clearColor() doneButton.addTarget(self, action: "doneButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) doneButton.alpha = 0.0 view.addSubview(doneButton) // gesture panGesture = UIPanGestureRecognizer(target: self, action: "panGestureRecognized:") panGesture.minimumNumberOfTouches = 1 panGesture.maximumNumberOfTouches = 1 // transition (this must be last call of view did load.) performPresentAnimation() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) isStatusBarOriginallyHidden = UIApplication.sharedApplication().statusBarHidden reloadData() } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() isPerformingLayout = true pagingScrollView.frame = frameForPagingScrollView() pagingScrollView.contentSize = contentSizeForPagingScrollView() pagingScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex) toolBar.frame = frameForToolbarAtOrientation() isPerformingLayout = false } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) isViewActive = true } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(true) pagingScrollView = nil visiblePages = Set() NSNotificationCenter.defaultCenter().removeObserver(self) } public override func prefersStatusBarHidden() -> Bool { if isForceStatusBarHidden { return true } if isDraggingPhoto { if isStatusBarOriginallyHidden { return true } else { return false } } else { return areControlsHidden() } } // MARK: - notification public func handleSKPhotoLoadingDidEndNotification(notification: NSNotification){ let photo = notification.object as! SKPhotoProtocol let page = pageDisplayingAtPhoto(photo) if page.photo == nil { return } if page.photo.underlyingImage != nil{ page.displayImage() loadAdjacentPhotosIfNecessary(photo) } else { page.displayImageFailure() } } public func loadAdjacentPhotosIfNecessary(photo: SKPhotoProtocol){ let page = pageDisplayingAtPhoto(photo) let pageIndex = (page.tag - pageIndexTagOffset) if currentPageIndex == pageIndex{ if pageIndex > 0 { // Preload index - 1 let previousPhoto = photoAtIndex(pageIndex - 1) if previousPhoto.underlyingImage == nil { previousPhoto.loadUnderlyingImageAndNotify() } } if pageIndex < numberOfPhotos - 1 { // Preload index + 1 let nextPhoto = photoAtIndex(pageIndex + 1) if nextPhoto.underlyingImage == nil { nextPhoto.loadUnderlyingImageAndNotify() } } } } // MARK: - initialize / setup public func reloadData(){ performLayout() view.setNeedsLayout() } public func performLayout(){ isPerformingLayout = true // for tool bar let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil) var items = [UIBarButtonItem]() items.append(flexSpace) if numberOfPhotos > 1 && displayBackAndForwardButton { items.append(toolPreviousButton) } if displayCounterLabel { items.append(flexSpace) items.append(toolCounterButton) items.append(flexSpace) } else { items.append(flexSpace) } if numberOfPhotos > 1 && displayBackAndForwardButton { items.append(toolNextButton) } items.append(flexSpace) toolBar.setItems(items, animated: false) updateToolbar() // reset local cache visiblePages.removeAll() // set content offset pagingScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex) // tile page tilePages() didStartViewingPageAtIndex(currentPageIndex) isPerformingLayout = false // add pangesture if need if !disableVerticalSwipe { view.addGestureRecognizer(panGesture) } } public func prepareForClosePhotoBrowser(){ applicationWindow.removeGestureRecognizer(panGesture) NSObject.cancelPreviousPerformRequestsWithTarget(self) delegate?.willDismissAtPageIndex?(currentPageIndex) } // MARK: - frame calculation public func frameForPagingScrollView() -> CGRect{ var frame = view.bounds frame.origin.x -= 10 frame.size.width += (2 * 10) return frame } public func frameForToolbarAtOrientation() -> CGRect{ let currentOrientation = UIApplication.sharedApplication().statusBarOrientation var height:CGFloat = navigationController?.navigationBar.frame.size.height ?? 44 if UIInterfaceOrientationIsLandscape(currentOrientation){ height = 32 } return CGRectMake(0, view.bounds.size.height - height, view.bounds.size.width, height) } public func frameForToolbarHideAtOrientation() -> CGRect{ let currentOrientation = UIApplication.sharedApplication().statusBarOrientation var height:CGFloat = navigationController?.navigationBar.frame.size.height ?? 44 if UIInterfaceOrientationIsLandscape(currentOrientation){ height = 32 } return CGRectMake(0, view.bounds.size.height + height, view.bounds.size.width, height) } public func frameForCaptionView(captionView:SKCaptionView, index: Int) -> CGRect{ let pageFrame = frameForPageAtIndex(index) let captionSize = captionView.sizeThatFits(CGSizeMake(pageFrame.size.width, 0)) let navHeight = navigationController?.navigationBar.frame.size.height ?? 44 return CGRectMake(pageFrame.origin.x, pageFrame.size.height - captionSize.height - navHeight, pageFrame.size.width, captionSize.height) } public func frameForPageAtIndex(index: Int) -> CGRect { let bounds = pagingScrollView.bounds var pageFrame = bounds pageFrame.size.width -= (2 * 10) pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + 10 return pageFrame } public func contentOffsetForPageAtIndex(index:Int) -> CGPoint{ let pageWidth = pagingScrollView.bounds.size.width let newOffset = CGFloat(index) * pageWidth return CGPointMake(newOffset, 0) } public func contentSizeForPagingScrollView() -> CGSize { let bounds = pagingScrollView.bounds return CGSizeMake(bounds.size.width * CGFloat(numberOfPhotos), bounds.size.height) } // MARK: - Toolbar public func updateToolbar(){ if numberOfPhotos > 1 { toolCounterLabel.text = "\(currentPageIndex + 1) / \(numberOfPhotos)" } else { toolCounterLabel.text = nil } toolPreviousButton.enabled = (currentPageIndex > 0) toolNextButton.enabled = (currentPageIndex < numberOfPhotos - 1) } // MARK: - panGestureRecognized public func panGestureRecognized(sender:UIPanGestureRecognizer){ let scrollView = pageDisplayedAtIndex(currentPageIndex) let viewHeight = scrollView.frame.size.height let viewHalfHeight = viewHeight/2 var translatedPoint = sender.translationInView(self.view) // gesture began if sender.state == .Began { firstX = scrollView.center.x firstY = scrollView.center.y senderViewForAnimation?.hidden = (currentPageIndex == initialPageIndex) isDraggingPhoto = true setNeedsStatusBarAppearanceUpdate() } translatedPoint = CGPointMake(firstX, firstY + translatedPoint.y) scrollView.center = translatedPoint view.opaque = true // gesture end if sender.state == .Ended{ if scrollView.center.y > viewHalfHeight+40 || scrollView.center.y < viewHalfHeight-40 { if currentPageIndex == initialPageIndex { performCloseAnimationWithScrollView(scrollView) return } let finalX:CGFloat = firstX var finalY:CGFloat = 0.0 let windowHeight = applicationWindow.frame.size.height if scrollView.center.y > viewHalfHeight+30 { finalY = windowHeight * 2.0 } else { finalY = -(viewHalfHeight) } let animationDuration = 0.35 UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn) scrollView.center = CGPointMake(finalX, finalY) UIView.commitAnimations() dismissPhotoBrowser() } else { // Continue Showing View isDraggingPhoto = false setNeedsStatusBarAppearanceUpdate() let velocityY:CGFloat = 0.35 * sender.velocityInView(self.view).y let finalX:CGFloat = firstX let finalY:CGFloat = viewHalfHeight let animationDuration = Double(abs(velocityY) * 0.0002 + 0.2) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn) scrollView.center = CGPointMake(finalX, finalY) UIView.commitAnimations() } } } // MARK: - perform animation public func performPresentAnimation(){ view.alpha = 0.0 pagingScrollView.alpha = 0.0 if let sender = senderViewForAnimation { senderViewOriginalFrame = (sender.superview?.convertRect(sender.frame, toView:nil))! let fadeView = UIView(frame: CGRectMake(0, 0, screenWidth, screenHeight)) fadeView.backgroundColor = UIColor.clearColor() applicationWindow.addSubview(fadeView) let imageFromView = senderOriginImage != nil ? senderOriginImage : getImageFromView(sender) resizableImageView = UIImageView(image: imageFromView) resizableImageView.frame = senderViewOriginalFrame resizableImageView.clipsToBounds = true resizableImageView.contentMode = .ScaleAspectFill applicationWindow.addSubview(resizableImageView) sender.hidden = true let scaleFactor = imageFromView.size.width / screenWidth let finalImageViewFrame = CGRectMake(0, (screenHeight/2) - ((imageFromView.size.height / scaleFactor)/2), screenWidth, imageFromView.size.height / scaleFactor) UIView.animateWithDuration(animationDuration, animations: { () -> Void in self.resizableImageView.layer.frame = finalImageViewFrame self.doneButton.alpha = 1.0 self.doneButton.frame = self.doneButtonShowFrame }, completion: { (Bool) -> Void in self.view.alpha = 1.0 self.pagingScrollView.alpha = 1.0 self.resizableImageView.alpha = 0.0 fadeView.removeFromSuperview() }) } else { let fadeView = UIView(frame: CGRectMake(0, 0, screenWidth, screenHeight)) fadeView.backgroundColor = UIColor.clearColor() applicationWindow.addSubview(fadeView) UIView.animateWithDuration(animationDuration, animations: { () -> Void in self.doneButton.alpha = 1.0 self.doneButton.frame = self.doneButtonShowFrame }, completion: { (Bool) -> Void in self.view.alpha = 1.0 self.pagingScrollView.alpha = 1.0 fadeView.removeFromSuperview() }) } } public func performCloseAnimationWithScrollView(scrollView:SKZoomingScrollView) { view.hidden = true let fadeView = UIView(frame: CGRectMake(0, 0, screenWidth, screenHeight)) fadeView.backgroundColor = UIColor.blackColor() fadeView.alpha = 1.0 applicationWindow.addSubview(fadeView) resizableImageView.alpha = 1.0 resizableImageView.clipsToBounds = true resizableImageView.contentMode = .ScaleAspectFill applicationWindow.addSubview(resizableImageView) UIView.animateWithDuration(animationDuration, animations: { () -> () in fadeView.alpha = 0.0 self.resizableImageView.layer.frame = self.senderViewOriginalFrame }, completion: { (Bool) -> () in self.resizableImageView.removeFromSuperview() fadeView.removeFromSuperview() self.dismissPhotoBrowser() }) } public func dismissPhotoBrowser(){ modalTransitionStyle = .CrossDissolve senderViewForAnimation?.hidden = false prepareForClosePhotoBrowser() dismissViewControllerAnimated(true){ self.delegate?.didDismissAtPageIndex?(self.currentPageIndex) } } //MARK: - image private func getImageFromView(sender:UIView) -> UIImage{ UIGraphicsBeginImageContextWithOptions(sender.frame.size, true, 2.0) sender.layer.renderInContext(UIGraphicsGetCurrentContext()!) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } public func imageForPhoto(photo: SKPhotoProtocol)-> UIImage?{ if photo.underlyingImage != nil { return photo.underlyingImage } else { photo.loadUnderlyingImageAndNotify() return nil } } // MARK: - paging public func initializePageIndex(index: Int){ var i = index if index >= numberOfPhotos { i = numberOfPhotos - 1 } initialPageIndex = i currentPageIndex = i if isViewLoaded() { jumpToPageAtIndex(index) if isViewActive { tilePages() } } } public func jumpToPageAtIndex(index:Int){ if index < numberOfPhotos { let pageFrame = frameForPageAtIndex(index) pagingScrollView.setContentOffset(CGPointMake(pageFrame.origin.x - 10, 0), animated: true) updateToolbar() } hideControlsAfterDelay() } public func photoAtIndex(index: Int) -> SKPhotoProtocol { return photos[index] } public func gotoPreviousPage(){ jumpToPageAtIndex(currentPageIndex - 1) } public func gotoNextPage(){ jumpToPageAtIndex(currentPageIndex + 1) } public func tilePages(){ let visibleBounds = pagingScrollView.bounds var firstIndex = Int(floor((CGRectGetMinX(visibleBounds) + 10 * 2) / CGRectGetWidth(visibleBounds))) var lastIndex = Int(floor((CGRectGetMaxX(visibleBounds) - 10 * 2 - 1) / CGRectGetWidth(visibleBounds))) if firstIndex < 0 { firstIndex = 0 } if firstIndex > numberOfPhotos - 1 { firstIndex = numberOfPhotos - 1 } if lastIndex < 0 { lastIndex = 0 } if lastIndex > numberOfPhotos - 1 { lastIndex = numberOfPhotos - 1 } for(var index = firstIndex; index <= lastIndex; index++){ if !isDisplayingPageForIndex(index){ let page = SKZoomingScrollView(frame: view.frame, browser: self) page.frame = frameForPageAtIndex(index) page.tag = index + pageIndexTagOffset page.photo = photoAtIndex(index) visiblePages.insert(page) pagingScrollView.addSubview(page) // if exists caption, insert if let captionView = captionViewForPhotoAtIndex(index) { captionView.frame = frameForCaptionView(captionView, index: index) pagingScrollView.addSubview(captionView) // ref val for control page.captionView = captionView } } } } private func didStartViewingPageAtIndex(index: Int){ delegate?.didShowPhotoAtIndex(index) } private func captionViewForPhotoAtIndex(index: Int) -> SKCaptionView?{ let photo = photoAtIndex(index) if let _ = photo.caption { let captionView = SKCaptionView(photo: photo) captionView.alpha = areControlsHidden() ? 0.0 : 1.0 return captionView } return nil } public func isDisplayingPageForIndex(index: Int) -> Bool{ for page in visiblePages{ if (page.tag - pageIndexTagOffset) == index { return true } } return false } public func pageDisplayedAtIndex(index: Int) -> SKZoomingScrollView { var thePage:SKZoomingScrollView = SKZoomingScrollView() for page in visiblePages { if (page.tag - pageIndexTagOffset) == index { thePage = page break } } return thePage } public func pageDisplayingAtPhoto(photo: SKPhotoProtocol) -> SKZoomingScrollView { var thePage:SKZoomingScrollView = SKZoomingScrollView() for page in visiblePages { if page.photo === photo { thePage = page break } } return thePage } // MARK: - Control Hiding / Showing public func cancelControlHiding(){ if controlVisibilityTimer != nil{ controlVisibilityTimer.invalidate() controlVisibilityTimer = nil } } public func hideControlsAfterDelay(){ // reset cancelControlHiding() // start controlVisibilityTimer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "hideControls:", userInfo: nil, repeats: false) } public func hideControls(timer: NSTimer){ setControlsHidden(true, animated: true, permanent: false) } public func toggleControls(){ setControlsHidden(!areControlsHidden(), animated: true, permanent: false) } public func setControlsHidden(hidden:Bool, animated:Bool, permanent:Bool){ cancelControlHiding() var captionViews = Set<SKCaptionView>() for page in visiblePages { if page.captionView != nil { captionViews.insert(page.captionView) } } UIView.animateWithDuration(0.35, animations: { () -> Void in let alpha:CGFloat = hidden ? 0.0 : 1.0 self.toolBar.alpha = alpha self.toolBar.frame = hidden ? self.frameForToolbarHideAtOrientation() : self.frameForToolbarAtOrientation() self.doneButton.alpha = alpha self.doneButton.frame = hidden ? self.doneButtonHideFrame : self.doneButtonShowFrame for v in captionViews { v.alpha = alpha } }, completion: { (Bool) -> Void in }) if !permanent { hideControlsAfterDelay() } setNeedsStatusBarAppearanceUpdate() } public func areControlsHidden() -> Bool{ return toolBar.alpha == 0.0 } // MARK: - Button public func doneButtonPressed(sender:UIButton) { if currentPageIndex == initialPageIndex { performCloseAnimationWithScrollView(pageDisplayedAtIndex(currentPageIndex)) } else { dismissPhotoBrowser() } } // MARK: - UIScrollView Delegate public func scrollViewDidScroll(scrollView: UIScrollView) { if !isViewActive { return } if isPerformingLayout { return } // tile page tilePages() // Calculate current page let visibleBounds = pagingScrollView.bounds var index = Int(floor(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds))) if index < 0 { index = 0 } if index > numberOfPhotos - 1 { index = numberOfPhotos } let previousCurrentPage = currentPageIndex currentPageIndex = index if currentPageIndex != previousCurrentPage { didStartViewingPageAtIndex(currentPageIndex) updateToolbar() } } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { setControlsHidden(true, animated: true, permanent: false) } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { hideControlsAfterDelay() } }
gpl-3.0
0dccaeec11117a3a8e7b7e3a420b0205
35.194478
172
0.612359
5.707876
false
false
false
false
st3fan/firefox-ios
SyncTests/HistorySynchronizerTests.swift
8
10361
/* 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 Shared import Account import Storage @testable import Sync import XCGLogger import XCTest import SwiftyJSON private let log = Logger.syncLogger class MockSyncDelegate: SyncDelegate { func displaySentTab(for url: URL, title: String, from deviceName: String?) { } } class DBPlace: Place { var isDeleted = false var shouldUpload = false var serverModified: Timestamp? var localModified: Timestamp? } class MockSyncableHistory { var wasReset: Bool = false var places = [GUID: DBPlace]() var remoteVisits = [GUID: Set<Visit>]() var localVisits = [GUID: Set<Visit>]() init() { } fileprivate func placeForURL(url: String) -> DBPlace? { return findOneValue(places) { $0.url == url } } } extension MockSyncableHistory: ResettableSyncStorage { func resetClient() -> Success { self.wasReset = true return succeed() } } extension MockSyncableHistory: SyncableHistory { // TODO: consider comparing the timestamp to local visits, perhaps opting to // not delete the local place (and instead to give it a new GUID) if the visits // are newer than the deletion. // Obviously this'll behave badly during reconciling on other devices: // they might apply our new record first, renaming their local copy of // the old record with that URL, and thus bring all the old visits back to life. // Desktop just finds by GUID then deletes by URL. func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Deferred<Maybe<()>> { self.remoteVisits.removeValue(forKey: guid) self.localVisits.removeValue(forKey: guid) self.places.removeValue(forKey: guid) return succeed() } func hasSyncedHistory() -> Deferred<Maybe<Bool>> { let has = self.places.values.contains(where: { $0.serverModified != nil }) return deferMaybe(has) } /** * This assumes that the provided GUID doesn't already map to a different URL! */ func ensurePlaceWithURL(_ url: String, hasGUID guid: GUID) -> Success { // Find by URL. if let existing = self.placeForURL(url: url) { let p = DBPlace(guid: guid, url: url, title: existing.title) p.isDeleted = existing.isDeleted p.serverModified = existing.serverModified p.localModified = existing.localModified self.places.removeValue(forKey: existing.guid) self.places[guid] = p } return succeed() } func storeRemoteVisits(_ visits: [Visit], forGUID guid: GUID) -> Success { // Strip out existing local visits. // We trust that an identical timestamp and type implies an identical visit. var remote = Set<Visit>(visits) if let local = self.localVisits[guid] { remote.subtract(local) } // Visits are only ever added. if var r = self.remoteVisits[guid] { r.formUnion(remote) } else { self.remoteVisits[guid] = remote } return succeed() } func insertOrUpdatePlace(_ place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> { // See if we've already applied this one. if let existingModified = self.places[place.guid]?.serverModified { if existingModified == modified { log.debug("Already seen unchanged record \(place.guid).") return deferMaybe(place.guid) } } // Make sure that we collide with any matching URLs -- whether locally // modified or not. Then overwrite the upstream and merge any local changes. return self.ensurePlaceWithURL(place.url, hasGUID: place.guid) >>> { if let existingLocal = self.places[place.guid] { if existingLocal.shouldUpload { log.debug("Record \(existingLocal.guid) modified locally and remotely.") log.debug("Local modified: \(existingLocal.localModified ??? "nil"); remote: \(modified).") // Should always be a value if marked as changed. if let localModified = existingLocal.localModified, localModified > modified { // Nothing to do: it's marked as changed. log.debug("Discarding remote non-visit changes!") self.places[place.guid]?.serverModified = modified return deferMaybe(place.guid) } else { log.debug("Discarding local non-visit changes!") self.places[place.guid]?.shouldUpload = false } } else { log.debug("Remote record exists, but has no local changes.") } } else { log.debug("Remote record doesn't exist locally.") } // Apply the new remote record. let p = DBPlace(guid: place.guid, url: place.url, title: place.title) p.localModified = Date.now() p.serverModified = modified p.isDeleted = false self.places[place.guid] = p return deferMaybe(place.guid) } } func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> { // TODO. return deferMaybe([]) } func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> { // TODO. return deferMaybe([]) } func markAsSynchronized(_: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> { // TODO return deferMaybe(0) } func markAsDeleted(_: [GUID]) -> Success { // TODO return succeed() } func onRemovedAccount() -> Success { // TODO return succeed() } func doneApplyingRecordsAfterDownload() -> Success { return succeed() } func doneUpdatingMetadataAfterUpload() -> Success { return succeed() } } class HistorySynchronizerTests: XCTestCase { private func applyRecords(records: [Record<HistoryPayload>], toStorage storage: SyncableHistory & ResettableSyncStorage) -> (synchronizer: HistorySynchronizer, prefs: Prefs, scratchpad: Scratchpad) { let delegate = MockSyncDelegate() // We can use these useless values because we're directly injecting decrypted // payloads; no need for real keys etc. let prefs = MockProfilePrefs() let scratchpad = Scratchpad(b: KeyBundle.random(), persistingTo: prefs) let synchronizer = HistorySynchronizer(scratchpad: scratchpad, delegate: delegate, basePrefs: prefs, why: .scheduled) let expectation = self.expectation(description: "Waiting for application.") var succeeded = false synchronizer.applyIncomingToStorage(storage, records: records) .upon({ result in succeeded = result.isSuccess expectation.fulfill() }) waitForExpectations(timeout: 10, handler: nil) XCTAssertTrue(succeeded, "Application succeeded.") return (synchronizer, prefs, scratchpad) } func testRecordSerialization() { let id = "abcdefghi" let modified: Timestamp = 0 // Ignored in upload serialization. let sortindex = 1 let ttl = 12345 let json: JSON = JSON([ "id": id, "visits": [], "histUri": "http://www.slideshare.net/swadpasc/bpm-edu-netseminarscepwithreactionrulemlprova", "title": "Semantic Complex Event Processing with \(Character(UnicodeScalar(11)))Reaction RuleML 1.0 and Prova", ]) let payload = HistoryPayload(json) let record = Record<HistoryPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex, ttl: ttl) let k = KeyBundle.random() let s = keysPayloadSerializer(keyBundle: k, { (x: HistoryPayload) -> JSON in x.json }) let converter = { (x: JSON) -> HistoryPayload in HistoryPayload(x) } let f = keysPayloadFactory(keyBundle: k, converter) let serialized = s(record)! let envelope = EnvelopeJSON(serialized) // With a badly serialized payload, we get null JSON! let p = f(envelope.payload) XCTAssertFalse(p!.json.isNull()) // When we round-trip, the payload should be valid, and we'll get a record here. let roundtripped = Record<HistoryPayload>.fromEnvelope(envelope, payloadFactory: f) XCTAssertNotNil(roundtripped) } func testApplyRecords() { let earliest = Date.now() let empty = MockSyncableHistory() let noRecords = [Record<HistoryPayload>]() // Apply no records. let _ = self.applyRecords(records: noRecords, toStorage: empty) // Hey look! Nothing changed. XCTAssertTrue(empty.places.isEmpty) XCTAssertTrue(empty.remoteVisits.isEmpty) XCTAssertTrue(empty.localVisits.isEmpty) // Apply one remote record. let jA = "{\"id\":\"aaaaaa\",\"histUri\":\"http://foo.com/\",\"title\": \"ñ\",\"visits\":[{\"date\":1222222222222222,\"type\":1}]}" let pA = HistoryPayload.fromJSON(JSON(parseJSON: jA))! let rA = Record<HistoryPayload>(id: "aaaaaa", payload: pA, modified: earliest + 10000, sortindex: 123, ttl: 1000000) let (_, prefs, _) = self.applyRecords(records: [rA], toStorage: empty) // The record was stored. This is checking our mock implementation, but real storage should work, too! XCTAssertEqual(1, empty.places.count) XCTAssertEqual(1, empty.remoteVisits.count) XCTAssertEqual(1, empty.remoteVisits["aaaaaa"]!.count) XCTAssertTrue(empty.localVisits.isEmpty) // Test resetting now that we have a timestamp. XCTAssertFalse(empty.wasReset) XCTAssertTrue(HistorySynchronizer.resetSynchronizerWithStorage(empty, basePrefs: prefs, collection: "history").value.isSuccess) XCTAssertTrue(empty.wasReset) } }
mpl-2.0
6971fae586a70c31fd930195aaaff741
37.513011
203
0.61583
4.807425
false
false
false
false
ilyathewhite/Euler
EulerSketch/EulerSketch/Commands/Sketch+Circle.swift
1
5652
// // Sketch+Circle.swift // EulerSketchOSX // // Created by Ilya Belenkiy on 7/25/16. // Copyright © 2016 Ilya Belenkiy. All rights reserved. // import Foundation extension Sketch { /// Adds a tangent segment to a circle from a given point. The tangent name is formed by the point from which the tangent is constructed /// (an existing point) and the point of tangency (a new point). The `selector` parameter selects a specific tangent point from the available tangent points. @discardableResult public func addTangent(_ tangentName: String, toCircle circleName: String, style: DrawingStyle? = nil, selector: @escaping ([HSPoint]) -> HSPoint?) -> FigureResult { do { let tangentPointNames = try scanPointNames(tangentName, expected: .segment) guard tangentPointNames.count == 2 else { throw SketchError.invalidFigureName(name: tangentName, kind: .segment) } let point1: PointFigure = try getFigure(name: tangentPointNames[0]) let circle: CircleFigure = try getFigure(name: circleName) let point2 = try PointFigure(name: tangentPointNames[1], usedFigures: FigureSet([point1, circle])) { let tangentPoints = circle.tangentPointsFromPoint(point: point1) return selector(tangentPoints) } try addExtraFigure(point2, style: style) return addSegment(tangentName, style: style) } catch { return .failure(error) } } /// Adds a circle with a given center (specified by its coordinates) and radius. /// The circle center is fixed, but the radius may be changed by dragging the circle. @discardableResult public func addCircle(_ circleName: String, withCenter center: BasicPoint, hintRadius radius: Double, style: DrawingStyle? = nil) -> FigureResult { do { let figure = CircleFigure(name: circleName, center.x, center.y, hintRadius: radius) return .success(try addFigure(figure, style: style)) } catch { return .failure(error) } } /// Adds a circle with a given center (specified by the point name) and a radius. /// The radius can be changed by dragging the circle, and the center can be change as well if the point is draggable. @discardableResult public func addCircle(_ circleName: String, withCenter centerName: String, hintRadius radius: Double, style: DrawingStyle? = nil) -> FigureResult { do { let O: PointFigure = try getFigure(name: centerName) let figure = try CircleFigure(name: circleName, center: O, hintRadius: radius) return .success(try addFigure(figure, style: style)) } catch { return .failure(error) } } /// Adds a circle with a given center (specified by the point name) that goes through a given point. @discardableResult public func addCircle(_ circleName: String, withCenter centerName: String, throughPoint pointName: String, style: DrawingStyle? = nil) -> FigureResult { do { let O: PointFigure = try getFigure(name: centerName) let A: PointFigure = try getFigure(name: pointName) let figure = try CircleFigure(name: circleName, center: O, throughPoint: A) return .success(try addFigure(figure, style: style)) } catch { return .failure(error) } } /// Adds a circle going through 3 points (if those points form a triangle). @discardableResult public func addCircle(_ circleName: String, throughPoints p1: String, _ p2: String, _ p3: String, style: DrawingStyle? = nil) -> FigureResult { do { func f(_ pointName: String) throws -> PointFigure { return try getFigure(name: pointName) } let figure = try CircleFigure(name: circleName, point1: try f(p1), point2: try f(p2), point3: try f(p3)) return .success(try addFigure(figure, style: style)) } catch { return .failure(error) } } } extension Sketch { /// Adds a radical axis for 2 circles. The bisector name is expected to be a lowercase letter. @discardableResult public func addRadicalAxis(_ radicalAxisName: String, ofCircles circle1Name: String, _ circle2Name: String, style: DrawingStyle? = nil) -> FigureResult { do { guard let circle1Figure = findFigure(name: circle1Name, prefix: .circle) as? CircleFigure else { throw SketchError.invalidFigureName(name: circle1Name, kind: .segment) } guard let circle2Figure = findFigure(name: circle2Name, prefix: .circle) as? CircleFigure else { throw SketchError.invalidFigureName(name: circle2Name, kind: .segment) } let circles = FigureSet([circle1Figure, circle2Figure]) let pointName = FigureNamePrefix.Part.rawValue + "radicalAxisPoint_" + radicalAxisName let pointFigure = try PointFigure(name: pointName, usedFigures: circles) { guard let (point, _) = HSCircle.radicalAxis(circle1: circle1Figure, circle2: circle2Figure) else { return nil } return point } pointFigure.hidden = true try addExtraFigure(pointFigure) let figure = try CompoundLineFigure(name: radicalAxisName, vertex: pointFigure, usedFigures: circles) { guard let (_, angle) = HSCircle.radicalAxis(circle1: circle1Figure, circle2: circle2Figure) else { return 0 } return angle } return .success(try addFigure(figure, style: style)) } catch { return .failure(error) } } }
mit
0194d36eb9801c13a951aeab899003d6
44.208
187
0.656521
4.303884
false
false
false
false
attaswift/Attabench
BenchmarkModel/Time.swift
2
6944
// Copyright © 2017 Károly Lőrentey. // This file is part of Attabench: https://github.com/attaswift/Attabench // For licensing information, see the file LICENSE.md in the Git repository above. import Foundation import BigInt private let picosecondsPerSecond = 1e12 extension BigInt { func dividingWithRounding<I: BinaryInteger>(by divisor: I) -> BigInt { let (q, r) = self.quotientAndRemainder(dividingBy: BigInt(divisor)) if r > divisor / 2 { return q + 1 } if r == divisor / 2 { return q & 1 == 0 ? q : q + 1 } return q } } public struct Time: CustomStringConvertible, LosslessStringConvertible, ExpressibleByFloatLiteral, Comparable, Codable { var picoseconds: BigInt public init(floatLiteral value: Double) { self.init(value) } public init(picoseconds: BigInt) { self.picoseconds = picoseconds } public init(_ timeInterval: TimeInterval) { self.picoseconds = BigInt(timeInterval * picosecondsPerSecond) } public init(orderOfMagnitude order: Int) { if order < -12 { self.picoseconds = 0; return } self.picoseconds = BigInt(10).power(order + 12) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() guard let picoseconds = BigInt(try container.decode(String.self), radix: 10) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid big integer value") } self.picoseconds = picoseconds } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(String(self.picoseconds, radix: 10)) } public var seconds: TimeInterval { return TimeInterval(picoseconds) / picosecondsPerSecond } public static let second = Time(picoseconds: BigInt(1e12)) public static let millisecond = Time(picoseconds: BigInt(1e9)) public static let microsecond = Time(picoseconds: BigInt(1e6)) public static let nanosecond = Time(picoseconds: BigInt(1e3)) public static let picosecond = Time(picoseconds: 1) public static let zero = Time(picoseconds: 0) private static let scaleFromSuffix: [String: Time] = [ "": .second, "s": .second, "ms": .millisecond, "µs": .microsecond, "us": .microsecond, "ns": .nanosecond, "ps": .picosecond ] private static let floatingPointCharacterSet = CharacterSet(charactersIn: "+-0123456789.e") public init?(_ description: String) { var description = description.trimmingCharacters(in: .whitespacesAndNewlines) description = description.lowercased() if let i = description.rangeOfCharacter(from: Time.floatingPointCharacterSet.inverted) { let number = description.prefix(upTo: i.lowerBound) let suffix = description.suffix(from: i.lowerBound) guard let value = Double(number) else { return nil } guard let scale = Time.scaleFromSuffix[String(suffix)] else { return nil } self = Time(value * scale.seconds) } else { guard let value = Double(description) else { return nil } self = Time(value) } } public var description: String { if self == .zero { return "0" } if self < .nanosecond { return "\(picoseconds)ps" } if self < .microsecond { return String(format: "%.3gns", Double(picoseconds) / 1e3) } if self < .millisecond { return String(format: "%.3gµs", Double(picoseconds) / 1e6) } if self < .second { return String(format: "%.3gms", Double(picoseconds) / 1e9) } if self.seconds < 1000 { return String(format: "%.3gs", seconds) } return String(format: "%gs", seconds.rounded()) } public static func ==(left: Time, right: Time) -> Bool { return left.picoseconds == right.picoseconds } public static func <(left: Time, right: Time) -> Bool { return left.picoseconds < right.picoseconds } public func dividingWithRounding<I: BinaryInteger>(by divisor: I) -> Time { return Time(picoseconds: picoseconds.dividingWithRounding(by: divisor)) } public func squared() -> TimeSquared { return self * self } } public func +(left: Time, right: Time) -> Time { return Time(picoseconds: left.picoseconds + right.picoseconds) } public func +=(left: inout Time, right: Time) { left.picoseconds += right.picoseconds } public func -(left: Time, right: Time) -> Time { return Time(picoseconds: left.picoseconds - right.picoseconds) } public func -=(left: inout Time, right: Time) { left.picoseconds -= right.picoseconds } public func *<I: BinaryInteger>(left: I, right: Time) -> Time { return Time(picoseconds: BigInt(left) * right.picoseconds) } public func /<I: BinaryInteger>(left: Time, right: I) -> Time { return Time(picoseconds: left.picoseconds / BigInt(right)) } public func *(left: Time, right: Time) -> TimeSquared { return TimeSquared(value: left.picoseconds * right.picoseconds) } public func *<I: BinaryInteger>(left: I, right: TimeSquared) -> TimeSquared { return TimeSquared(value: BigInt(left) * right.value) } public func +(left: TimeSquared, right: TimeSquared) -> TimeSquared { return TimeSquared(value: left.value + right.value) } public func +=(left: inout TimeSquared, right: TimeSquared) { left.value += right.value } public func -(left: TimeSquared, right: TimeSquared) -> TimeSquared { return TimeSquared(value: left.value - right.value) } public func -=(left: inout TimeSquared, right: TimeSquared) { left.value -= right.value } public struct TimeSquared: Comparable, Codable { var value: BigInt // picoseconds^2 public init() { self.value = 0 } init(value: BigInt) { self.value = value } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() guard let value = BigInt(try container.decode(String.self), radix: 10) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid big integer value") } self.value = value } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(String(self.value, radix: 10)) } public func squareRoot() -> Time { return Time(picoseconds: value.squareRoot()) } public func dividingWithRounding<I: BinaryInteger>(by divisor: I) -> TimeSquared { return TimeSquared(value: value.dividingWithRounding(by: divisor)) } public static func ==(left: TimeSquared, right: TimeSquared) -> Bool { return left.value == right.value } public static func <(left: TimeSquared, right: TimeSquared) -> Bool { return left.value < right.value } }
mit
6fea0bd909ee1ad4fe5c481953b37842
36.106952
120
0.660182
4.015625
false
false
false
false
mlilback/rc2SwiftClient
ClientCore/Parsing/RmdDocument.swift
1
11145
// // RmdDocument.swift // ClientCore // // Created by Mark Lilback on 12/10/19. // Copyright © 2019 Rc2. All rights reserved. // import Cocoa import Parsing import Logging import ReactiveSwift // liikely don't need to do R highlighting here. Output is html, and editor uses without parrsing. // editor needs to use without chunks internal let parserLog = Logger(label: "io.rc2.rc2parser") fileprivate extension Array { /// same as using subscript, but it does range checking and returns nil if invalid index func element(at index: Int) -> Element? { guard index >= 0, index < count else { return nil } return self[index] } } /// The parser uses a ChunkType, which inlcudes inline chunks. This type is for the types of chunks /// that appear at the top level of a document (e.g. no inline) public enum RootChunkType: String, Codable { case markdown, code, equation public init(_ pctype: ChunkType) { switch pctype { case .markdown: self = .markdown case .code: self = .code case .equation: self = .equation default: fatalError("unsupported chunk type \(pctype)") } } } public enum ParserError: Error { case parseFailed case invalidParser } extension Notification.Name { /// the object is the document that was updated. userInfo contains the the array of changed indexes with the key RmdDocument.changedIndexesKey public static let rmdDocumentUpdated = NSNotification.Name("rmdDocumentUpdated") } /// A parsed representation of an .Rmd file public class RmdDocument: CustomDebugStringConvertible { /// used with the userInfo dictionary of a rmdDocumentUpdated notification public static let changedIndexesKey = "changedIndexes" /// Updates document with contents. /// If a code chunks changes and there are code chunks after it, the document will be completely refreshed. /// /// - Parameter document: The document to update. /// - Parameter with: The updated content. /// /// - Returns: If nil, consider the doucment completely refreshed. Otherwise, the indexes of chunks that just changed content. /// - Throws: any exception raised while creating a new document. public class func update(document: RmdDocument, with content: String) throws -> [Int]? { guard let parser = document.parser else { throw ParserError.invalidParser } guard document.attributedString.string != content else { return [] } let newDoc = try RmdDocument(contents: content, parser: parser) defer { document.chunks = newDoc.chunks // do the ones that trigger signals/notifications last document.frontMatter = newDoc.frontMatter document.textStorage.replace(with: newDoc.textStorage) } // if number of chunks changed, we can't list indexes that changed guard newDoc.chunks.count == document.chunks.count else { return nil } var changed = [Int]() let firstCodeIndex = document.chunks.firstIndex(where: { $0.chunkType == .code }) ?? -1 for idx in 0..<newDoc.chunks.count { // compare if chunks are similar guard let oldChunk = document.chunks[idx] as? RmdDocChunk, let newChunk = newDoc.chunks[idx] as? RmdDocChunk, oldChunk != newChunk else { return nil } if newChunk.chunkType == .code && idx < firstCodeIndex { return nil } if newDoc.string(for: newChunk) != document.string(for: oldChunk) { changed.append(idx) document.chunks[idx] = newChunk } } NotificationCenter.default.post(name: .rmdDocumentUpdated, object: document, userInfo: [RmdDocument.changedIndexesKey: changed]) return changed } private var textStorage = NSTextStorage() private weak var parser: Rc2RmdParser? /// the chunks in this document public private(set) var chunks = [RmdDocumentChunk]() /// any frontmatter that exists in the document public private(set) var frontMatter: String? /// the attributed contents of this document public var attributedString: NSAttributedString { return NSAttributedString(attributedString: textStorage) } /// version of contents after removing any text attachments public var rawString: String { return textStorage.string.replacingOccurrences(of: "\u{0ffe}", with: "") } public var debugDescription: String { return "RmdDocument with \(chunks.count) chunks" } /// types of ranges that can be requested public enum RangeType: Int { /// the contents without delimiters, arguments, etc. case inner /// the full contents of the chunk, including delimiters case outer } /// Creates a structure document. /// /// - Parameters: /// - contents: Initial contents of the document. public init(contents: String, parser: Rc2RmdParser) throws { self.parser = parser textStorage.append(NSAttributedString(string: contents)) let pchunks = try parser.parse(input: contents) for (idx, aChunk) in pchunks.enumerated() { chunks.append(RmdDocChunk(rawChunk: aChunk, number: idx, parentRange: aChunk.range)) } } /// Get array of chunks that intersect with range /// - Parameters: /// - range: The range to check for /// - delta: The change in the range. Currently unused public func chunks(in range: NSRange, delta: Int = 0) -> [RmdDocumentChunk] { return chunks.compactMap { guard $0.parsedRange.contains(range.lowerBound) || $0.parsedRange.contains(range.upperBound) else { return nil } return $0 } } /// Returns the contents of chunk as a String /// - Parameter chunk: The chunk whose ccntent will be returned /// - Parameter type: Which range should be used. Defaults to .outer /// - Returns: the requested contents public func string(for chunk: RmdDocumentChunk, type: RangeType = .outer) -> String { if chunk.isInline { guard let child = chunk as? RmdDocChunk else { fatalError("can't have inline without parent") } return textStorage.attributedSubstring(from: type == .outer ? child.parsedRange : child.innerRange).string } return attrString(for: chunk, rangeType: type).string.replacingOccurrences(of: "\u{0ffe}", with: "") } /// Returns the contents of chunk as an NSAttributedString /// - Parameter chunk: The chunk whose ccntent will be returned /// - Parameter type: Which range should be used. Defaults to .outer /// - Returns: the requested contents public func attrtibutedString(for chunk: RmdDocumentChunk, type: RangeType = .outer) -> NSAttributedString { return attrString(for: chunk, rangeType: .inner) } /// internal method to reduce code duplication of bounds checking private func attrString(for chunk: RmdDocumentChunk, rangeType: RangeType) -> NSAttributedString { guard let realChunk = chunk as? RmdDocChunk else { fatalError("invalid chunk index") } // FIXME: ckeck that chunks.contains(chunk) guard chunks.first(where: { (myChunk) -> Bool in (myChunk as! RmdDocChunk) == realChunk }) != nil else { fatalError("chunk does not belong to me") } let desiredString = textStorage.attributedSubstring(from: rangeType == .outer ? realChunk.chunkRange : realChunk.innerRange) if chunk.isExecutable || chunk.isEquation { let baseStr = NSMutableAttributedString(attributedString: desiredString) do { if let parser = parser { let rng = NSRange(location: 0, length: baseStr.length) if chunk.isExecutable { let rhigh = try RHighlighter(baseStr, range: rng) try rhigh.start() } else if chunk.isEquation { parser.highlightEquation(contents: baseStr, range: rng) } } } catch { parserLog.info("error highligthing R code: \(error.localizedDescription)") } return baseStr } return desiredString } } extension RmdDocument: Equatable { public static func == (lhs: RmdDocument, rhs: RmdDocument) -> Bool { return lhs.textStorage == rhs.textStorage } } /// A chunk in a document public protocol RmdDocumentChunk { /// the type of the chunk (.markdown, .code, .equation, including inline) var chunkType: ChunkType { get } /// true if a n inline code or equation chunk var isInline: Bool { get } /// trrue if it is a code module that can be executed var isExecutable: Bool { get } /// true if an equation or inline equation var isEquation: Bool { get } /// the range of this chunk in the document /// - Tag: parsedRange var parsedRange: NSRange { get } /// the range of this chunk in the document excluding delimiters e.q. (```, $$) var innerRange: NSRange { get } /// if isInline, the range of this chunk in its parent chunk. Otherwise, same as [parsedRange](x-source-tag://parsedRange) var chunkRange: NSRange { get } /// for .markdown chunks, any inline chunks. an empty arrary for other chunk types var children: [RmdDocumentChunk] { get } } public extension RmdDocumentChunk { /// Find the child range at location /// - Parameter location: A valid index in the document string /// - Returns: The inline chunk that encompasses that location, or nil if it is not part of an inline chunk func childContaining(location: Int) -> RmdDocumentChunk? { return children.first(where: {$0.innerRange.contains(location) } ) } } internal class RmdDocChunk: RmdDocumentChunk { let chunkType: ChunkType let parserChunk: AnyChunk let chunkNumber: Int public private(set) var children = [RmdDocumentChunk]() init(rawChunk: AnyChunk, number: Int, parentRange: NSRange) { chunkType = rawChunk.type parserChunk = rawChunk chunkNumber = number parsedRange = rawChunk.range innerRange = rawChunk.innerRange if rawChunk.isInline { chunkRange = NSRange(location: parsedRange.location - parentRange.location, length: parsedRange.length) } else { chunkRange = parsedRange } if let mchunk = rawChunk.asMarkdown { // need to add inline chunks var i = 0 mchunk.inlineChunks.forEach { ichk in children.append(RmdDocChunk(rawChunk: ichk, number: i, parentRange: parsedRange)) i += 1 } } if rawChunk.type == .code { // FIXME: set name and argument } } /// true if this is a code or inline code chunk public var isExecutable: Bool { return chunkType == .code || parserChunk.type == .inlineCode } /// true if an equation or inline equation public var isEquation: Bool { return chunkType == .equation || parserChunk.type == .inlineEquation } /// trtue if this is an inline chunk public var isInline: Bool { return parserChunk.isInline } /// the range of this chunk in the entire document public let parsedRange: NSRange /// the range of the content (without open/close markers) public let innerRange: NSRange /// If an inline chunk, the range of this chunk inside the parent markdown chunk. /// Otherwise, the same a parsedRange public let chunkRange: NSRange // if this is a .code chunk, the argument in the chunk header public private(set) var arguments: String? // if this is a code chunk, the name given to the chunk public private(set) var name: String? public var executableCode: String { guard isExecutable else { return "" } if let cchunk = parserChunk.asCode { return cchunk.code } if let icc = parserChunk.asInlineCode { return icc.code } fatalError("not possible") } } extension RmdDocChunk: Equatable { static func == (lhs: RmdDocChunk, rhs: RmdDocChunk) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } }
isc
5e970e597964207e49ec26e29a8e8a0b
36.648649
143
0.723528
3.697412
false
false
false
false
dzt/ftp
ios/FTP/SplashViewController.swift
1
1742
// // SplashViewController.swift // FTP // // Created by Peter on 3/21/16. // Copyright © 2016 FTP. All rights reserved. // import UIKit import Alamofire class SplashViewController: UIViewController { @IBOutlet weak var logo: UIImageView! override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func viewDidLoad() { super.viewDidLoad() let jeremyGif = UIImage.gifWithName("anim") logo.image = jeremyGif let timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("ftpServ"), userInfo: nil, repeats: false) } let url = "https://ftpadmin-ftpadmin.rhcloud.com/status" func ftpServ() { Alamofire.request(.GET, url, encoding:.JSON).responseJSON { response in switch response.result { case .Success(let JSON): print("Success with JSON: \(JSON)") let response = JSON as! NSDictionary let status = response.objectForKey("status") as! String if (status == "closed") { self.performSegueWithIdentifier("closedSegue", sender: self) } else if(status == "open") { self.performSegueWithIdentifier("showApp", sender: self) } print(response) case .Failure(let error): print("Request failed with error: \(error)") } } } }
mit
c95a60a333159456e41684228d25888b
26.650794
139
0.504308
5.580128
false
false
false
false
rnystrom/GitHawk
Pods/ContextMenu/ContextMenu/ContextMenu+Options.swift
1
1281
// // ContextMenuOptions.swift // ThingsUI // // Created by Ryan Nystrom on 3/10/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import UIKit extension ContextMenu { /// Display and behavior options for a menu. public struct Options { /// Animation durations and properties. let durations: AnimationDurations /// Appearance properties for the menu container. let containerStyle: ContainerStyle /// Style options for menu behavior. let menuStyle: MenuStyle /// Trigger haptic feedback when the menu is shown. let hapticsStyle: HapticFeedbackStyle? /// The position relative to the source view (if provided). let position: Position public init( durations: AnimationDurations = AnimationDurations(), containerStyle: ContainerStyle = ContainerStyle(), menuStyle: MenuStyle = .default, hapticsStyle: HapticFeedbackStyle? = nil, position: Position = .default ) { self.durations = durations self.containerStyle = containerStyle self.menuStyle = menuStyle self.hapticsStyle = hapticsStyle self.position = position } } }
mit
f61494a3541edb26e0f5658b7af2c491
26.826087
67
0.625
5.12
false
false
false
false
rnystrom/GitHawk
Pods/cmark-gfm-swift/Source/ASTOperations.swift
1
7055
// // ASTOperations.swift // CommonMark // // Created by Chris Eidhof on 23/05/15. // Copyright (c) 2015 Unsigned Integer. All rights reserved. // import Foundation extension Sequence where Iterator.Element == Block { /// Apply a transformation to each block-level element in the sequence. /// Performs a deep traversal of the element tree. /// /// - parameter f: The transformation function that will be recursively applied /// to each block-level element in `elements`. /// /// The function returns an array of elements, which allows you to transform /// one element into several (or none). Return an array containing only the /// unchanged element to not transform that element at all. Return an empty /// array to delete an element from the result. /// - returns: A Markdown document containing the results of the transformation, /// represented as an array of block-level elements. public func deepApply(_ f: (Block) throws -> [Block]) rethrows -> [Block] { return try flatMap { try $0.deepApply(f) } } /// Apply a transformation to each inline element in the sequence /// Performs a deep traversal of the element tree. /// /// - parameter f: The transformation function that will be recursively applied /// to each inline element in `elements`. /// /// The function returns an array of elements, which allows you to transform /// one element into several (or none). Return an array containing only the /// unchanged element to not transform that element at all. Return an empty /// array to delete an element from the result. /// - returns: A Markdown document containing the results of the transformation, /// represented as an array of block-level elements. public func deepApply(_ f: (Inline) throws -> [Inline]) rethrows -> [Block] { return try flatMap { try $0.deepApply(f) } } } extension Block { public func deepApply(_ f: (Block) throws -> [Block]) rethrows -> [Block] { switch self { case let .list(items, type): let newItems = try items.map { item in try item.deepApply(f) } return try f(.list(items: newItems, type: type)) case .blockQuote(let items): return try f(.blockQuote(items: try items.deepApply(f))) default: return try f(self) } } public func deepApply(_ f: (Inline) throws -> [Inline]) rethrows -> [Block] { switch self { case .paragraph(let children): return [.paragraph(text: try children.deepApply(f))] case let .list(items, type): return [.list(items: try items.map { try $0.deepApply(f) }, type: type)] case .blockQuote(let items): return [.blockQuote(items: try items.deepApply(f))] case let .heading(text, level): return [.heading(text: try text.deepApply(f), level: level)] default: return [self] } } } extension Sequence where Iterator.Element == Inline { public func deepApply(_ f: (Inline) throws -> [Inline]) rethrows -> [Inline] { return try flatMap { try $0.deepApply(f) } } } extension Inline { public func deepApply(_ f: (Inline) throws -> [Inline]) rethrows -> [Inline] { switch self { case .emphasis(let children): return try f(.emphasis(children: try children.deepApply(f))) case .strong(let children): return try f(Inline.strong(children: try children.deepApply(f))) case let .link(children, title, url): return try f(Inline.link(children: try children.deepApply(f), title: title, url: url)) case let .image(children, title, url): return try f(Inline.image(children: try children.deepApply(f), title: title, url: url)) default: return try f(self) } } } extension Sequence where Iterator.Element == Block { /// Performs a deep 'flatMap' operation over all _block-level elements_ in a /// sequence. Performs a deep traversal over all block-level elements /// in the element tree, applies `f` to each element, and returns the flattened /// results. /// /// Use this function to extract data from a Markdown document. E.g. you could /// extract the texts and levels of all headers in a document to build a table /// of contents. /// /// - parameter f: The function that will be recursively applied to each /// block-level element in `elements`. /// /// The function returns an array, which allows you to extract zero, one, or /// multiple pieces of data from each element. Return an empty array to ignore /// this element in the result. /// - returns: A flattened array of the results of all invocations of `f`. public func deep<A>(collect: (Block) throws -> [A]) rethrows -> [A] { return try flatMap { try $0.deep(collect: collect) } } public func deep<A>(collect: (Inline) throws -> [A]) rethrows -> [A] { return try flatMap { try $0.deep(collect: collect) } } } extension Block { public func deep<A>(collect: (Block) throws -> [A]) rethrows -> [A] { var result: [A] switch self { case .list(let items, _): result = try items.joined().deep(collect: collect) case .blockQuote(let items): result = try items.deep(collect: collect) default: result = [] } try result.append(contentsOf: collect(self)) return result } public func deep<A>(collect: (Inline) throws -> [A]) rethrows -> [A] { var result: [A] switch self { case .list(let items, _): result = try items.joined().deep(collect: collect) case .blockQuote(let items): result = try items.deep(collect: collect) case .heading(let items, _): result = try items.deep(collect: collect) case .paragraph(let items): result = try items.deep(collect: collect) default: result = [] } return result } } extension Inline { public func deep<A>(collect: (Inline) throws -> [A]) rethrows -> [A] { var result: [A] switch self { case .emphasis(let children): result = try children.deep(collect: collect) case .strong(let children): result = try children.deep(collect: collect) case let .link(children, _, _): result = try children.deep(collect: collect) case let .image(children, _, _): result = try children.deep(collect: collect) default: result = [] } result.append(contentsOf: try collect(self)) return result } } extension Sequence where Iterator.Element == Inline { public func deep<A>(collect: (Inline) throws -> [A]) rethrows -> [A] { return try flatMap { try $0.deep(collect: collect) } } }
mit
6929044fa216266ddb452963b52fffc3
37.342391
99
0.608079
4.234694
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00152-swift-parser-parsetypeidentifier.swift
1
1721
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -typecheck protocol kj : gf { func gf class t<u : t> { } protocol qp { r on r t = on r lk = on } class gf<kj : kj, t : kj ih kj.vu == t> : qp { } class gf<kj, t> { } protocol kj { r vu } ed vu = sr ed ts: o -> o = { fe $gf } l on: o = { (kj: o, lk: o -> o) -> o po fe lk(kj) }(vu, ts) l qp: o = { kj, lk po fe lk(kj) }(vu, ts) class qp<lk : gf, vu : gf ih lk.on == vu> { } protocol gf { r on r t } struct kj<kj : gf> : gf { r on = kj r t = qp<kj<kj>, on> } func qp(kj: v, ji: v) -> (((v, v) -> v) -> v) { fe { (ut: (v, v) -> v) -> v po fe ut(kj, ji) } } func gf(p: (((v, v) -> v) -> v)) -> v { fe p({ (ut: v, fe:v) -> v po fe ut }) } gf(qp(sr, qp(s, w))) protocol t { r n func gf(n) } struct cb<hg> : t { on k on.t = { } { vu) { kj } } protocol lk { class func t() } class on: lk{ class func t {} protocol qp { class func kj() } class gf: qp { class func kj() { } } (gf() x qp).ji.gf vu.kj == lk.kj> { } protocol t { r kj } func lk() { ({}) } protocol t { r n } class lk<dc> { rq <t: t ih t.n == dc>(t: t.n) { nm gf = gf } protocol t { r k } struct n<u : t> { l kj: u l t: u.k } protocol lk { r ml func >) } struct dc : lk { r ml = o func vu< u.k == ml>(lk: n<u>)
apache-2.0
6e201963b912866c973d33c18d56566e
15.235849
79
0.499709
2.479827
false
false
false
false
CoBug92/MyRestaurant
MyRestraunts/AboutUsTableViewController.swift
1
2593
// // AboutUsTableViewController.swift // MyRestaurant // // Created by Богдан Костюченко on 24/10/2016. // Copyright © 2016 Bogdan Kostyuchenko. All rights reserved. // import UIKit class AboutUsTableViewController: UITableViewController { let sectionsHeaders = ["We are in the social networks", "Our sites"] let sectionsContent = [["facebook", "vk", "linkdin"],["I have not a site yet:("]] let firstSectionLinks = ["https://www.facebook.com/CoBugs", "https://vk.com/kostyuchenkobogdan", "https://www.linkedin.com/in/bogdan-kostyuchenko-17119ba0?trk=nav_responsive_tab_profile_pic"] override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView(frame: CGRect.zero) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return sectionsHeaders.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return sectionsContent[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = sectionsContent[indexPath.section][indexPath.row] return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionsHeaders[section] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 0: switch indexPath.row { case 0..<firstSectionLinks.count: performSegue(withIdentifier: "showWebPageSegue", sender: self) default: break } default: break } tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showWebPageSegue" { if let indexPath = tableView.indexPathForSelectedRow { let destinationVC = segue.destination as! WebViewController destinationVC.url = URL(string: firstSectionLinks[indexPath.row]) } } } }
gpl-3.0
dd0468bff532bf009b81e32d531c594b
33.810811
195
0.650233
4.906667
false
false
false
false
IndisputableLabs/Swifthereum
Swifthereum/Classes/Geth/EthereumClient.swift
1
11145
// // EthereumClient.swift // GethTest // // Created by Ronald Mannak on 9/23/17. // Copyright © 2017 Indisputable. All rights reserved. // import Foundation import Geth import BigInt protocol EthereumClientProtocol { // func ethereumClient(_: EthereumClient, didDoSomething like: String) } /* Solidity includes 7 basic types, listed below: hash: 256-bit, 32-byte data chunk, indexable into bytes and operable with bitwise operations. uint: 256-bit unsigned integer, operable with bitwise and unsigned arithmetic operations. int: 256-bit signed integer, operable with bitwise and signed arithmetic operations. string32: zero-terminated ASCII string of maximum length 32-bytes (256-bit). address: account identifier, similar to a 160-bit hash type. bool: two-state value. */ /** EthereumClient provides access to the Ethereum APIs. Do or don't create one? Let Node create one for you? */ open class EthereumClient { open let _gethEthereumClient: GethEthereumClient public init(client: GethEthereumClient) { _gethEthereumClient = client } /** NewEthereumClient connects a client to the given URL. - parameter path: Path */ public init(path: String = "ws://10.0.2.2:8546") throws{ var error: NSError? = nil let gethClient = GethNewEthereumClient(path, &error) guard error == nil else { throw(error!)} guard let client = gethClient else { throw(SwifthereumError.invalidPath) } _gethEthereumClient = client } /** CallContract executes a message call transaction, which is directly executed in the VM of the node, but never mined into the blockchain. blockNumber selects the block height at which the call runs. It can be <0, in which case the code is taken from the latest known block. Note that state from very old blocks might not be available. Original method: ```-(NSData*)callContract:(GethContext*)ctx msg:(GethCallMsg*)msg number:(int64_t)number error:(NSError**)error;``` */ open func call(message: Message, context: Context = .cancel, number: Int = 0) throws -> Data { return try _gethEthereumClient.callContract(context._gethContext, msg: message._callMsg, number: Int64(number)) } /** EstimateGas tries to estimate the gas needed to execute a specific transaction based on the current pending state of the backend blockchain. There is no guarantee that this is the true gas limit requirement as other transactions may be added or removed by miners, but it should provide a basis for setting a reasonable default. Original method: ```-(GethBigInt*)estimateGas:(GethContext*)ctx msg:(GethCallMsg*)msg error:(NSError**)error;``` */ open func estimateGas(for message: Message, context: Context = .cancel) throws -> Gas { return try _gethEthereumClient.estimateGas(context._gethContext, msg: message._callMsg).getInt64() } /** FilterLogs executes a filter query. Original method: ```-(GethLogs*)filterLogs:(GethContext*)ctx query:(GethFilterQuery*)query error:(NSError**)error;``` */ open func filterLogs(query: FilterQuery, context: Context = .cancel) throws -> [Log] { return try _gethEthereumClient.filterLogs(context._gethContext, query: query._gethFilterQuery).arrays() } /** GetBalanceAt returns the wei balance of the given account. The block number can be <0, in which case the balance is taken from the latest known block. Original method: ```-(GethBigInt*)getBalanceAt:(GethContext*)ctx account:(GethAddress*)account number:(int64_t)number error:(NSError**)error;``` */ open func balance(for account: Address, token: ERC20Token? = nil, block: BlockNumber = -1, context: Context = .cancel) throws -> Wei { if let token = token { fatalError() // TODO: } else { let balance = try _gethEthereumClient.getBalanceAt(context._gethContext, account: account._gethAddress, number: block) return Wei(balance) } } /** GetBlockByHash returns the given full block. Original Method: ```-(GethBlock*)getBlockByHash:(GethContext*)ctx hash:(GethHash*)hash error:(NSError**)error;``` */ open func block(byHash hash: Hash, context: Context = .cancel) throws -> Block { let gethBlock = try _gethEthereumClient.getBlockByHash(context._gethContext, hash: hash._gethHash) return try Block(block: gethBlock) } /** GetBlockByNumber returns a block from the current canonical chain. If number is <0, the latest known block is returned. Orignal Method: ```- (GethBlock*)getBlockByNumber:(GethContext*)ctx number:(int64_t)number error:(NSError**)error;``` */ open func block(byNumber number: Int64, context: Context = .cancel) throws -> Block { let gethBlock = try _gethEthereumClient.getBlockByNumber(context._gethContext, number: number) return try Block(block: gethBlock) } /** * GetCodeAt returns the contract code of the given account. The block number can be <0, in which case the code is taken from the latest known block. */ //- (NSData*)getCodeAt:(GethContext*)ctx account:(GethAddress*)account number:(int64_t)number error:(NSError**)error; /** * GetHeaderByHash returns the block header with the given hash. */ //- (GethHeader*)getHeaderByHash:(GethContext*)ctx hash:(GethHash*)hash error:(NSError**)error; /** * GetHeaderByNumber returns a block header from the current canonical chain. If number is <0, the latest known header is returned. */ //- (GethHeader*)getHeaderByNumber:(GethContext*)ctx number:(int64_t)number error:(NSError**)error; /** * GetNonceAt returns the account nonce of the given account. The block number can be <0, in which case the nonce is taken from the latest known block. */ //- (BOOL)getNonceAt:(GethContext*)ctx account:(GethAddress*)account number:(int64_t)number nonce:(int64_t*)nonce error:(NSError**)error; /** GetPendingBalanceAt returns the wei balance of the given account in the pending state. Original method: ```- (GethBigInt*)getPendingBalanceAt:(GethContext*)ctx account:(GethAddress*)account error:(NSError**)error;``` */ open func pendingBalance(account: Address, context: Context = .cancel) throws -> Wei { return try Wei(_gethEthereumClient.getPendingBalance(at: context._gethContext, account: account._gethAddress)) } /** GetPendingCodeAt returns the contract code of the given account in the pending state. - (NSData*)getPendingCodeAt:(GethContext*)ctx account:(GethAddress*)account error:(NSError**)error; */ /** GetPendingStorageAt returns the value of key in the contract storage of the given account in the pending state. Original method: ```- (NSData*)getPendingStorageAt:(GethContext*)ctx account:(GethAddress*)account key:(GethHash*)key error:(NSError**)error;``` */ // open func /** GetPendingTransactionCount returns the total number of transactions in the pending state. Orignal method: ```- (BOOL)getPendingTransactionCount:(GethContext*)ctx count:(long*)count error:(NSError**)error;``` */ // open func pendingTransactionCoint /** GetTransactionCount returns the total number of transactions in the given block. Original method: ```- (BOOL)getTransactionCount:(GethContext*)ctx hash:(GethHash*)hash count:(long*)count error:(NSError**)error;``` */ open func transactionCountForBlock(_ hash: Hash, context: Context = .cancel) throws -> Int { var count: Int = 0 try _gethEthereumClient.getTransactionCount(context._gethContext, hash: hash._gethHash, count: &count) return count } /** SyncProgress retrieves the current progress of the sync algorithm. If there's no sync currently running, it returns nil. Original method: -(GethSyncProgress*)syncProgress:(GethContext*)ctx error:(NSError**)error; */ open func syncProgress(context: Context = .cancel) -> SyncProgress? { let progress = try? _gethEthereumClient.syncProgress(context._gethContext) return SyncProgress(progress: progress) } } /* /** * GetPendingNonceAt returns the account nonce of the given account in the pending state. This is the nonce that should be used for the next transaction. */ - (BOOL)getPendingNonceAt:(GethContext*)ctx account:(GethAddress*)account nonce:(int64_t*)nonce error:(NSError**)error; /** GetStorageAt returns the value of key in the contract storage of the given account. The block number can be <0, in which case the value is taken from the latest known block. */ - (NSData*)getStorageAt:(GethContext*)ctx account:(GethAddress*)account key:(GethHash*)key number:(int64_t)number error:(NSError**)error; /** * GetTransactionByHash returns the transaction with the given hash. */ - (GethTransaction*)getTransactionByHash:(GethContext*)ctx hash:(GethHash*)hash error:(NSError**)error; /** * GetTransactionInBlock returns a single transaction at index in the given block. */ - (GethTransaction*)getTransactionInBlock:(GethContext*)ctx hash:(GethHash*)hash index:(long)index error:(NSError**)error; /** * GetTransactionReceipt returns the receipt of a transaction by transaction hash. Note that the receipt is not available for pending transactions. */ - (GethReceipt*)getTransactionReceipt:(GethContext*)ctx hash:(GethHash*)hash error:(NSError**)error; /** * PendingCallContract executes a message call transaction using the EVM. The state seen by the contract call is the pending state. */ - (NSData*)pendingCallContract:(GethContext*)ctx msg:(GethCallMsg*)msg error:(NSError**)error; /** * SendTransaction injects a signed transaction into the pending pool for execution. If the transaction was a contract creation use the TransactionReceipt method to get the contract address after the transaction has been mined. */ - (BOOL)sendTransaction:(GethContext*)ctx tx:(GethTransaction*)tx error:(NSError**)error; /** * SubscribeFilterLogs subscribes to the results of a streaming filter query. */ - (GethSubscription*)subscribeFilterLogs:(GethContext*)ctx query:(GethFilterQuery*)query handler:(id<GethFilterLogsHandler>)handler buffer:(long)buffer error:(NSError**)error; /** * SubscribeNewHead subscribes to notifications about the current blockchain head on the given channel. */ - (GethSubscription*)subscribeNewHead:(GethContext*)ctx handler:(id<GethNewHeadHandler>)handler buffer:(long)buffer error:(NSError**)error; /** * SuggestGasPrice retrieves the currently suggested gas price to allow a timely execution of a transaction. */ - (GethBigInt*)suggestGasPrice:(GethContext*)ctx error:(NSError**)error; /** * SyncProgress retrieves the current progress of the sync algorithm. If there's no sync currently running, it returns nil. */ - (GethSyncProgress*)syncProgress:(GethContext*)ctx error:(NSError**)error; @end */
mit
1b87311eae41e808c76f127738469a2b
43.222222
175
0.707915
4.118256
false
false
false
false
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTP.git--6392294032632002019/Sources/HTTPHeaders.swift
1
14904
// // HTTPHeaders.swift // PerfectLib // // Created by Kyle Jessup on 2016-06-17. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // /// An HTTP request header. public enum HTTPRequestHeader { /// A header name type. Each has a corresponding value type. public enum Name: Hashable { case accept, acceptCharset, acceptEncoding, acceptLanguage, acceptDatetime, authorization case cacheControl, connection, cookie, contentLength, contentMD5, contentType case date, expect, forwarded, from, host case ifMatch, ifModifiedSince, ifNoneMatch, ifRange, ifUnmodifiedSince case maxForwards, origin, pragma, proxyAuthorization, range, referer case te, userAgent, upgrade, via, warning, xRequestedWith, xRequestedBy, dnt case xAuthorization, xForwardedFor, xForwardedHost, xForwardedProto case frontEndHttps, xHttpMethodOverride, xATTDeviceId, xWapProfile case proxyConnection, xUIDH, xCsrfToken, accessControlRequestMethod, accessControlRequestHeaders case custom(name: String) public var hashValue: Int { return self.standardName.lowercased().hashValue } public var standardName: String { switch self { case .accept: return "Accept" case .acceptCharset: return "Accept-Charset" case .acceptEncoding: return "Accept-Encoding" case .acceptLanguage: return "Accept-Language" case .acceptDatetime: return "Accept-Datetime" case .accessControlRequestMethod: return "Access-Control-Request-Method" case .accessControlRequestHeaders: return "Access-Control-Request-Headers" case .authorization: return "Authorization" case .cacheControl: return "Cache-Control" case .connection: return "Connection" case .cookie: return "Cookie" case .contentLength: return "Content-Length" case .contentMD5: return "Content-MD5" case .contentType: return "Content-Type" case .date: return "Date" case .expect: return "Expect" case .forwarded: return "Forwarded" case .from: return "From" case .host: return "Host" case .ifMatch: return "If-Match" case .ifModifiedSince: return "If-Modified-Since" case .ifNoneMatch: return "If-None-Match" case .ifRange: return "If-Range" case .ifUnmodifiedSince: return "If-Unmodified-Since" case .maxForwards: return "Max-Forwards" case .origin: return "Origin" case .pragma: return "Pragma" case .proxyAuthorization: return "Proxy-Authorization" case .range: return "Range" case .referer: return "Referer" case .te: return "TE" case .userAgent: return "User-Agent" case .upgrade: return "Upgrade" case .via: return "Via" case .warning: return "Warning" case .xAuthorization: return "X-Authorization" case .xRequestedWith: return "X-Requested-with" case .xRequestedBy: return "X-Requested-by" case .dnt: return "DNT" case .xForwardedFor: return "X-Forwarded-For" case .xForwardedHost: return "X-Forwarded-Host" case .xForwardedProto: return "X-Forwarded-Proto" case .frontEndHttps: return "Front-End-Https" case .xHttpMethodOverride: return "X-HTTP-Method-Override" case .xATTDeviceId: return "X-Att-Deviceid" case .xWapProfile: return "X-WAP-Profile" case .proxyConnection: return "Proxy-Connection" case .xUIDH: return "X-UIDH" case .xCsrfToken: return "X-CSRF-Token" case .custom(let str): return str } } static let lookupTable: [String:HTTPRequestHeader.Name] = [ "accept":.accept, "accept-charset":.acceptCharset, "accept-encoding":.acceptEncoding, "accept-language":.acceptLanguage, "accept-datetime":.acceptDatetime, "access-control-request-method":.accessControlRequestMethod, "access-control-request-headers":.accessControlRequestHeaders, "authorization":.authorization, "cache-control":.cacheControl, "connection":.connection, "cookie":.cookie, "content-length":.contentLength, "content-md5":.contentMD5, "content-type":.contentType, "date":.date, "expect":.expect, "forwarded":.forwarded, "from":.from, "host":.host, "if-match":.ifMatch, "if-modified-since":.ifModifiedSince, "if-none-match":.ifNoneMatch, "if-range":.ifRange, "if-unmodified-since":.ifUnmodifiedSince, "max-forwards":.maxForwards, "origin":.origin, "pragma":.pragma, "proxy-authorization":.proxyAuthorization, "range":.range, "referer":.referer, "te":.te, "user-agent":.userAgent, "upgrade":.upgrade, "via":.via, "warning":.warning, "x-requested-with":.xRequestedWith, "x-requested-by":.xRequestedBy, "dnt":.dnt, "x-authorization":.xAuthorization, "x-forwarded-for":.xForwardedFor, "x-forwarded-host":.xForwardedHost, "x-forwarded-proto":.xForwardedProto, "front-end-https":.frontEndHttps, "x-http-method-override":.xHttpMethodOverride, "x-att-deviceid":.xATTDeviceId, "x-wap-profile":.xWapProfile, "proxy-connection":.proxyConnection, "x-uidh":.xUIDH, "x-csrf-token":.xCsrfToken ] public static func fromStandard(name: String) -> HTTPRequestHeader.Name { if let found = HTTPRequestHeader.Name.lookupTable[name.lowercased()] { return found } return .custom(name: name) } } } public func ==(lhs: HTTPRequestHeader.Name, rhs: HTTPRequestHeader.Name) -> Bool { return lhs.standardName.lowercased() == rhs.standardName.lowercased() } /// A HTTP response header. public enum HTTPResponseHeader { public enum Name { case accessControlAllowOrigin case accessControlAllowMethods case accessControlAllowCredentials case accessControlMaxAge case acceptPatch case acceptRanges case age case allow case altSvc case cacheControl case connection case contentDisposition case contentEncoding case contentLanguage case contentLength case contentLocation case contentMD5 case contentRange case contentType case date case eTag case expires case lastModified case link case location case p3p case pragma case proxyAuthenticate case publicKeyPins case refresh case retryAfter case server case setCookie case status case strictTransportSecurity case trailer case transferEncoding case tsv case upgrade case vary case via case warning case wwwAuthenticate case xFrameOptions case xxsSProtection case contentSecurityPolicy case xContentSecurityPolicy case xWebKitCSP case xContentTypeOptions case xPoweredBy case xUACompatible case xContentDuration case upgradeInsecureRequests case xRequestID case xCorrelationID case custom(name: String) public var hashValue: Int { return self.standardName.lowercased().hashValue } public var standardName: String { switch self { case .accessControlAllowOrigin: return "Access-Control-Allow-Origin" case .accessControlAllowMethods: return "Access-Control-Allow-Methods" case .accessControlAllowCredentials: return "Access-Control-Allow-Credentials" case .accessControlMaxAge: return "Access-Control-Max-Age" case .acceptPatch: return "Accept-Patch" case .acceptRanges: return "Accept-Ranges" case .age: return "Age" case .allow: return "Allow" case .altSvc: return "Alt-Svc" case .cacheControl: return "Cache-Control" case .connection: return "Connection" case .contentDisposition: return "Content-Disposition" case .contentEncoding: return "Content-Encoding" case .contentLanguage: return "Content-Language" case .contentLength: return "Content-Length" case .contentLocation: return "Content-Location" case .contentMD5: return "Content-MD5" case .contentRange: return "Content-Range" case .contentType: return "Content-Type" case .date: return "Date" case .eTag: return "ETag" case .expires: return "Expires" case .lastModified: return "Last-Modified" case .link: return "Link" case .location: return "Location" case .p3p: return "P3P" case .pragma: return "Pragma" case .proxyAuthenticate: return "Proxy-Authenticate" case .publicKeyPins: return "Public-Key-Pins" case .refresh: return "Refresh" case .retryAfter: return "Retry-After" case .server: return "Server" case .setCookie: return "Set-Cookie" case .status: return "Status" case .strictTransportSecurity: return "Strict-Transport-Security" case .trailer: return "Trailer" case .transferEncoding: return "Transfer-Encoding" case .tsv: return "TSV" case .upgrade: return "Upgrade" case .vary: return "Vary" case .via: return "Via" case .warning: return "Warning" case .wwwAuthenticate: return "WWW-Authenticate" case .xFrameOptions: return "X-Frame-Options" case .xxsSProtection: return "X-XSS-Protection" case .contentSecurityPolicy: return "Content-Security-Policy" case .xContentSecurityPolicy: return "X-Content-Security-Policy" case .xWebKitCSP: return "X-WebKit-CSP" case .xContentTypeOptions: return "X-Content-Type-Options" case .xPoweredBy: return "X-Powered-By" case .xUACompatible: return "X-UA-Compatible" case .xContentDuration: return "X-Content-Duration" case .upgradeInsecureRequests: return "Upgrade-Insecure-Requests" case .xRequestID: return "X-Request-ID" case .xCorrelationID: return "X-Correlation-ID" case .custom(let str): return str } } public static func fromStandard(name: String) -> HTTPResponseHeader.Name { switch name.lowercased() { case "access-control-Allow-Origin": return .accessControlAllowOrigin case "access-control-Allow-Methods": return .accessControlAllowMethods case "access-control-Allow-Credentials": return .accessControlAllowCredentials case "access-control-Max-Age": return .accessControlMaxAge case "accept-patch": return .acceptPatch case "accept-ranges": return .acceptRanges case "age": return .age case "allow": return .allow case "alt-svc": return .altSvc case "cache-control": return .cacheControl case "connection": return .connection case "content-disposition": return .contentDisposition case "content-encoding": return .contentEncoding case "content-language": return .contentLanguage case "content-length": return .contentLength case "content-location": return .contentLocation case "content-mD5": return .contentMD5 case "content-range": return .contentRange case "content-type": return .contentType case "date": return .date case "etag": return .eTag case "expires": return .expires case "last-modified": return .lastModified case "link": return .link case "location": return .location case "p3p": return .p3p case "pragma": return .pragma case "proxy-authenticate": return .proxyAuthenticate case "public-key-pins": return .publicKeyPins case "refresh": return .refresh case "retry-after": return .retryAfter case "server": return .server case "set-cookie": return .setCookie case "status": return .status case "strict-transport-security": return .strictTransportSecurity case "srailer": return .trailer case "sransfer-encoding": return .transferEncoding case "ssv": return .tsv case "upgrade": return .upgrade case "vary": return .vary case "via": return .via case "warning": return .warning case "www-authenticate": return .wwwAuthenticate case "x-frame-options": return .xFrameOptions case "x-xss-protection": return .xxsSProtection case "content-security-policy": return .contentSecurityPolicy case "x-content-security-policy": return .xContentSecurityPolicy case "x-webkit-csp": return .xWebKitCSP case "x-content-type-options": return .xContentTypeOptions case "x-powered-by": return .xPoweredBy case "x-ua-compatible": return .xUACompatible case "x-content-duration": return .xContentDuration case "upgrade-insecure-requests": return .upgradeInsecureRequests case "x-request-id": return .xRequestID case "x-correlation-id": return .xCorrelationID default: return .custom(name: name) } } } } public func ==(lhs: HTTPResponseHeader.Name, rhs: HTTPResponseHeader.Name) -> Bool { return lhs.standardName.lowercased() == rhs.standardName.lowercased() }
apache-2.0
386a29a58a9e2b345deebf048052c030
41.582857
104
0.603798
4.63577
false
false
false
false
nextcloud/ios
iOSClient/Share/NCShare+NCCellDelegate.swift
1
2728
// // NCShare+NCCellDelegate.swift // Nextcloud // // Created by Henrik Storch on 03.01.22. // Copyright © 2022 Henrik Storch. All rights reserved. // // Author Henrik Storch <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit // MARK: - NCCell Delegates extension NCShare: NCShareLinkCellDelegate, NCShareUserCellDelegate { func copyInternalLink(sender: Any) { guard let metadata = self.metadata, let appDelegate = appDelegate else { return } let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName) { _, metadata, error in if error == .success, let metadata = metadata { let internalLink = appDelegate.urlBase + "/index.php/f/" + metadata.fileId NCShareCommon.shared.copyLink(link: internalLink, viewController: self, sender: sender) } else { NCContentPresenter.shared.showError(error: error) } } } func tapCopy(with tableShare: tableShare?, sender: Any) { guard let tableShare = tableShare else { return copyInternalLink(sender: sender) } NCShareCommon.shared.copyLink(link: tableShare.url, viewController: self, sender: sender) } func tapMenu(with tableShare: tableShare?, sender: Any) { if let tableShare = tableShare { self.toggleShareMenu(for: tableShare) } else { self.makeNewLinkShare() } } func showProfile(with tableShare: tableShare?, sender: Any) { guard let tableShare = tableShare else { return } showProfileMenu(userId: tableShare.shareWith) } func quickStatus(with tableShare: tableShare?, sender: Any) { guard let tableShare = tableShare, let metadata = metadata, tableShare.shareType != NCGlobal.shared.permissionDefaultFileRemoteShareNoSupportShareOption else { return } self.toggleUserPermissionMenu(isDirectory: metadata.directory, tableShare: tableShare) } }
gpl-3.0
b1949112782c6fab5a9138607505a5d9
38.521739
122
0.680601
4.267606
false
false
false
false
SaberVicky/LoveStory
LoveStory/Feature/Reply/LSReplyViewModel.swift
1
1117
// // LSReplyViewModel.swift // LoveStory // // Created by songlong on 2017/2/6. // Copyright © 2017年 com.Saber. All rights reserved. // import UIKit class LSReplyViewModel: NSObject { lazy var replyList = [LSReplyModel]() func loadReplyData(publish_id: Int, finished: @escaping (_ isSuccessed: Bool) -> ()) { LSNetworking.sharedInstance.request(method: .GET, URLString: API_GET_REPLY, parameters: ["publish_id": publish_id], success: { (task, responseObject) in let dic = responseObject as! NSDictionary guard let array = dic["data"] as? [[String: AnyObject]] else { finished(false) return } var dataList = [LSReplyModel]() for dict in array { dataList.append(LSReplyModel(dict: dict)) } self.replyList = dataList finished(true) }, failure: { (task, error) in finished(false) }) } }
mit
1b75b4656833183186c922a7f7cdea7c
25.52381
160
0.509874
4.740426
false
false
false
false
Beaver/BeaverCodeGen
Tests/BeaverCodeGenTests/GeneratedCode/Module/ModuleOne/ModuleOne/ModuleOneReducer.swift
1
734
import Beaver import Core public struct ModuleOneReducer: Beaver.ChildReducing { public typealias ActionType = ModuleOneAction public typealias StateType = ModuleOneState public init() { } public func handle(action: ModuleOneAction, state: ModuleOneState, completion: @escaping (ModuleOneState) -> ()) -> ModuleOneState { var newState = state switch ExhaustiveAction<ModuleOneRoutingAction, ModuleOneUIAction>(action) { case .routing(.start): newState.currentScreen = .main case .routing(.stop): newState.currentScreen = .none case .ui: break } return newState } }
mit
829baeb0f99ccbb040a11617f70763e1
24.310345
88
0.610354
4.926174
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Rx.playground/Pages/Working_with_Subjects.xcplaygroundpage/Contents.swift
15
4825
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxSwift-macOS** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator**. 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). ---- [Previous](@previous) - [Table of Contents](Table_of_Contents) */ import RxSwift /*: # Working with Subjects A Subject is a sort of bridge or proxy that is available in some implementations of Rx that acts as both an observer and `Observable`. Because it is an observer, it can subscribe to one or more `Observable`s, and because it is an `Observable`, it can pass through the items it observes by reemitting them, and it can also emit new items. [More info](http://reactivex.io/documentation/subject.html) */ extension ObservableType { /** Add observer with `id` and print each emitted event. - parameter id: an identifier for the subscription. */ func addObserver(_ id: String) -> Disposable { return subscribe { print("Subscription:", id, "Event:", $0) } } } func writeSequenceToConsole<O: ObservableType>(name: String, sequence: O) -> Disposable { return sequence.subscribe { event in print("Subscription: \(name), event: \(event)") } } /*: ## PublishSubject Broadcasts new events to all observers as of their time of the subscription. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject.png "PublishSubject") */ example("PublishSubject") { let disposeBag = DisposeBag() let subject = PublishSubject<String>() subject.addObserver("1").disposed(by: disposeBag) subject.onNext("🐶") subject.onNext("🐱") subject.addObserver("2").disposed(by: disposeBag) subject.onNext("🅰️") subject.onNext("🅱️") } /*: > This example also introduces using the `onNext(_:)` convenience method, equivalent to `on(.next(_:)`, which causes a new Next event to be emitted to subscribers with the provided `element`. There are also `onError(_:)` and `onCompleted()` convenience methods, equivalent to `on(.error(_:))` and `on(.completed)`, respectively. ---- ## ReplaySubject Broadcasts new events to all subscribers, and the specified `bufferSize` number of previous events to new subscribers. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replaysubject.png) */ example("ReplaySubject") { let disposeBag = DisposeBag() let subject = ReplaySubject<String>.create(bufferSize: 1) subject.addObserver("1").disposed(by: disposeBag) subject.onNext("🐶") subject.onNext("🐱") subject.addObserver("2").disposed(by: disposeBag) subject.onNext("🅰️") subject.onNext("🅱️") } /*: ---- ## BehaviorSubject Broadcasts new events to all subscribers, and the most recent (or initial) value to new subscribers. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject.png) */ example("BehaviorSubject") { let disposeBag = DisposeBag() let subject = BehaviorSubject(value: "🔴") subject.addObserver("1").disposed(by: disposeBag) subject.onNext("🐶") subject.onNext("🐱") subject.addObserver("2").disposed(by: disposeBag) subject.onNext("🅰️") subject.onNext("🅱️") subject.addObserver("3").disposed(by: disposeBag) subject.onNext("🍐") subject.onNext("🍊") } /*: > Notice what's missing in these previous examples? A Completed event. `PublishSubject`, `ReplaySubject`, and `BehaviorSubject` do not automatically emit Completed events when they are about to be disposed of. ---- ## Variable Wraps a `BehaviorSubject`, so it will emit the most recent (or initial) value to new subscribers. And `Variable` also maintains current value state. `Variable` will never emit an Error event. However, it will automatically emit a Completed event and terminate on `deinit`. */ example("Variable") { let disposeBag = DisposeBag() let variable = Variable("🔴") variable.asObservable().addObserver("1").disposed(by: disposeBag) variable.value = "🐶" variable.value = "🐱" variable.asObservable().addObserver("2").disposed(by: disposeBag) variable.value = "🅰️" variable.value = "🅱️" } //: > Call `asObservable()` on a `Variable` instance in order to access its underlying `BehaviorSubject` sequence. `Variable`s do not implement the `on` operator (or, e.g., `onNext(_:)`), but instead expose a `value` property that can be used to get the current value, and also set a new value. Setting a new value will also add that value onto its underlying `BehaviorSubject` sequence. //: [Next](@next) - [Table of Contents](Table_of_Contents)
mit
1f510654ef49792d443cdc2f0b931f08
42.118182
398
0.693443
4.399814
false
false
false
false
ezrover/Watchdog
Classes/Watchdog.swift
1
2264
import Foundation import UIKit #if DEBUG public class Watchdog { /* The number of seconds that must pass to consider the main thread blocked */ private var threshold: Double private var runLoop: CFRunLoopRef = CFRunLoopGetMain() private var observer: CFRunLoopObserverRef! private var startTime: UInt64 = 0; public init(threshold: Double = 0.2) { self.threshold = threshold var timebase: mach_timebase_info_data_t = mach_timebase_info(numer: 0, denom: 0) mach_timebase_info(&timebase) let secondsPerMachine: NSTimeInterval = NSTimeInterval(Double(timebase.numer) / Double(timebase.denom) / Double(1e9)) observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFRunLoopActivity.AllActivities.rawValue, true, 0) { [weak self] (observer, activity) in guard let weakSelf = self else { return } switch(activity) { case CFRunLoopActivity.Entry, CFRunLoopActivity.BeforeTimers, CFRunLoopActivity.AfterWaiting, CFRunLoopActivity.BeforeSources: if weakSelf.startTime == 0 { weakSelf.startTime = mach_absolute_time() } case CFRunLoopActivity.BeforeWaiting, CFRunLoopActivity.Exit: let elapsed = mach_absolute_time() - weakSelf.startTime let duration: NSTimeInterval = NSTimeInterval(elapsed) * secondsPerMachine if duration > weakSelf.threshold { print("👮 Main thread was blocked for " + String(format:"%.2f", duration) + "s 👮"); print(NSThread.callStackSymbols()) } weakSelf.startTime = 0 default: () } } CFRunLoopAddObserver(CFRunLoopGetMain(), observer!, kCFRunLoopCommonModes) } deinit { CFRunLoopObserverInvalidate(observer!) } } #endif // DEBUG
mit
0901038dbcc03465a0279e88f86e62f8
33.738462
125
0.542516
5.819588
false
false
false
false
xBrux/Pensieve
Source/Core/Connection.swift
1
24662
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 Dispatch /// A connection to SQLite. /*public*/ final class Connection { /// The location of a SQLite database. /*public*/ enum Location { /// An in-memory database (equivalent to `.URI(":memory:")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb> case InMemory /// A temporary, file-backed database (equivalent to `.URI("")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#temp_db> case Temporary /// A database located at the given URI filename (or path). /// /// See: <https://www.sqlite.org/uri.html> /// /// - Parameter filename: A URI filename case URI(String) } /*public*/ var handle: COpaquePointer { return _handle } private var _handle: COpaquePointer = nil /// Initializes a new SQLite connection. /// /// - Parameters: /// /// - location: The location of the database. Creates a new database if it /// doesn’t already exist (unless in read-only mode). /// /// Default: `.InMemory`. /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Returns: A new database connection. /*public*/ init(_ location: Location = .InMemory, readonly: Bool = false) throws { let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil)) dispatch_queue_set_specific(queue, Connection.queueKey, queueContext, nil) } /// Initializes a new connection to a database. /// /// - Parameters: /// /// - filename: The location of the database. Creates a new database if /// it doesn’t already exist (unless in read-only mode). /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Throws: `Result.Error` iff a connection cannot be established. /// /// - Returns: A new database connection. /*public*/ convenience init(_ filename: String, readonly: Bool = false) throws { try self.init(.URI(filename), readonly: readonly) } deinit { sqlite3_close(handle) } // MARK: - /// Whether or not the database was opened in a read-only state. /*public*/ var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. /*public*/ var lastInsertRowid: Int64? { let rowid = sqlite3_last_insert_rowid(handle) return rowid > 0 ? rowid : nil } /// The last number of changes (inserts, updates, or deletes) made to the /// database via this connection. /*public*/ var changes: Int { return Int(sqlite3_changes(handle)) } /// The total number of changes (inserts, updates, or deletes) made to the /// database via this connection. /*public*/ var totalChanges: Int { return Int(sqlite3_total_changes(handle)) } // MARK: - Execute /// Executes a batch of SQL statements. /// /// - Parameter SQL: A batch of zero or more semicolon-separated SQL /// statements. /// /// - Throws: `Result.Error` if query execution fails. /*public*/ func execute(SQL: String) throws { try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) } } // MARK: - Prepare /// Prepares a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result /*public*/ func prepare(sqlString: String, _ bindings: Binding?...) throws -> Statement { if !bindings.isEmpty { return try prepare(sqlString, bindings) } else { return try Statement(self, sqlString) } } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result /*public*/ func prepare(sqlString: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(sqlString).bind(bindings) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: A prepared statement. @warn_unused_result /*public*/ func prepare(sqlString: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(sqlString).bind(bindings) } // MARK: - Run /// Runs a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. /*public*/ func run(sqlString: String, _ bindings: Binding?...) throws -> Statement { return try run(sqlString, bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. /*public*/ func run(sqlString: String, _ bindings: [Binding?]) throws -> Statement { return try prepare(sqlString).run(bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. /*public*/ func run(sqlString: String, _ bindings: [String: Binding?]) throws -> Statement { return try prepare(sqlString).run(bindings) } // MARK: - Scalar /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result /*public*/ func scalar(sqlString: String, _ bindings: Binding?...) throws -> Binding? { return try scalar(sqlString, bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result /*public*/ func scalar(sqlString: String, _ bindings: [Binding?]) throws -> Binding? { return try prepare(sqlString).scalar(bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. @warn_unused_result /*public*/ func scalar(sqlString: String, _ bindings: [String: Binding?]) throws -> Binding? { return try prepare(sqlString).scalar(bindings) } // MARK: - Transactions /// The mode in which a transaction acquires a lock. /*public*/ enum TransactionMode : String { /// Defers locking the database till the first read/write executes. case Deferred = "DEFERRED" /// Immediately acquires a reserved lock on the database. case Immediate = "IMMEDIATE" /// Immediately acquires an exclusive lock on all databases. case Exclusive = "EXCLUSIVE" } // TODO: Consider not requiring a throw to roll back? /// Runs a transaction with the given mode. /// /// - Note: Transactions cannot be nested. To nest transactions, see /// `savepoint()`, instead. /// /// - Parameters: /// /// - mode: The mode in which a transaction acquires a lock. /// /// Default: `.Deferred` /// /// - block: A closure to run SQL statements within the transaction. /// The transaction will be committed when the block returns. The block /// must throw to roll the transaction back. /// /// - Throws: `Result.Error`, and rethrows. /*public*/ func transaction(mode: TransactionMode = .Deferred, block: () throws -> Void) throws { try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION") } // TODO: Consider not requiring a throw to roll back? // TODO: Consider removing ability to set a name? /// Runs a transaction with the given savepoint name (if omitted, it will /// generate a UUID). /// /// - SeeAlso: `transaction()`. /// /// - Parameters: /// /// - savepointName: A unique identifier for the savepoint (optional). /// /// - block: A closure to run SQL statements within the transaction. /// The savepoint will be released (committed) when the block returns. /// The block must throw to roll the savepoint back. /// /// - Throws: `SQLite.Result.Error`, and rethrows. /*public*/ func savepoint(name: String = NSUUID().UUIDString, block: () throws -> Void) throws { let name = name.quote("'") let savepoint = "SAVEPOINT \(name)" try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)") } private func transaction(begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws { return try sync { try self.run(begin) do { try block() } catch { try self.run(rollback) throw error } try self.run(commit) } } /// Interrupts any long-running queries. /*public*/ func interrupt() { sqlite3_interrupt(handle) } // MARK: - Handlers /// The number of seconds a connection will attempt to retry a statement /// after encountering a busy signal (lock). /*public*/ var busyTimeout: Double = 0 { didSet { sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000)) } } /// Sets a handler to call after encountering a busy signal (lock). /// /// - Parameter callback: This block is executed during a lock in which a /// busy error would otherwise be returned. It’s passed the number of /// times it’s been called for this lock. If it returns `true`, it will /// try again. If it returns `false`, no further attempts will be made. /*public*/ func busyHandler(callback: ((tries: Int) -> Bool)?) { guard let callback = callback else { sqlite3_busy_handler(handle, nil, nil) busyHandler = nil return } let box: BusyHandler = { callback(tries: Int($0)) ? 1 : 0 } sqlite3_busy_handler(handle, { callback, tries in unsafeBitCast(callback, BusyHandler.self)(tries) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) busyHandler = box } private typealias BusyHandler = @convention(block) Int32 -> Int32 private var busyHandler: BusyHandler? /// Sets a handler to call when a statement is executed with the compiled /// SQL. /// /// - Parameter callback: This block is invoked when a statement is executed /// with the compiled SQL as its argument. /// /// db.trace { SQL in print(SQL) } /*public*/ func trace(callback: (String -> Void)?) { guard let callback = callback else { sqlite3_trace(handle, nil, nil) trace = nil return } let box: Trace = { callback(String.fromCString($0)!) } sqlite3_trace(handle, { callback, SQL in unsafeBitCast(callback, Trace.self)(SQL) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) trace = box } private typealias Trace = @convention(block) UnsafePointer<Int8> -> Void private var trace: Trace? /// Registers a callback to be invoked whenever a row is inserted, updated, /// or deleted in a rowid table. /// /// - Parameter callback: A callback invoked with the `Operation` (one of /// `.Insert`, `.Update`, or `.Delete`), database name, table name, and /// rowid. /*public*/ func updateHook(callback: ((operation: Operation, db: String, table: String, rowid: Int64) -> Void)?) { guard let callback = callback else { sqlite3_update_hook(handle, nil, nil) updateHook = nil return } let box: UpdateHook = { callback( operation: Operation(rawValue: $0), db: String.fromCString($1)!, table: String.fromCString($2)!, rowid: $3 ) } sqlite3_update_hook(handle, { callback, operation, db, table, rowid in unsafeBitCast(callback, UpdateHook.self)(operation, db, table, rowid) }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) updateHook = box } private typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void private var updateHook: UpdateHook? /// Registers a callback to be invoked whenever a transaction is committed. /// /// - Parameter callback: A callback invoked whenever a transaction is /// committed. If this callback throws, the transaction will be rolled /// back. /*public*/ func commitHook(callback: (() throws -> Void)?) { guard let callback = callback else { sqlite3_commit_hook(handle, nil, nil) commitHook = nil return } let box: CommitHook = { do { try callback() } catch { return 1 } return 0 } sqlite3_commit_hook(handle, { callback in unsafeBitCast(callback, CommitHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) commitHook = box } private typealias CommitHook = @convention(block) () -> Int32 private var commitHook: CommitHook? /// Registers a callback to be invoked whenever a transaction rolls back. /// /// - Parameter callback: A callback invoked when a transaction is rolled /// back. /*public*/ func rollbackHook(callback: (() -> Void)?) { guard let callback = callback else { sqlite3_rollback_hook(handle, nil, nil) rollbackHook = nil return } let box: RollbackHook = { callback() } sqlite3_rollback_hook(handle, { callback in unsafeBitCast(callback, RollbackHook.self)() }, unsafeBitCast(box, UnsafeMutablePointer<Void>.self)) rollbackHook = box } private typealias RollbackHook = @convention(block) () -> Void private var rollbackHook: RollbackHook? /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - argumentCount: The number of arguments that the function takes. If /// `nil`, the function may take any number of arguments. /// /// Default: `nil` /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. The block /// is called with an array of raw SQL values mapped to the function’s /// parameters and should return a raw SQL value (or nil). /*public*/ func createFunction(function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: (args: [Binding?]) -> Binding?) { let argc = argumentCount.map { Int($0) } ?? -1 let box: Function = { context, argc, argv in let arguments: [Binding?] = (0..<Int(argc)).map { idx in let value = argv[idx] switch sqlite3_value_type(value) { case SQLITE_BLOB: return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value))) case SQLITE_FLOAT: return sqlite3_value_double(value) case SQLITE_INTEGER: return sqlite3_value_int64(value) case SQLITE_NULL: return nil case SQLITE_TEXT: return String.fromCString(UnsafePointer(sqlite3_value_text(value)))! case let type: fatalError("unsupported value type: \(type)") } } let result = block(args: arguments) if let result = result as? Blob { sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil) } else if let result = result as? Double { sqlite3_result_double(context, result) } else if let result = result as? Int64 { sqlite3_result_int64(context, result) } else if let result = result as? String { sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT) } else if result == nil { sqlite3_result_null(context) } else { fatalError("unsupported result type: \(result)") } } var flags = SQLITE_UTF8 if deterministic { flags |= SQLITE_DETERMINISTIC } sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { context, argc, value in unsafeBitCast(sqlite3_user_data(context), Function.self)(context, argc, value) }, nil, nil, nil) if functions[function] == nil { self.functions[function] = [:] } functions[function]?[argc] = box } private typealias Function = @convention(block) (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) -> Void private var functions = [String: [Int: Function]]() /// The return type of a collation comparison function. /*public*/ typealias ComparisonResult = NSComparisonResult /// Defines a new collating sequence. /// /// - Parameters: /// /// - collation: The name of the collation added. /// /// - block: A collation function that takes two strings and returns the /// comparison result. /*public*/ func createCollation(collation: String, _ block: (lhs: String, rhs: String) -> ComparisonResult) { let box: Collation = { lhs, rhs in Int32(block(lhs: String.fromCString(UnsafePointer<Int8>(lhs))!, rhs: String.fromCString(UnsafePointer<Int8>(rhs))!).rawValue) } try! check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { callback, _, lhs, _, rhs in unsafeBitCast(callback, Collation.self)(lhs, rhs) }, nil)) collations[collation] = box } private typealias Collation = @convention(block) (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32 private var collations = [String: Collation]() // MARK: - Error Handling func sync<T>(block: () throws -> T) rethrows -> T { var success: T? var failure: ErrorType? let box: () -> Void = { do { success = try block() } catch { failure = error } } if dispatch_get_specific(Connection.queueKey) == queueContext { box() } else { dispatch_sync(queue, box) // FIXME: rdar://problem/21389236 } if let failure = failure { try { () -> Void in throw failure }() } return success! } func check(resultCode: Int32, statement: Statement? = nil) throws -> Int32 { guard let error = Result(errorCode: resultCode, connection: self, statement: statement) else { return resultCode } throw PensieveDBError(sqliteError: error) } private var queue = dispatch_queue_create("SQLite.Database", DISPATCH_QUEUE_SERIAL) private static let queueKey = unsafeBitCast(Connection.self, UnsafePointer<Void>.self) private lazy var queueContext: UnsafeMutablePointer<Void> = unsafeBitCast(self, UnsafeMutablePointer<Void>.self) } extension Connection : CustomStringConvertible { /*public*/ var description: String { return String.fromCString(sqlite3_db_filename(handle, nil))! } } extension Connection.Location : CustomStringConvertible { /*public*/ var description: String { switch self { case .InMemory: return ":memory:" case .Temporary: return "" case .URI(let URI): return URI } } } /// An SQL operation passed to update callbacks. /*public*/ enum Operation { /// An INSERT operation. case Insert /// An UPDATE operation. case Update /// A DELETE operation. case Delete private init(rawValue: Int32) { switch rawValue { case SQLITE_INSERT: self = .Insert case SQLITE_UPDATE: self = .Update case SQLITE_DELETE: self = .Delete default: fatalError("unhandled operation code: \(rawValue)") } } } /*public*/ enum Result : ErrorType { private static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE] case Error(message: String, code: Int32, statement: Statement?) init?(errorCode: Int32, connection: Connection, statement: Statement? = nil) { guard !Result.successCodes.contains(errorCode) else { return nil } let message = String.fromCString(sqlite3_errmsg(connection.handle))! self = Error(message: message, code: errorCode, statement: statement) } } extension Result : CustomStringConvertible { /*public*/ var description: String { switch self { case let .Error(message, _, statement): guard let statement = statement else { return message } return "\(message) (\(statement))" } } }
mit
8ab4f2e6174594ac6f67fc60049a569e
34.829942
161
0.601477
4.459298
false
false
false
false
efremidze/Cluster
Sources/Extensions.swift
1
3849
// // Extensions.swift // Cluster // // Created by Lasha Efremidze on 4/15/17. // Copyright © 2017 efremidze. All rights reserved. // import Foundation import MapKit extension MKMapRect { init(minX: Double, minY: Double, maxX: Double, maxY: Double) { self.init(x: minX, y: minY, width: abs(maxX - minX), height: abs(maxY - minY)) } init(x: Double, y: Double, width: Double, height: Double) { self.init(origin: MKMapPoint(x: x, y: y), size: MKMapSize(width: width, height: height)) } func contains(_ coordinate: CLLocationCoordinate2D) -> Bool { return self.contains(MKMapPoint(coordinate)) } } let CLLocationCoordinate2DMax = CLLocationCoordinate2D(latitude: 90, longitude: 180) let MKMapPointMax = MKMapPoint(CLLocationCoordinate2DMax) extension CLLocationCoordinate2D: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(latitude) hasher.combine(longitude) } } public func ==(lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude } extension Double { var zoomLevel: Double { let maxZoomLevel = log2(MKMapSize.world.width / 256) // 20 let zoomLevel = floor(log2(self) + 0.5) // negative return max(0, maxZoomLevel + zoomLevel) // max - current } } private let radiusOfEarth: Double = 6372797.6 extension CLLocationCoordinate2D { func coordinate(onBearingInRadians bearing: Double, atDistanceInMeters distance: Double) -> CLLocationCoordinate2D { let distRadians = distance / radiusOfEarth // earth radius in meters let lat1 = latitude * .pi / 180 let lon1 = longitude * .pi / 180 let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(bearing)) let lon2 = lon1 + atan2(sin(bearing) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2)) return CLLocationCoordinate2D(latitude: lat2 * 180 / .pi, longitude: lon2 * 180 / .pi) } var location: CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } func distance(from coordinate: CLLocationCoordinate2D) -> CLLocationDistance { return location.distance(from: coordinate.location) } } extension Array where Element: MKAnnotation { func subtracted(_ other: [Element]) -> [Element] { return filter { item in !other.contains { $0.isEqual(item) } } } mutating func subtract(_ other: [Element]) { self = self.subtracted(other) } mutating func add(_ other: [Element]) { self.append(contentsOf: other) } @discardableResult mutating func remove(_ item: Element) -> Element? { return firstIndex { $0.isEqual(item) }.map { remove(at: $0) } } } extension MKPolyline { convenience init(mapRect: MKMapRect) { let points = [ MKMapPoint(x: mapRect.minX, y: mapRect.minY), MKMapPoint(x: mapRect.maxX, y: mapRect.minY), MKMapPoint(x: mapRect.maxX, y: mapRect.maxY), MKMapPoint(x: mapRect.minX, y: mapRect.maxY), MKMapPoint(x: mapRect.minX, y: mapRect.minY) ] self.init(points: points, count: points.count) } } extension OperationQueue { static var serial: OperationQueue { let queue = OperationQueue() queue.name = "com.cluster.serialQueue" queue.maxConcurrentOperationCount = 1 return queue } func addBlockOperation(_ block: @escaping (BlockOperation) -> Void) { let operation = BlockOperation() operation.addExecutionBlock { [weak operation] in guard let operation = operation else { return } block(operation) } self.addOperation(operation) } }
mit
0a09127b6563076b1909f50d2a3729ae
33.357143
120
0.648389
4.054795
false
false
false
false
JohnSundell/Marathon
Sources/MarathonCore/Create.swift
1
2399
/** * Marathon * Copyright (c) John Sundell 2017 * Licensed under the MIT license. See LICENSE file. */ import Foundation import Files // MARK: - Error public enum CreateError { case missingName case failedToCreateFile(String) } extension CreateError: PrintableError { public var message: String { switch self { case .missingName: return "No script name given" case .failedToCreateFile(let name): return "Failed to create script file named '\(name)'" } } public var hints: [String] { switch self { case .missingName: return ["Pass the name of a script file to create (for example 'marathon create myScript')"] case .failedToCreateFile: return ["Make sure you have write permissions to the current folder"] } } } // MARK: - Task internal final class CreateTask: Task, Executable { private typealias Error = CreateError func execute() throws { guard let path = arguments.first?.asScriptPath() else { throw Error.missingName } guard (try? File(path: path)) == nil else { let editTask = EditTask( folder: folder, arguments: arguments, scriptManager: scriptManager, packageManager: packageManager, printer: printer ) return try editTask.execute() } guard let data = makeScriptContent().data(using: .utf8) else { throw Error.failedToCreateFile(path) } let file = try perform(FileSystem().createFile(at: path, contents: data), orThrow: Error.failedToCreateFile(path)) printer.output("🐣 Created script at \(path)") if !argumentsContainNoOpenFlag { let script = try scriptManager.script(atPath: file.path, allowRemote: false) try script.setupForEdit(arguments: arguments) try script.watch(arguments: arguments) } } private func makeScriptContent() -> String { let defaultContent = "import Foundation\n\n" guard let argument = arguments.element(at: 1) else { return defaultContent } guard !argument.hasPrefix("-") else { return defaultContent } return argument } }
mit
2cbab750d776e476f53708d86ff12f5a
26.227273
104
0.59015
4.782435
false
false
false
false
GhostSK/SpriteKitPractice
TileMap/TileMap/TileMapLayer.swift
1
2471
// // TileMapLayer.swift // TileMap // // Created by 胡杨林 on 17/3/20. // Copyright © 2017年 胡杨林. All rights reserved. // import Foundation import SpriteKit class TileMapLayer : SKNode { var tileSize: CGSize = CGSize() //用来保存瓦片的大小 var atlas: SKTextureAtlas? = nil //用来保存纹理集合 init(tilesize: CGSize) { super.init() self.tileSize = tilesize } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(atlasName: String, tileSize: CGSize, tileCodes: [String]) { self.init(tilesize: tileSize) self.position = CGPoint(x: 0, y: 0) atlas = SKTextureAtlas(named: atlasName) //遍历 for row in 0..<tileCodes.count { var line = tileCodes[row] as String var i = 0 for char in line.characters{ // print("\(i) --- \(char)") let tile = nodeForCode(tileCode: char) tile?.position = self.position(ForRow: row, col: i) if tile != nil { addChild(tile!) } i += 1 } } } //获取对应的瓦片 func nodeForCode(tileCode:Character) -> SKNode? { //判断atlas是否为空 if atlas == nil{ return nil } var tile: SKNode? //判断tileCode switch tileCode { case "x": tile = SKSpriteNode(texture: atlas!.textureNamed("wall")) break case "o": tile = SKSpriteNode(texture: atlas!.textureNamed("grass")) break case "w": tile = SKSpriteNode(texture: atlas!.textureNamed("water")) break case "=": tile = SKSpriteNode(texture: atlas!.textureNamed("stone")) break default: print("未知图片") break } if let sprite = tile as? SKSpriteNode { sprite.blendMode = .replace sprite.texture?.filteringMode = .nearest } return tile } func position(ForRow:Int, col: Int) ->CGPoint { let x = CGFloat(col) * tileSize.width + tileSize.width / 2 let y = 300 - CGFloat(ForRow) * tileSize.height + tileSize.height / 2 return CGPoint(x: x, y: y) } }
apache-2.0
be93a6f3ce54085cf770021bc2c5c785
26.356322
80
0.512605
4.327273
false
false
false
false
mvader/advent-of-code
2020/10/01.swift
1
623
import Foundation let adapters = try String(contentsOfFile: "./input.txt", encoding: .utf8) .components(separatedBy: "\n") .map { s in Int(s)! } .sorted() enum ChainError: Error { case notChainable } func joltDifferences(_ adapters: [Int]) throws -> (Int, Int, Int) { var (diff1, diff2, diff3) = (0, 0, 0) var jolts = 0 for a in adapters { switch a - jolts { case 1: diff1 += 1 case 2: diff2 += 1 case 3: diff3 += 1 default: throw ChainError.notChainable } jolts = a } return (diff1, diff2, diff3 + 1) } let diffs = try joltDifferences(adapters) print(diffs.0 * diffs.2)
mit
d7d1fa00361482ae4c12dc723e785288
19.766667
73
0.626003
3.009662
false
false
false
false
FabrizioBrancati/Queuer
Sources/Queuer/Scheduler.swift
1
2899
// // Scheduler.swift // Queuer // // MIT License // // Copyright (c) 2017 - 2019 Fabrizio Brancati // // 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 Dispatch import Foundation /// Scheduler struct, based on top of `DispatchSourceTimer`. public struct Scheduler { /// Schedule timer. public private(set) var timer: DispatchSourceTimer /// Schedule deadline. public private(set) var deadline: DispatchTime /// Schedule repeating interval. public private(set) var repeating: DispatchTimeInterval /// Schedule quality of service. public private(set) var qualityOfService: DispatchQoS /// Schedule handler. public private(set) var handler: (() -> Void)? /// Create a schedule. /// /// - Parameters: /// - deadline: Deadline. /// - repeating: Repeating interval /// - qualityOfService: Quality of service. /// - handler: Closure handler. public init(deadline: DispatchTime, repeating: DispatchTimeInterval, qualityOfService: DispatchQoS = .default, handler: (() -> Void)? = nil) { self.deadline = deadline self.repeating = repeating self.qualityOfService = qualityOfService self.handler = handler timer = DispatchSource.makeTimerSource() timer.schedule(deadline: deadline, repeating: repeating) if let handler = handler { timer.setEventHandler(qos: qualityOfService) { handler() } timer.resume() } } /// Set the handler after schedule creation. /// /// - Parameter handler: Closure handler. public mutating func setHandler(_ handler: @escaping () -> Void) { self.handler = handler timer.setEventHandler(qos: qualityOfService) { handler() } timer.resume() } }
mit
4008c926b5aec860637ce5b549d776be
36.649351
146
0.673336
4.815615
false
false
false
false
jongwonwoo/CodeSamples
Safe Area/SafeAreaSample/SafeAreaSample/ViewController.swift
1
1666
// // ViewController.swift // SafeAreaSample // // Created by Jongwon Woo on 12/12/2017. // Copyright © 2017 jongwonwoo. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var contentView: UIView! @IBOutlet weak var descriptionLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. showInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() contentView.layer.borderColor = UIColor.red.cgColor contentView.layer.borderWidth = 3.0 } func showInfo() { if #available(iOS 11.0, *) { descriptionLabel.text = "iOS 11" } else { descriptionLabel.text = "older version than iOS 11" } } @IBAction func changeAdditionalSafeAreaInsets(_ sender: Any) { if #available(iOS 11.0, *) { additionalSafeAreaInsets = UIEdgeInsets(top: 50, left: 20, bottom: 50, right: 20) } else { // Fallback on earlier versions } } @IBAction func resetAdditionalSafeAreaInsets(_ sender: Any) { if #available(iOS 11.0, *) { additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } else { // Fallback on earlier versions } } @IBAction func unwindToVC(segue:UIStoryboardSegue) { } }
mit
72059f4d4ae6fd81834b9a5430219e0c
25.854839
93
0.607207
4.730114
false
false
false
false
SSU-CS-Department/ssumobile-ios
SSUMobile/Modules/Core/Extensions.swift
1
1045
// // Extensions.swift // SSUMobile // // Created by Eric Amorde on 6/25/18. // Copyright © 2018 Sonoma State University Department of Computer Science. All rights reserved. // import Foundation import MapKit extension Array { func group<GroupKey>(by keyPath: KeyPath<Element, GroupKey>) -> [GroupKey:[Element]] { let groupedValues: [GroupKey:[Element]] = self.reduce(into: [:]) { (result, value) -> Void in let key = value[keyPath: keyPath] var elements: [Element] = result[key] ?? [] elements.append(value) result[key] = elements } return groupedValues } } func minValue<T: Comparable>(_ a: T?, _ b: T?) -> T? { return [a, b].lazy.compactMap { $0 }.min() } func maxValue<T: Comparable>(_ args: T?...) -> T? { return args.lazy.compactMap { $0 }.max() } extension MKPolygon { public convenience init(coordinates: [CLLocationCoordinate2D]) { var coords = coordinates self.init(coordinates: &coords, count: coords.count) } }
apache-2.0
895b894bf080bbc323db801e4bfe468c
27.216216
101
0.618774
3.741935
false
false
false
false
S2dentik/Taylor
TaylorFramework/Modules/temper/Core/Temper.swift
4
5430
// // Temper.swift // Temper // // Created by Mihai Seremet on 8/28/15. // Copyright © 2015 Yopeso. All rights reserved. // import Foundation internal typealias Result = (isOk: Bool, message: String?, value: Int?) final class Temper { var rules: [Rule] fileprivate let outputPath: String fileprivate var violations: [Violation] fileprivate var output: OutputCoordinator fileprivate var currentPath: String? fileprivate var reporters: [Reporter] fileprivate var fileWasChecked = false static var statistics = TemperStatistics() var resultsOutput = [ResultOutput]() var path: String { return outputPath } /** Temper module initializer If the path is wrong, the current directory path will be used as output path For reporter customization, call setReporters([Reporter]) method with needed reporters For rule customization, call setLimits([String:Int]) method with needed limits For check the content for violations, call checkContent(FileContent) method For finish and generate the reporters, call finishTempering() method :param: outputPath The output path when will be created the reporters */ init(outputPath: String) { if !FileManager.default.fileExists(atPath: outputPath) { print("Temper: Wrong output path! The current directory path will be used as output path!") self.outputPath = FileManager.default.currentDirectoryPath } else { self.outputPath = outputPath } rules = RulesFactory().getRules() violations = [Violation]() output = OutputCoordinator(filePath: outputPath) reporters = [Reporter(PMDReporter())] } /** This method check the content of file for violations For finish and generate the reporters, call finishTempering() method :param: content The content of file parsed in components */ func checkContent(_ content: FileContent) { Temper.statistics.totalFiles += 1 fileWasChecked = false currentPath = content.path let initialViolations = violations.count startAnalazy(content.components) resultsForFile(currentPath, violations: violations.count - initialViolations) } func resultsForFile(_ currentPath: String?, violations: Int) { guard let path = currentPath , path.characters.count > outputPath.characters.count else { return } let relativePath: String = (path as NSString).substring(from: outputPath.characters.count + 1) resultsOutput.append(ResultOutput(path: relativePath, warnings: violations)) } /** This method set the reporters. If method is not called, PMD reporter will be used as default. :param: reporters An array of reporters: * PMD (xml file) * JSON (json file) * Xcode (Xcode IDE warnings/error) * Plain (text file) */ func setReporters(_ reporters: [Reporter]) { self.reporters = reporters } /** This method is called when there are no more content for checking. It will create the reporters and write the violations. */ func finishTempering() { output.writeTheOutput(violations, reporters: reporters) } /** This method set the limits of the rules. The limits should be greather than 0 :param: limits A dictionary with the rule name as key and unsigned int as value(the limit) */ func setLimits(_ limits: [String:Int]) { rules = rules.map({ ( rule: Rule) -> Rule in var mutableRule = rule if let limit = limits[rule.rule] { mutableRule.limit = limit } return mutableRule }) } // Private methods fileprivate func startAnalazy(_ components: [Component]) { for component in components { for rule in rules { checkPair(rule: rule, component: component) } if !component.components.isEmpty { startAnalazy(component.components) } } } fileprivate func checkPair(rule: Rule, component: Component) { guard let path = currentPath else { return } let result = rule.checkComponent(component) guard !result.isOk else { return } if let message = result.message, let value = result.value { let violation = Violation(component: component, rule: rule, violationData: ViolationData(message: message, path: path, value: value)) violations.append(violation) updateStatisticsWithViolation(violation) } } fileprivate func updateStatisticsWithViolation(_ violation: Violation) { if !fileWasChecked { fileWasChecked = true Temper.statistics.filesWithViolations += 1 } switch violation.rule.priority { case 1: Temper.statistics.violationsWithP1 += 1 case 2: Temper.statistics.violationsWithP2 += 1 default: Temper.statistics.violationsWithP3 += 1 } } } struct TemperStatistics { var totalFiles: Int = 0 var filesWithViolations: Int = 0 var violationsWithP1: Int = 0 var violationsWithP2: Int = 0 var violationsWithP3: Int = 0 }
mit
4c4e186162765467d4f577d979d67648
32.103659
149
0.635476
4.830071
false
false
false
false
sven820/Brick
Brick/Pods/ReactiveCocoa/ReactiveCocoa/UIKit/UITextField.swift
2
2232
import ReactiveSwift import UIKit extension Reactive where Base: UITextField { /// Sets the text of the text field. public var text: BindingTarget<String?> { return makeBindingTarget { $0.text = $1 } } /// A signal of text values emitted by the text field upon end of editing. /// /// - note: To observe text values that change on all editing events, /// see `continuousTextValues`. public var textValues: Signal<String, Never> { return mapControlEvents([.editingDidEnd, .editingDidEndOnExit]) { $0.text ?? "" } } /// A signal of text values emitted by the text field upon any changes. /// /// - note: To observe text values only when editing ends, see `textValues`. public var continuousTextValues: Signal<String, Never> { return mapControlEvents(.allEditingEvents) { $0.text ?? "" } } /// Sets the attributed text of the text field. public var attributedText: BindingTarget<NSAttributedString?> { return makeBindingTarget { $0.attributedText = $1 } } /// Sets the placeholder text of the text field. public var placeholder: BindingTarget<String?> { return makeBindingTarget { $0.placeholder = $1 } } /// Sets the textColor of the text field. public var textColor: BindingTarget<UIColor> { return makeBindingTarget { $0.textColor = $1 } } /// A signal of attributed text values emitted by the text field upon end of editing. /// /// - note: To observe attributed text values that change on all editing events, /// see `continuousAttributedTextValues`. public var attributedTextValues: Signal<NSAttributedString, Never> { return mapControlEvents([.editingDidEnd, .editingDidEndOnExit]) { $0.attributedText ?? NSAttributedString() } } /// A signal of attributed text values emitted by the text field upon any changes. /// /// - note: To observe attributed text values only when editing ends, see `attributedTextValues`. public var continuousAttributedTextValues: Signal<NSAttributedString, Never> { return mapControlEvents(.allEditingEvents) { $0.attributedText ?? NSAttributedString() } } /// Sets the secure text entry attribute on the text field. public var isSecureTextEntry: BindingTarget<Bool> { return makeBindingTarget { $0.isSecureTextEntry = $1 } } }
mit
71d30a8f610cf5eb261ef3cbcb905c1e
36.830508
111
0.730287
4.171963
false
false
false
false
dunkelstern/UnchainedIPAddress
UnchainedIPAddress/ipaddress.swift
1
6693
// // ipaddress.swift // twohundred // // Created by Johannes Schriewer on 01/11/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // #if os(Linux) import Glibc #else import Darwin.C #endif import UnchainedString extension UInt16 { func hexString(padded padded:Bool = true) -> String { let dict:[Character] = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"] var result = "" var somethingWritten = false for i in 0...3 { let value = Int(self >> UInt16(((3 - i) * 4)) & 0xf) if !padded && !somethingWritten && value == 0 { continue } somethingWritten = true result.append(dict[value]) } if (result.characters.count == 0) { return "0" } return result } } public enum IPAddress { case IPv4(_: UInt8, _: UInt8, _: UInt8, _: UInt8) case IPv6(_: UInt16, _: UInt16, _: UInt16, _: UInt16, _: UInt16, _: UInt16, _: UInt16, _: UInt16) case Wildcard public init?(fromString inputString: String) { var fromString = inputString if fromString.hasPrefix("::ffff:") { // special case, this is a IPv4 address returned from the IPv6 stack fromString = inputString.subString(fromIndex: inputString.startIndex.advanced(by: 7)).stringByReplacing(":", replacement: ".") } if fromString.contains(":") { // IPv6 var components: [String] if fromString.hasPrefix("::") { components = fromString.subString(fromIndex: fromString.startIndex.advanced(by: 1)).split(":") } else { components = fromString.split(":") if components.count > 8 || components.count < 1 { return nil } } var segments = [UInt16]() var filled = false for component in components { if component.characters.count == 0 && !filled { filled = true for _ in 0...(8 - components.count) { segments.append(0) } continue } if let segment = UInt32(component, radix: 16) { if segment > 65535 { return nil } segments.append(UInt16(segment)) } else { return nil } } self = .IPv6(segments[0], segments[1], segments[2], segments[3], segments[4], segments[5], segments[6], segments[7]) } else { // IPv4 let components = fromString.split(".") if components.count != 4 { return nil } var segments = [UInt8]() for component in components { if let segment = UInt16(component, radix: 10) { if segment > 255 { return nil } segments.append(UInt8(segment)) } else { return nil } } self = .IPv4(segments[0], segments[1], segments[2], segments[3]) } } public func sin_addr() -> in_addr? { switch self { case .IPv4: var sa = in_addr() inet_pton(AF_INET, self.description, &sa) return sa case .Wildcard: var sa = in_addr() inet_pton(AF_INET, "0.0.0.0", &sa) return sa default: return nil } } public func sin6_addr() -> in6_addr? { switch self { case .IPv6: var sa = in6_addr() inet_pton(AF_INET6, self.description, &sa) return sa case .Wildcard: var sa = in6_addr() inet_pton(AF_INET6, "::", &sa) return sa default: return nil } } } extension IPAddress: CustomStringConvertible { public var description: String { switch(self) { case .IPv4(let s1, let s2, let s3, let s4): return "\(s1).\(s2).\(s3).\(s4)" case .IPv6(let s1, let s2, let s3, let s4, let s5, let s6, let s7, let s8): let segments = [s8, s7, s6, s5, s4, s3, s2, s1] var result = "" var gapStarted = false, gapEnded = false for segment in segments { if (segment == 0) && (!gapEnded) { if (!gapStarted) { gapStarted = true result = ":" + result } continue } if gapStarted && !gapEnded { gapEnded = true } result = ":" + segment.hexString(padded: false) + result } if !result.hasPrefix("::") { result = result.subString(fromIndex: result.startIndex.advanced(by: 1)) } return result case .Wildcard: return "*" } } } extension in_addr: CustomStringConvertible { public var description: String { var result = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN)) var copy = self inet_ntop(AF_INET, &copy, &result, socklen_t(INET_ADDRSTRLEN)) if let string = String(validatingUTF8: result) { return string } return "<in_addr: invalid>" } } extension in6_addr: CustomStringConvertible { public var description: String { var result = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN)) var copy = self inet_ntop(AF_INET6, &copy, &result, socklen_t(INET6_ADDRSTRLEN)) if let string = String(validatingUTF8: result) { return string } return "<in6_addr: invalid>" } } extension sockaddr_storage: CustomStringConvertible { public var description: String { var copy = self let result:String = withUnsafePointer(&copy) { ptr in var host = [CChar](repeating: 0, count: 1000) #if os(Linux) let len = socklen_t(_SS_SIZE) #else let len = socklen_t(copy.ss_len) #endif if getnameinfo(UnsafeMutablePointer(ptr), len, &host, 1000, nil, 0, NI_NUMERICHOST) == 0 { return String(validatingUTF8: host)! } else { return "<sockaddr: invalid>" } } return result } }
bsd-3-clause
2bcde3a53230c48e101556e3eb1a5979
31.173077
138
0.478631
4.385321
false
false
false
false
iwheelbuy/VK
VK/Method/Storage/VK+Method+Storage+GetKeys.swift
1
1876
import Foundation public extension Method.Storage { /// Возвращает названия всех переменных. public struct GetKeys: Strategy { /// Количество названий переменных, информацию о которых необходимо получить. Максимальное значение 1000, по умолчанию 100 public let count: Int /// Если необходимо работать с глобальными переменными, а не с переменными пользователя. public let global: Bool /// Смещение, необходимое для выборки определенного подмножества названий переменных. По умолчанию 0. public let offset: Int /// Специальный ключ доступа для идентификации в API public let token: Token public init(count: Int = 100, global: Bool = false, offset: Int = 0, token: Token) { assert(count > 0) assert(offset + count <= 1000) self.count = count self.global = global self.offset = offset self.token = token } public var method: String { return "storage.getKeys" } public var parameters: [String: Any] { var dictionary = [String: Any]() dictionary["access_token"] = token dictionary["count"] = count dictionary["global"] = global ? "1" : "0" dictionary["offset"] = offset return dictionary } public var transform: (Object.Response<[String]>) -> [String] { return { $0.response.filter({ $0.isEmpty == false }) } } } }
mit
175e4ace3107fc8633adaeaecb2b9585
36.926829
130
0.580064
3.956743
false
false
false
false
StupidTortoise/personal
iOS/Swift/Array_test.swift
1
1857
// Swift Array test let constantStringList = ["Apple", "Pear", "Banana"]; println( constantStringList[2] ) println( constantStringList.count ) if constantStringList.isEmpty { println( "constantStringList is empty!" ) } else { println( "constantStringList is not empty!" ) } println( constantStringList.first ) println( constantStringList.last ) for str in constantStringList { println( str ) } println( "============================================" ) // error readonly /* constantStringList[0] = "Wind" for str in constantStringList { println( str ) } */ var StringList = constantStringList StringList[1] = "Wind" for str in StringList { println( str ) } println( "============================================" ) StringList.append( "Door" ) for str in StringList { println( str ) } println( "============================================" ) StringList += ["Black", "White"] for str in StringList { println( str ) } println( "============================================" ) StringList[ 4...5 ] = ["One", "Two"] for str in StringList { println( str ) } println( "============================================" ) StringList.insert( "Zero", atIndex: 2 ) for str in StringList { println( str ) } println( "============================================" ) StringList.removeAtIndex( 3 ) for str in StringList { println( str ) } println( "============================================" ) StringList.removeLast() for str in StringList { println( str ) } println( "============================================" ) for (index, value) in enumerate( StringList ) { println( "index \(index + 1): \(value)" ) } var tempArray = constantStringList + StringList println( "============================================" ) for (index, value) in enumerate( tempArray ) { println( "index \(index + 1): \(value)" ) }
gpl-2.0
fc19de875959b01c92e99bc3db60804f
22.2125
57
0.516424
3.828866
false
false
false
false
cybersamx/FotoBox
iOS/FotoBox/DetailsViewController.swift
1
4852
// // DetailsViewController.swift // FotoBox // // Created by Samuel Chow on 7/26/16. // Copyright © 2016 Cybersam. All rights reserved. // // Credit: Based off of BOXSampleFileDetailsController (ObjC code) in the Box iOS sample code. import Foundation import UIKit import BoxContentSDK enum DetailsSection: Int { case FileInfo = 0 case OwnerInfo case Download case Count } class DetailsViewController: UITableViewController { let client = BOXContentClient.defaultClient() static var dateFormatter: NSDateFormatter { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy h:mm a" return dateFormatter } var request: BOXRequest? var itemID: String? var itemType: String? var item: BOXItem? // --- Private Helpers --- func fetchItem() { let request = client.fileInfoRequestWithID(itemID) request.requestAllFileFields = true request.performRequestWithCompletion { (file, error) in if error != nil { print("No items returned...") return } self.item = file self.tableView.reloadData() self.request = request } } // --- Override UIViewController --- override func viewDidLoad() { super.viewDidLoad() if item == nil { fetchItem() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } // --- Override UITableDataSource --- override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if self.item == nil { return 0 } return DetailsSection.Count.rawValue } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.item == nil { return 0 } switch section { case DetailsSection.FileInfo.rawValue: return 6 case DetailsSection.OwnerInfo.rawValue: return 2 case DetailsSection.Download.rawValue: return 1 default: return 0 } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title: String? switch section { case DetailsSection.FileInfo.rawValue: title = "General Info" case DetailsSection.OwnerInfo.rawValue: title = "Owner" default: title = "" } return title } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DetailsCell", forIndexPath: indexPath) switch indexPath.section { case DetailsSection.FileInfo.rawValue: switch indexPath.row { case 0: cell.textLabel?.text = "Name" cell.detailTextLabel?.text = item?.name case 1: cell.textLabel?.text = "Description" cell.detailTextLabel?.text = item?.itemDescription case 2: cell.textLabel?.text = "Created at" guard let createdDate = item?.createdDate else { break; } cell.detailTextLabel?.text = DetailsViewController.dateFormatter.stringFromDate(createdDate) case 3: cell.textLabel?.text = "Modified at" guard let modifiedDate = item?.modifiedDate else { break; } cell.detailTextLabel?.text = DetailsViewController.dateFormatter.stringFromDate(modifiedDate) case 4: cell.textLabel?.text = "Size (KB)" guard let size = item?.size?.unsignedIntegerValue else { break } let sizeKB = size/1024 cell.detailTextLabel?.text = "\(sizeKB)" case 5: cell.textLabel?.text = "Comments" var commentsCount: Int if item?.isFile == true { commentsCount = (item as! BOXFile).commentCount.integerValue } else if item?.isBookmark == true { commentsCount = (item as! BOXBookmark).commentCount.integerValue } else { commentsCount = 0 } cell.detailTextLabel?.text = "\(commentsCount)" default: cell.detailTextLabel?.text = "" } case DetailsSection.OwnerInfo.rawValue: if indexPath.row == 0 { cell.textLabel?.text = "Name" cell.detailTextLabel?.text = item?.owner.name } else if indexPath.row == 1 { cell.textLabel?.text = "Login" cell.detailTextLabel?.text = item?.owner.login } case DetailsSection.Download.rawValue: cell.textLabel?.text = "Download" if item?.isFile == true { cell.textLabel?.textColor = UIColor.blackColor() } else { cell.textLabel?.textColor = UIColor.lightGrayColor() } default: cell.textLabel?.text = "" } return cell } }
mit
07f2bfdc26b124acc3323432718373b9
25.80663
116
0.63925
4.769912
false
false
false
false
Bunn/firefox-ios
XCUITests/ScreenGraphTest.swift
1
10286
/* 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 MappaMundi import XCTest class ScreenGraphTest: XCTestCase { var navigator: MMNavigator<TestUserState>! var app: XCUIApplication! override func setUp() { app = XCUIApplication() navigator = createTestGraph(for: self, with: app).navigator() app.terminate() app.launchArguments = [LaunchArguments.Test, LaunchArguments.ClearProfile, LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew] app.activate() } } extension XCTestCase { func wait(forElement element: XCUIElement, timeout: TimeInterval) { let predicate = NSPredicate(format: "exists == 1") expectation(for: predicate, evaluatedWith: element) waitForExpectations(timeout: timeout) } } extension ScreenGraphTest { // Temoporary disable since it is failing intermittently on BB func testUserStateChanges() { XCTAssertNil(navigator.userState.url, "Current url is empty") navigator.userState.url = "https://mozilla.org" navigator.performAction(TestActions.LoadURLByTyping) // The UserState is mutated in BrowserTab. navigator.goto(BrowserTab) navigator.nowAt(BrowserTab) XCTAssertTrue(navigator.userState.url?.starts(with: "www.mozilla.org") ?? false, "Current url recorded by from the url bar is \(navigator.userState.url ?? "nil")") } func testBackStack() { // We'll go through the browser tab, through the menu. navigator.goto(SettingsScreen) // Going back, there is no explicit way back to the browser tab, // and the menu will have dismissed. We should be detecting the existence of // elements as we go through each screen state, so if there are errors, they'll be // reported in the graph below. navigator.goto(BrowserTab) } func testSimpleToggleAction() { // Switch night mode on, by toggling. navigator.performAction(TestActions.ToggleNightMode) XCTAssertTrue(navigator.userState.nightMode) navigator.back() XCTAssertEqual(navigator.screenState, BrowserTab) // Nothing should happen here, because night mode is already on. navigator.toggleOn(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode) XCTAssertTrue(navigator.userState.nightMode) XCTAssertEqual(navigator.screenState, BrowserTab) // Switch night mode off. navigator.toggleOff(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode) XCTAssertFalse(navigator.userState.nightMode) navigator.back() XCTAssertEqual(navigator.screenState, BrowserTab) } func testChainedActionPerf1() { let navigator = self.navigator! measure { navigator.userState.url = defaultURL navigator.performAction(TestActions.LoadURLByPasting) XCTAssertEqual(navigator.screenState, WebPageLoading) } } func testChainedActionPerf2() { let navigator = self.navigator! measure { navigator.userState.url = defaultURL navigator.performAction(TestActions.LoadURLByTyping) XCTAssertEqual(navigator.screenState, WebPageLoading) } navigator.userState.url = defaultURL navigator.performAction(TestActions.LoadURL) XCTAssertEqual(navigator.screenState, WebPageLoading) } func testConditionalEdgesSimple() { XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff)) XCTAssertFalse(navigator.can(goto: PasscodeSettingsOn)) navigator.goto(PasscodeSettingsOff) XCTAssertEqual(navigator.screenState, PasscodeSettingsOff) } func testConditionalEdgesRerouting() { // The navigator should dynamically reroute to the target screen // if the userState changes. // This test adds to the graph a passcode setting screen. In that screen, // there is a noop action that fatalErrors if it is taken. // let map = createTestGraph(for: self, with: app) func typePasscode(_ passCode: String) { passCode.forEach { char in app.keys["\(char)"].tap() } } map.addScreenState(SetPasscodeScreen) { screenState in // This is a silly way to organize things here, // and is an artifical way to show that the navigator is re-routing midway through // a goto. screenState.onEnter() { userState in typePasscode(userState.newPasscode) typePasscode(userState.newPasscode) userState.passcode = userState.newPasscode } screenState.noop(forAction: "FatalError", transitionTo: PasscodeSettingsOn, if: "passcode == nil") { _ in fatalError() } screenState.noop(forAction: "Very", "Long", "Path", "Of", "Actions", transitionTo: PasscodeSettingsOn, if: "passcode != nil") { _ in } } navigator = map.navigator() XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn)) XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff)) XCTAssertTrue(navigator.can(goto: "FatalError")) navigator.goto(PasscodeSettingsOn) XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn)) XCTAssertFalse(navigator.can(goto: PasscodeSettingsOff)) XCTAssertFalse(navigator.can(goto: "FatalError")) XCTAssertEqual(navigator.screenState, PasscodeSettingsOn) } } private let defaultURL = "https://example.com" @objcMembers class TestUserState: MMUserState { required init() { super.init() initialScreenState = FirstRun } var url: String? = nil var nightMode = false var passcode: String? = nil var newPasscode: String = "111111" } let PasscodeSettingsOn = "PasscodeSettingsOn" let PasscodeSettingsOff = "PasscodeSettingsOff" let WebPageLoading = "WebPageLoading" fileprivate class TestActions { static let ToggleNightMode = "menu-NightMode" static let LoadURL = "LoadURL" static let LoadURLByTyping = "LoadURLByTyping" static let LoadURLByPasting = "LoadURLByPasting" } public var isTablet: Bool { // There is more value in a variable having the same name, // so it can be used in both predicates and in code // than avoiding the duplication of one line of code. return UIDevice.current.userInterfaceIdiom == .pad } fileprivate func createTestGraph(for test: XCTestCase, with app: XCUIApplication) -> MMScreenGraph<TestUserState> { let map = MMScreenGraph(for: test, with: TestUserState.self) map.addScreenState(FirstRun) { screenState in screenState.noop(to: BrowserTab) screenState.tap(app.textFields["url"], to: URLBarOpen) } map.addScreenState(WebPageLoading) { screenState in screenState.dismissOnUse = true // Would like to use app.otherElements.deviceStatusBars.networkLoadingIndicators.element // but this means exposing some of SnapshotHelper to another target. // screenState.onEnterWaitFor("exists != true", // element: app.progressIndicators.element(boundBy: 0)) screenState.noop(to: BrowserTab) } map.addScreenState(BrowserTab) { screenState in screenState.onEnter { userState in userState.url = app.textFields["url"].value as? String } screenState.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu) screenState.tap(app.textFields["url"], to: URLBarOpen) screenState.gesture(forAction: TestActions.LoadURLByPasting, TestActions.LoadURL) { userState in UIPasteboard.general.string = userState.url ?? defaultURL app.textFields["url"].press(forDuration: 1.0) app.tables["Context Menu"].cells["menu-PasteAndGo"].firstMatch.tap() } } map.addScreenState(URLBarOpen) { screenState in screenState.gesture(forAction: TestActions.LoadURLByTyping, TestActions.LoadURL) { userState in let urlString = userState.url ?? defaultURL app.textFields["address"].typeText("\(urlString)\r") } } map.addScreenAction(TestActions.LoadURL, transitionTo: WebPageLoading) map.addScreenState(BrowserTabMenu) { screenState in screenState.dismissOnUse = true screenState.onEnterWaitFor(element: app.tables["Context Menu"]) screenState.tap(app.tables.cells["Settings"], to: SettingsScreen) screenState.tap(app.cells["menu-NightMode"], forAction: TestActions.ToggleNightMode, transitionTo: BrowserTabMenu) { userState in userState.nightMode = !userState.nightMode } screenState.backAction = { if isTablet { // There is no Cancel option in iPad. app.otherElements["PopoverDismissRegion"].tap() } else { app.buttons["PhotonMenu.close"].tap() } } } let navigationControllerBackAction = { app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap() } map.addScreenState(SettingsScreen) { screenState in let table = app.tables["AppSettingsTableViewController.tableView"] screenState.onEnterWaitFor(element: table) screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOff, if: "passcode == nil") screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOn, if: "passcode != nil") screenState.backAction = navigationControllerBackAction } map.addScreenState(PasscodeSettingsOn) { screenState in screenState.backAction = navigationControllerBackAction } map.addScreenState(PasscodeSettingsOff) { screenState in screenState.tap(app.staticTexts["Turn Passcode On"], to: SetPasscodeScreen) screenState.backAction = navigationControllerBackAction } map.addScreenState(SetPasscodeScreen) { screenState in screenState.backAction = navigationControllerBackAction } return map }
mpl-2.0
e3668eda64cb94e18e65fd55f254ee14
37.962121
171
0.679953
5.092079
false
true
false
false
LimonTop/StoreKit
StoreKit/NSManagedObject+Extras.swift
1
1424
// // NSManagedObject+Extras.swift // JSQCoreDataKit // // Created by Doug Mason on 9/6/15. // Copyright © 2015 Hexed Bits. All rights reserved. // import Foundation import CoreData public extension NSManagedObject { /** Convenience static function to grab name of an entity to make life easier when creating an NSEntityDescription instance especially on NSManagedObject subclass's during initialization. */ public static var entityName: String { let fullClassName = NSStringFromClass(object_getClass(self)) let nameComponents = fullClassName.characters.split { $0 == "." } .map { String($0) } return nameComponents.last! } /** This convenience initializer makes it easier to init an NSManagedObject subclass without needing to provide boiler plate code to setup an entity description in every subclass init method; simply make a call to init on self in your subclass. :param: context The NSManagedObjectContext to init the subclassed NSManagedObject with. */ public convenience init(context: NSManagedObjectContext) { let entityName = self.dynamicType.entityName let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)! self.init(entity: entity, insertIntoManagedObjectContext: context) } }
mit
d916764adc1ab38fea9e555614e8f7a1
37.459459
148
0.690794
5.494208
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/iOSSwiftStarter/Classes/Modules/DetailRepoModule/WireFrame/DetailRepoModuleWireFrame.swift
1
1557
// // Created by VIPER // Copyright (c) 2015 VIPER. All rights reserved. // import Foundation import UIKit class DetailRepoModuleWireFrame: DetailRepoModuleWireFrameProtocol { func presentDetailRepoModuleModule(fromView fromView: AnyObject, repo: Repo) { // Generating module components let view: DetailRepoModuleViewProtocol = Storyboards.Main.instantiateDetailRepoModuleView(); let presenter: protocol<DetailRepoModulePresenterProtocol, DetailRepoModuleInteractorOutputProtocol> = DetailRepoModulePresenter(); let interactor: DetailRepoModuleInteractorInputProtocol = DetailRepoModuleInteractor(); let APIDataManager: DetailRepoModuleAPIDataManagerInputProtocol = DetailRepoModuleAPIDataManager(); let localDataManager: DetailRepoModuleLocalDataManagerInputProtocol = DetailRepoModuleLocalDataManager(); let wireFrame: DetailRepoModuleWireFrameProtocol = DetailRepoModuleWireFrame(); // Connecting view.presenter = presenter; presenter.view = view; presenter.wireFrame = wireFrame; presenter.interactor = interactor; interactor.presenter = presenter; interactor.APIDataManager = APIDataManager; interactor.localDatamanager = localDataManager; // Present view if(fromView.isKindOfClass(UINavigationController)) { (fromView as! UINavigationController).pushViewController(view as! UIViewController, animated: true); presenter.detailItem = repo; } } }
apache-2.0
1cb5e7874f78d1c2c9ac034131f0a2cc
41.108108
139
0.73282
5.897727
false
false
false
false
soso1617/iCalendar
Calendar/ViewControllers/Base/BaseViewController.swift
1
3788
// // BaseViewController.swift // Calendar // // Created by Zhang, Eric X. on 4/30/17. // Copyright © 2017 ShangHe. All rights reserved. // import UIKit /********************************************************************* * * class BaseViewController * *********************************************************************/ class BaseViewController: UIViewController { // // sub-class could use this to hide/dispaly navigation bar // var bNeedTransparentNavigationBar = false convenience init() { self.init(nibName:nil, bundle:nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // // set view default background color // self.view.backgroundColor = UIColor.icBackground; // // do customization for each sub-class // self.initialFromLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // // do customization of navigation bar // self.configNavigationBar() } // // do initial here just like viewdidload, don't need super // func initialFromLoad() { // // sub-class should do initialization here // } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // // config nagivation bar, u'd better not to do the following things here, set title, set bar button items // subclass much load super // func configNavigationBar() { // // this will layout content view below navigation bar, same as UIRectEdge.none // self.edgesForExtendedLayout = [] // // set navigation controller background transparent // if self.bNeedTransparentNavigationBar { self.edgesForExtendedLayout = self.hidesBottomBarWhenPushed ? UIRectEdge.all : UIRectEdge.top self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() } else { self.navigationController?.navigationBar.setBackgroundImage(SystemUtility.crystalColorImage(crystalColor: UIColor.icGreen, gradiantSize: CGSize.init(width: SystemConfiguration.screenSize().width, height: kDefaultHeaderHeight), inset: UIEdgeInsets.zero), for: .default) self.navigationController?.navigationBar.shadowImage = nil } // // clear back button item title // self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "" , style: self.navigationItem.backBarButtonItem?.style ?? .plain, target: nil, action: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d5eef1dccfffd0118dbc07f256351aa3
28.130769
280
0.591233
5.464646
false
false
false
false
Shvier/Dota2Helper
Dota2Helper/Dota2Helper/Main/News/Controller/DHNewsDetailViewController.swift
1
2230
// // DHNewsDetailViewController.swift // Dota2Helper // // Created by Shvier on 9/22/16. // Copyright © 2016 Shvier. All rights reserved. // import UIKit import WebKit class DHNewsDetailViewController: DHBaseDetailViewController, WKNavigationDelegate { var newsModel: DHNewsModel? var newsDetailView: DHNewsDetailView? var loadingView: DHLoadingView? lazy var viewModel: DHNewsDetailViewModel = { return DHNewsDetailViewModel() }() // MARK: - 3D Touch Peek Menu @available(iOS 9.0, *) override var previewActionItems: [UIPreviewActionItem] { get { let openWithSafariAction: UIPreviewAction = UIPreviewAction(title: "使用Safari打开", style: .default, handler: { [unowned self] (UIPreviewAction, UIViewController) in self.viewModel.getDetailNews(model: self.newsModel!, { (urlString) in UIApplication.shared.openURL(URL(string: urlString)!) }, failure: {} ()) }) let cancelAction: UIPreviewAction = UIPreviewAction(title: "取消", style: .destructive, handler: { (UIPreviewAction, UIViewController) in }) return [openWithSafariAction, cancelAction] } set { } } // MARK: - Life Cycle func handleData() { newsDetailView = DHNewsDetailView(frame: CGRect(x: 0, y: 0, width: kNewsDetailViewWidth, height: kNewsDetailViewHeight - kTabBarHeight)) viewModel.getDetailNews(model: newsModel!, { (urlString) in self.newsDetailView?.loadRequest(request: URLRequest(url: URL(string: urlString)!)) }, failure: {} ()) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loadingView?.isHidden = true } func setContentView() { newsDetailView?.webView?.navigationDelegate = self view.addSubview(newsDetailView!) loadingView = addLoadingViewForViewController(self) } override func viewDidLoad() { super.viewDidLoad() handleData() setContentView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
d686e72229632f51a7f6871427b376ea
31.130435
174
0.639152
4.788337
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/UI/SectionHeader.swift
1
2592
// Copyright DApps Platform Inc. All rights reserved. import UIKit final class SectionHeader: UIView { private var fillColor: UIColor private var borderColor: UIColor private var title: String? private var textColor: UIColor private var textFont: UIFont init( fillColor: UIColor = UIColor(hex: "fafafa"), borderColor: UIColor = UIColor(hex: "e1e1e1"), title: String?, textColor: UIColor = UIColor(hex: "555357"), textFont: UIFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium) ) { self.fillColor = fillColor self.borderColor = borderColor self.title = title self.textColor = textColor self.textFont = textFont super.init(frame: .zero) addLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addLayout() { self.backgroundColor = fillColor let topBorder = UIView() topBorder.backgroundColor = borderColor let bottomBorder = UIView() bottomBorder.backgroundColor = borderColor let titleLabel = UILabel() titleLabel.text = title titleLabel.textColor = textColor titleLabel.font = textFont titleLabel.sizeToFit() self.addSubview(titleLabel) self.addSubview(topBorder) self.addSubview(bottomBorder) titleLabel.translatesAutoresizingMaskIntoConstraints = false topBorder.translatesAutoresizingMaskIntoConstraints = false bottomBorder.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ topBorder.trailingAnchor.constraint(equalTo: self.trailingAnchor), topBorder.leadingAnchor.constraint(equalTo: self.leadingAnchor), topBorder.topAnchor.constraint(equalTo: self.topAnchor), topBorder.heightAnchor.constraint(equalToConstant: 0.5), titleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0.0), titleLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0), titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20.0), bottomBorder.trailingAnchor.constraint(equalTo: self.trailingAnchor), bottomBorder.leadingAnchor.constraint(equalTo: self.leadingAnchor), bottomBorder.bottomAnchor.constraint(equalTo: self.bottomAnchor), bottomBorder.heightAnchor.constraint(equalToConstant: 0.5), ]) } }
gpl-3.0
7572be086291cee2f30de2ceb8905ac6
35
93
0.679398
5.456842
false
false
false
false
jonstaff/MultiActionDemoViewController
MultiActionDemoViewController/Classes/MultiActionDemoViewController.swift
1
1554
// // MultiActionDemoViewController.swift // MultiActionDemoViewController // // Created by Jonathon Staff on 8/25/16. // Copyright © 2016 Nplexity LLC. All rights reserved. // import UIKit open class MultiActionDemoViewController: UIViewController { open var actions: [Action] = [] { didSet { updateButtons() } } fileprivate var lookupTable: [UIButton: Action] = [:] fileprivate weak var stackView: UIStackView? open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white updateButtons() } } private extension MultiActionDemoViewController { func updateButtons() { self.stackView?.removeFromSuperview() lookupTable.removeAll() let stackView = UIStackView() stackView.distribution = .fillEqually stackView.axis = .vertical stackView.alignment = .center stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight] stackView.frame = CGRect(origin: CGPoint.zero, size: view.bounds.size) view.addSubview(stackView) for action in actions { let button = UIButton(type: .system) button.setTitle(action.title, for: UIControlState()) button.addTarget(self, action: #selector(invokeAction), for: .touchUpInside) lookupTable[button] = action stackView.addArrangedSubview(button) } self.stackView = stackView } @objc func invokeAction(_ button: UIButton) { if let action = lookupTable[button] { action.action() } else { print("No action provided for button: \(button)") } } }
mit
c1a98d550994698d8da15f3f50c45592
25.322034
82
0.69414
4.501449
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Tokens/Coordinators/TokensBalanceService.swift
1
1697
// Copyright DApps Platform Inc. All rights reserved. import Foundation import BigInt import JSONRPCKit import APIKit import Result import TrustCore public class TokensBalanceService { let server: RPCServer init( server: RPCServer ) { self.server = server } func getBalance( for address: Address, contract: Address, completion: @escaping (Result<BigInt, AnyError>) -> Void ) { guard let address = address as? EthereumAddress else { return } let encoded = ERC20Encoder.encodeBalanceOf(address: address) let request = EtherServiceRequest( for: server, batch: BatchFactory().create(CallRequest(to: contract.description, data: encoded.hexEncoded)) ) Session.send(request) { result in switch result { case .success(let balance): let biguint = BigUInt(Data(hex: balance)) completion(.success(BigInt(sign: .plus, magnitude: biguint))) case .failure(let error): completion(.failure(AnyError(error))) } } } func getBalance( for address: Address, completion: @escaping (Result<Balance, AnyError>) -> Void ) { let request = EtherServiceRequest(for: server, batch: BatchFactory().create(BalanceRequest(address: address.description))) Session.send(request) { result in switch result { case .success(let balance): completion(.success(balance)) case .failure(let error): completion(.failure(AnyError(error))) } } } }
gpl-3.0
b170f799d255f88c4d6a7629a9b16f42
27.762712
130
0.591043
4.807365
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/LiquidLoade/LiquidLoader.swift
1
1553
// // LiquidLoader.swift // LiquidLoading // // Created by Takuma Yoshida on 2015/08/24. // Copyright (c) 2015年 yoavlt. All rights reserved. // import Foundation import UIKit public enum Effect { case Line(UIColor) case Circle(UIColor) case GrowLine(UIColor) case GrowCircle(UIColor) func setup(loader: LiquidLoader) -> LiquidLoadEffect { switch self { case .Line(let color): return LiquidLineEffect(loader: loader, color: color) case .Circle(let color): return LiquidCircleEffect(loader: loader, color: color) case .GrowLine(let color): let line = LiquidLineEffect(loader: loader, color: color) line.isGrow = true return line case .GrowCircle(let color): let circle = LiquidCircleEffect(loader: loader, color: color) circle.isGrow = true return circle } } } public class LiquidLoader : UIView { private let effect: Effect private var effectDelegate: LiquidLoadEffect? public init(frame: CGRect, effect: Effect) { self.effect = effect super.init(frame: frame) self.effectDelegate = self.effect.setup(self) } public required init?(coder aDecoder: NSCoder) { self.effect = .Circle(UIColor.whiteColor()) super.init(coder: aDecoder) self.effectDelegate = self.effect.setup(self) } public func show() { self.hidden = false } public func hide() { self.hidden = true } }
apache-2.0
6c80787698c435dd9e08dedf19ff3696
25.305085
73
0.62089
4.169355
false
false
false
false
pattypatpat2632/EveryoneGetsToDJ
EveryoneGetsToDJ/EveryoneGetsToDJ/UIViewExt.swift
1
3279
// // UIViewExt.swift // EveryoneGetsToDJ // // Created by Patrick O'Leary on 6/28/17. // Copyright © 2017 Patrick O'Leary. All rights reserved. // import Foundation extension UIView: DJView { func flash() { let bgColor = self.backgroundColor UIView.animateKeyframes(withDuration: 0.8, delay: 0, options: .calculationModeLinear, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: { self.backgroundColor = self.colorScheme.model.highlightColor }) UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.2, animations: { self.backgroundColor = bgColor }) UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.2, animations: { self.backgroundColor = self.colorScheme.model.highlightColor }) UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.2, animations: { self.backgroundColor = bgColor }) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.4, animations: { self.transform = CGAffineTransform(scaleX: 1.4, y: 1.4) }) UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.4, animations: { self.transform = CGAffineTransform(scaleX: 1, y: 1) }) }, completion: nil) } func hide() { self.isHidden = true } func display() { self.isHidden = false } } extension UIView { public func addInnerShadow(topColor: UIColor = UIColor.black.withAlphaComponent(0.3), bottomColor: UIColor = UIColor.white.withAlphaComponent(0)) { let topLayer = CAGradientLayer() topLayer.cornerRadius = layer.cornerRadius topLayer.frame = bounds topLayer.colors = [ topColor.cgColor, bottomColor.cgColor ] topLayer.endPoint = CGPoint(x: 0.5, y: 0.1) let bottomLayer = CAGradientLayer() bottomLayer.cornerRadius = layer.cornerRadius bottomLayer.frame = bounds bottomLayer.colors = [ topColor.cgColor, bottomColor.cgColor ] bottomLayer.startPoint = CGPoint(x: 0.5, y: 1) bottomLayer.endPoint = CGPoint(x: 0.5, y: 0.9) let leftLayer = CAGradientLayer() leftLayer.cornerRadius = layer.cornerRadius leftLayer.frame = bounds leftLayer.colors = [ topColor.cgColor, bottomColor.cgColor ] leftLayer.startPoint = CGPoint(x: 0, y: 0.5) leftLayer.endPoint = CGPoint(x: 0.025, y: 0.5) let rightLeyer = CAGradientLayer() rightLeyer.cornerRadius = layer.cornerRadius rightLeyer.frame = bounds rightLeyer.colors = [ topColor.cgColor, bottomColor.cgColor ] rightLeyer.startPoint = CGPoint(x: 1, y: 0.5) rightLeyer.endPoint = CGPoint(x: 0.975, y: 0.5) layer.addSublayer(topLayer) layer.addSublayer(bottomLayer) layer.addSublayer(rightLeyer) layer.addSublayer(leftLayer) } }
mit
800308c1d529d185dd4a3e5011d5103d
33.145833
151
0.599451
4.610408
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPBounceView.swift
1
2770
// // KPBounceView.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/5/14. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit class KPBounceView: UIView { //---------------------------- // MARK: - Properties //---------------------------- var selected: Bool = false { didSet { icon.tintColor = selected ? selectedColor : unSelectedColor if selected && oldValue != selected { performBounceAnimation() } } } var icon: UIImageView! var iconSize: CGSize! { didSet { self.icon.addConstraint(forWidth: iconSize.width) self.icon.addConstraint(forHeight: iconSize.height) } } var selectedColor = KPColorPalette.KPMainColor.starColor var unSelectedColor = KPColorPalette.KPMainColor.grayColor_level4 var dampingRatio: CGFloat = 0.35 var bounceDuration: Double = 0.8 //---------------------------- // MARK: - Initalization //---------------------------- required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) } convenience init(_ iconImage: UIImage) { self.init(frame: .zero) icon = UIImageView(image: iconImage.withRenderingMode(.alwaysTemplate)) icon.tintColor = unSelectedColor addSubview(icon) icon.contentMode = .scaleAspectFit icon.addConstraintForCenterAligningToSuperview(in: .vertical) icon.addConstraintForCenterAligningToSuperview(in: .horizontal) selected = false } private func performTouchEndAnimation() { UIView.animate(withDuration: bounceDuration, delay: 0, usingSpringWithDamping: dampingRatio, initialSpringVelocity: 1, options: UIViewAnimationOptions.beginFromCurrentState, animations: { self.layer.transform = CATransform3DIdentity; }) { _ in } } private func performBounceAnimation() { layer.transform = CATransform3DScale(CATransform3DIdentity, 0.8, 0.8, 1.0); UIView.animate(withDuration: bounceDuration, delay: 0, usingSpringWithDamping: dampingRatio, initialSpringVelocity: 1, options: UIViewAnimationOptions.beginFromCurrentState, animations: { self.layer.transform = CATransform3DIdentity; }) { _ in } } }
mit
8b5f477a8443ff1b0214705c5219faee
29.406593
83
0.549693
5.578629
false
false
false
false
czechboy0/Buildasaur
Buildasaur/SyncerViewModel.swift
2
3158
// // SyncerViewModel.swift // Buildasaur // // Created by Honza Dvorsky on 28/09/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaKit import ReactiveCocoa import Result struct SyncerStatePresenter { static func stringForState(state: SyncerEventType, active: Bool) -> String { guard active else { return "🚧 stopped" } let errorGen = { () -> String in "❗ error!" } switch state { case .DidStartSyncing: return "🔄 syncing..." case .DidFinishSyncing(let error): if error != nil { return errorGen() } case .DidEncounterError(_): return errorGen() default: break } return "✅ idle..." } } struct SyncerViewModel { let syncer: StandardSyncer let status: SignalProducer<String, NoError> let host: SignalProducer<String, NoError> let projectName: SignalProducer<String, NoError> let initialProjectName: String let buildTemplateName: SignalProducer<String, NoError> let editButtonTitle: SignalProducer<String, NoError> let editButtonEnabled: SignalProducer<Bool, NoError> let controlButtonTitle: SignalProducer<String, NoError> typealias PresentEditViewControllerType = (ConfigTriplet) -> () let presentEditViewController: PresentEditViewControllerType init(syncer: StandardSyncer, presentEditViewController: PresentEditViewControllerType) { self.syncer = syncer self.presentEditViewController = presentEditViewController let active = syncer.activeSignalProducer.producer let state = syncer.state.producer self.status = combineLatest(state, active) .map { SyncerStatePresenter.stringForState($0.0, active: $0.1) } self.host = SignalProducer(value: syncer.xcodeServer) .map { $0.config.host ?? "[No Xcode Server]" } self.projectName = SignalProducer(value: syncer.project) .map { $0.workspaceMetadata?.projectName ?? "[No Project]" } //pull initial project name for sorting self.initialProjectName = syncer.project.workspaceMetadata?.projectName ?? "" self.buildTemplateName = SignalProducer(value: syncer.buildTemplate.name) self.editButtonTitle = SignalProducer(value: "View") self.editButtonEnabled = SignalProducer(value: true) self.controlButtonTitle = active.map { $0 ? "Stop" : "Start" } } func viewButtonClicked() { //present the edit window let triplet = self.syncer.configTriplet self.presentEditViewController(triplet) } func startButtonClicked() { //TODO: run through validation first? self.syncer.active = true } func stopButtonClicked() { self.syncer.active = false } func controlButtonClicked() { //TODO: run through validation first? self.syncer.active = !self.syncer.active } }
mit
d6db77dace509835020b21cb515a117d
29.259615
92
0.629488
5.043269
false
false
false
false
PigDogBay/Food-Hygiene-Ratings
Food Hygiene Ratings/GooglePlaceImage.swift
1
1091
// // GooglePlaceImage.swift // Food Hygiene Ratings // // Created by Mark Bailey on 20/09/2018. // Copyright © 2018 MPD Bailey Technology. All rights reserved. // import Foundation import GooglePlaces class GooglePlaceImage : IPlaceImage { private(set) var attribution: NSAttributedString? = nil private(set) var observableStatus: ObservableProperty<FetchStatus> = ObservableProperty<FetchStatus>(.uninitialized) private(set) var image: UIImage? = nil var index: Int = 0 private let metadata : GMSPlacePhotoMetadata init(metadata : GMSPlacePhotoMetadata){ self.metadata = metadata self.attribution = metadata.attributions observableStatus.owner = self } func fetchBitmap() { observableStatus.value = .fetching GMSPlacesClient.shared().loadPlacePhoto(metadata){ result, _ in if let result = result { self.image = result self.observableStatus.value = .ready return } self.observableStatus.value = .error } } }
apache-2.0
12b846d82b9e2c89559c9472cfbd2a9a
28.459459
120
0.654128
4.678112
false
false
false
false
orta/Agrume
Example/Agrume Example/MultipleImagesCollectionViewController.swift
2
1688
// // MultipleImagesCollectionViewController.swift // Agrume Example // import UIKit import Agrume class MultipleImagesCollectionViewController: UICollectionViewController { private let identifier = "Cell" private let images = [ UIImage(named: "MapleBacon")!, UIImage(named: "EvilBacon")! ] override func viewDidLoad() { super.viewDidLoad() let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: CGRectGetWidth(view.bounds), height: CGRectGetHeight(view.bounds)) } // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! DemoCell cell.imageView.image = images[indexPath.row] return cell } // MARK: UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let agrume = Agrume(images: images, startIndex: indexPath.row, backgroundBlurStyle: .Light) agrume.didScroll = { [unowned self] index in self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0), atScrollPosition: .allZeros, animated: false) } agrume.showFrom(self) } }
mit
3bc282bd87f73b67cae50a2248e0024a
32.76
139
0.702014
5.589404
false
false
false
false
sarunw/SWSegmentedControl
Pod/Classes/SWBadgeView.swift
1
3168
// // SWBadgeView.swift // FBSnapshotTestCase // // Created by Sarun Wongpatcharapakorn on 5/17/18. // import Foundation private let VerticalPadding: CGFloat = 2 private let HorizontalPadding: CGFloat = 5 public class SWBadgeView: UIView { public var label = UILabel() public var badgeColor: UIColor? { didSet { configureView() } } public var contentInsets: UIEdgeInsets? { didSet { configureView() } } private var topLayoutConstraint: NSLayoutConstraint! private var leadingLayoutConstraint: NSLayoutConstraint! private var trailingLayoutConstraint: NSLayoutConstraint! private var bottomLayoutConstraint: NSLayoutConstraint! private var colorToUse: UIColor { return badgeColor ?? tintColor } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func awakeFromNib() { super.awakeFromNib() commonInit() } private func configureView() { backgroundColor = colorToUse let contentInsets = self.contentInsets ?? UIEdgeInsets(top: VerticalPadding, left: HorizontalPadding, bottom: VerticalPadding, right: HorizontalPadding) leadingLayoutConstraint.constant = contentInsets.left trailingLayoutConstraint.constant = contentInsets.right topLayoutConstraint.constant = contentInsets.top bottomLayoutConstraint.constant = contentInsets.bottom layoutIfNeeded() } private func commonInit() { backgroundColor = tintColor label.font = UIFont.systemFont(ofSize: 12) label.textColor = .white label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) leadingLayoutConstraint = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: HorizontalPadding) trailingLayoutConstraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: label, attribute: .trailing, multiplier: 1, constant: HorizontalPadding) topLayoutConstraint = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: VerticalPadding) bottomLayoutConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1, constant: VerticalPadding) addConstraints([ leadingLayoutConstraint, trailingLayoutConstraint, topLayoutConstraint, bottomLayoutConstraint ]) } override public func tintColorDidChange() { super.tintColorDidChange() configureView() } override public func layoutSubviews() { super.layoutSubviews() let minLength = min(bounds.size.width, bounds.size.height) layer.cornerRadius = minLength / 2 } }
mit
7de8dac89302ec110840b4130a5261e2
32.347368
187
0.668561
5.509565
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemSinDeg.swift
1
899
import UIKit class MCalculatorFunctionsItemSinDeg:MCalculatorFunctionsItem { init() { let icon:UIImage = #imageLiteral(resourceName: "assetFunctionSin") let title:String = NSLocalizedString("MCalculatorFunctionsItemSinDeg_title", comment:"") super.init( icon:icon, title:title) } override func processFunction( currentValue:Double, currentString:String, modelKeyboard:MKeyboard, view:UITextView) { let sinDegValue:Double = sin(currentValue * M_PI / 180.0) let sinDegString:String = modelKeyboard.numberAsString(scalar:sinDegValue) let descr:String = "deg sin(\(currentString)) = \(sinDegString)" applyUpdate( modelKeyboard:modelKeyboard, view:view, newEditing:sinDegString, descr:descr) } }
mit
31e7deecb6e4f07da333da3dd7e69c08
28
96
0.619577
4.540404
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Tests/KnowledgeDetailComponentTests/Presenter Tests/Test Doubles/StubKnowledgeDetailSceneInteractor.swift
1
2417
import EurofurenceModel import Foundation import KnowledgeDetailComponent import TestUtilities import XCTEurofurenceModel final class StubKnowledgeEntryDetailViewModel: KnowledgeEntryDetailViewModel { var title: String var contents: NSAttributedString var links: [LinkViewModel] var images: [KnowledgeEntryImageViewModel] var modelLinks: [Link] init(title: String, contents: NSAttributedString, links: [LinkViewModel], images: [KnowledgeEntryImageViewModel], modelLinks: [Link]) { self.title = title self.contents = contents self.links = links self.images = images self.modelLinks = modelLinks } func link(at index: Int) -> Link { return modelLinks[index] } private(set) var shareSender: AnyObject? func shareKnowledgeEntry(_ sender: AnyObject) { shareSender = sender } } extension StubKnowledgeEntryDetailViewModel: RandomValueProviding { static var random: StubKnowledgeEntryDetailViewModel { let linkModels = [Link].random let linkViewModels: [LinkViewModel] = .random(upperLimit: linkModels.count) return StubKnowledgeEntryDetailViewModel(title: .random, contents: .random, links: linkViewModels, images: .random, modelLinks: linkModels) } static var randomWithoutLinks: StubKnowledgeEntryDetailViewModel { let viewModel = random viewModel.links = [] viewModel.modelLinks = [] return viewModel } } extension LinkViewModel: RandomValueProviding { public static var random: LinkViewModel { return LinkViewModel(name: .random) } } extension KnowledgeEntryImageViewModel: RandomValueProviding { public static var random: KnowledgeEntryImageViewModel { return KnowledgeEntryImageViewModel(imagePNGData: .random) } } class StubKnowledgeDetailViewModelFactory: KnowledgeDetailViewModelFactory { var viewModel = StubKnowledgeEntryDetailViewModel.random func makeViewModel( for entry: KnowledgeEntryIdentifier, completionHandler: @escaping (KnowledgeEntryDetailViewModel) -> Void ) { completionHandler(viewModel) } }
mit
f0f1ddcaa3d39f1c0654410e4d435043
26.781609
83
0.654117
5.634033
false
false
false
false
kdw9/TIY-Assignments
TheNewHeroTracker/The New Hero Tracker/TipsTableViewController.swift
1
5974
// // TipsTableViewController.swift // The New Hero Tracker // // Created by Keron Williams on 11/6/15. // Copyright © 2015 The Iron Yard. All rights reserved. // // //import UIKit // //class TipsTableViewController: UITableViewController, UITextFieldDelegate //{ // // var tips = [PFObject]() // // override func viewDidLoad() // { // super.viewDidLoad() // navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addTip:") // // } // // // override func viewDidAppear(animated: Bool) // { // super.viewWillAppear(animated) // if PFUser.currentUser() == nil // { // performSegueWithIdentifier("ShowLoginModalSegue", sender: self) // } // else // { // refreshTips() // } // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } // // // MARK: - Table view data source // // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // #warning Incomplete implementation, return the number of sections // return 1 // } // // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // // #warning Incomplete implementation, return the number of rows // return tips.count // } // // // override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCellWithIdentifier("TipCell", forIndexPath: indexPath) as! TipTableViewCell // // let aTip = tips[indexPath.row] // if let comment = aTip["comment"] as? String // { // if comment == "" // { // cell.textFeild.becomeFirstResponder() // } // else // { // cell.textFeild.text = aTip["comment"] as? String // } // // return cell // } // // // MARK: - Parse Queries // // func refreshTips() // { // if PFUser.currentUser() != nil // { // let query = PFQuery(className: "Tip") // query.findObjectsInBackgroundWithBlock {(objects: [PFObject]?, error: NSError?) -> Void in // if error == nil // { // self.tips = objects! // self.tableView.reloadData() // } // else // { // print(error?.localizedDescription) // } // } // } // } // // /* // // 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. // } // */ // // // //MARK: - Action Handlers // // @IBAction func unwindToTipsTableViewController(unwindSegue: UIStoryboardSegue) // { // refreshTips() // } // // @IBAction func addTip(Sender: UIBarButtonItem) // { // let aTip = PFObject(className: "Tip") // tips.insert(aTip, atIndex:0) // let indexPath = NSIndexPath(forRow: 0, inSection: 0) // tableView .insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) // // } // // // MARK: - Textfeild Delegate // // func textFieldShouldReturn(textField: UITextField) -> Bool // { // var rc = false // if textField.text != "" // { // rc = true // // textField.resignFirstResponder() // let contentView = textField.superview // let cell = contentView?.superview as? TipTableViewCell // let indexPath = tableView.indexPathForCell(cell!) // let aTip = tips[indexPath!.row] // aTip["comment"] = textField.text // aTip.saveInBackgroundWithBlock {(succeeded: Bool, error: NSError?) -> Void in // if succeeded // { // // Object was saved to Parse // } // else // { // print(error?.localizedDescription) // } // } // } // return rc // } // //} // // // // //}
cc0-1.0
d955ee9259eca32ae2fbaf0d9feb0992
30.442105
159
0.564038
4.300216
false
false
false
false
ppei/ioscreator
IOS8SwiftMapKitTutorial/IOS8SwiftMapKitTutorial/ViewController.swift
37
985
// // ViewController.swift // IOS8SwiftMapKitTutorial // // Created by Arthur Knopper on 17/08/14. // Copyright (c) 2014 Arthur Knopper. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() let location = CLLocationCoordinate2D( latitude: 51.50007773, longitude: -0.1246402 ) let span = MKCoordinateSpanMake(0.05, 0.05) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = "Big Ben" annotation.subtitle = "London" mapView.addAnnotation(annotation) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3d8a3482b406ef09ce509872b8e89400
21.906977
65
0.673096
4.560185
false
false
false
false
samsymons/Photon
Photon/Images/Image.swift
1
4303
// Image.swift // Copyright (c) 2017 Sam Symons // // 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 import CoreGraphics #if os(iOS) || os(tvOS) || os(watchOS) import UIKit public typealias ImageType = UIImage #elseif os(OSX) import Cocoa public typealias ImageType = NSImage #endif public typealias Color = PixelData /// Represents a single pixel color. /// /// - Note: The alpha channel is largely ignored throughout the framework, and /// is only included to satisfy CGImage. There should always be maximum /// alpha; no pixels are transparent. public struct PixelData { public static let white = PixelData(r: UInt8.max, g: UInt8.max, b: UInt8.max) public let r: UInt8 public let g: UInt8 public let b: UInt8 public let a: UInt8 = 255 public init(r: UInt8, g: UInt8, b: UInt8) { self.r = r self.g = g self.b = b } } extension PixelData: Equatable { public static func == (lhs: PixelData, rhs: PixelData) -> Bool { return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a } public static func * (lhs: PixelData, rhs: Float) -> PixelData { let floatR = Float(lhs.r) * rhs let floatG = Float(lhs.g) * rhs let floatB = Float(lhs.b) * rhs return PixelData(r: UInt8(floatR), g: UInt8(floatG), b: UInt8(floatB)) } } /// `Image` provides helpers functions for generating a platform-friendly image /// from an array of `PixelData` structs. public struct Image { private static let colorSpace = CGColorSpaceCreateDeviceRGB() private static let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue) /// Returns an image from a given array of `PixelData`. /// /// - Parameter pixels: An array of `PixelData` to be used in the image. /// - Parameter width: The width of the image. /// - Parameter height: The height of the image. /// /// - Note: The value of `width` * `height` must equal the size of the pixels array. /// This condition is tested with an assert. public static func image(from pixels: [PixelData], width: Int, height: Int) -> ImageType? { let bitsPerComponent: Int = MemoryLayout<UInt8>.size * 8 let bitsPerPixel: Int = MemoryLayout<PixelData>.size * 8 assert(pixels.count == Int(width * height), "The pixel count should match the provided image size") var mutablePixelData = pixels guard let providerRef = CGDataProvider(data: NSData(bytes: &mutablePixelData, length: mutablePixelData.count * MemoryLayout<PixelData>.size)) else { preconditionFailure("Failed to create a CGDataProvider") } let image = CGImage( width: width, height: height, bitsPerComponent: bitsPerComponent, bitsPerPixel: bitsPerPixel, bytesPerRow: width * MemoryLayout<PixelData>.size, space: Image.colorSpace, bitmapInfo: Image.bitmapInfo, provider: providerRef, decode: nil, shouldInterpolate: true, intent: .defaultIntent ) guard let unwrappedImage = image else { return nil } #if os(iOS) || os(tvOS) || os(watchOS) return UIImage(cgImage: unwrappedImage) #elseif os(OSX) return NSImage(cgImage: unwrappedImage, size: NSSize(width: width, height: height)) #endif } }
mit
a60e4679500335505852899d3e14cb87
35.466102
152
0.699744
4.109838
false
false
false
false
qvacua/vimr
NvimView/Sources/NvimView/ColorUtils.swift
1
1272
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import Commons final class ColorUtils { /// ARGB static func cgColorIgnoringAlpha(_ rgb: Int) -> CGColor { if let color = cgColorCache.valueForKey(rgb) { return color } let color = self.colorIgnoringAlpha(rgb).cgColor cgColorCache.set(color, forKey: rgb) return color } static func cgColorIgnoringAlpha(_ rgb: Int32) -> CGColor { if let color = cgColorCache.valueForKey(Int(rgb)) { return color } let color = self.colorIgnoringAlpha(Int(rgb)).cgColor cgColorCache.set(color, forKey: Int(rgb)) return color } /// ARGB static func colorIgnoringAlpha(_ rgb: Int) -> NSColor { if let color = colorCache.valueForKey(rgb) { return color } // @formatter:off let red = ((rgb >> 16) & 0xFF).cgf / 255.0 let green = ((rgb >> 8) & 0xFF).cgf / 255.0 let blue = (rgb & 0xFF).cgf / 255.0 // @formatter:on let color = NSColor(srgbRed: red, green: green, blue: blue, alpha: 1.0) colorCache.set(color, forKey: rgb) return color } } private let colorCache = FifoCache<Int, NSColor>(count: 500, queueQos: .userInteractive) private let cgColorCache = FifoCache<Int, CGColor>(count: 500, queueQos: .userInteractive)
mit
7cfe487fe9a4105b6a4695219183f93b
26.06383
90
0.665094
3.583099
false
false
false
false
EstefaniaGilVaquero/ciceIOS
App_VolksWagenFinal-/App_VolksWagenFinal-/VWOfertasTableViewController.swift
1
2523
// // VWOfertasTableViewController.swift // App_VolksWagenFinal_CICE // // Created by Formador on 17/10/16. // Copyright © 2016 icologic. All rights reserved. // import UIKit class VWOfertasTableViewController: UITableViewController { //MARK: - VARIABLES LOCALES GLOBALES var refreshTVC = UIRefreshControl() var arrayOfertas = [VWOfertasModel]() override func viewDidLoad() { super.viewDidLoad() refreshTVC.backgroundColor = UIColor(red: 255/255, green: 128/255, blue: 0/255, alpha: 1.0) refreshTVC.attributedTitle = NSAttributedString(string: CONSTANTES.TEXTO_RECARGA_TABLA) refreshTVC.addTarget(self, action: Selector(refreshFunction(tableView, endRefreshTVC: refreshTVC)), forControlEvents: .EditingDidEnd) tableView.addSubview(refreshTVC) //Aqui alimentamos nuestro array arrayOfertas = VWAPIManager.sharedInstance.getOfertasParse() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return arrayOfertas.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! VWOfertasCustomCell let ofertasData = arrayOfertas[indexPath.row] cell.myMasInformacionLBL.text = ofertasData.descripcion cell.myFechaFin.text = ofertasData.fechaFin! cell.myImagenOferta.kf_setImageWithURL(NSURL(string: getImagePath(ofertasData.imagen!))) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let detalleOfertaVC = self.storyboard?.instantiateViewControllerWithIdentifier("detalleOfertaFinal") as! VWDetalleOfertasViewController detalleOfertaVC.arrayOfertasData = arrayOfertas[indexPath.row] navigationController?.pushViewController(detalleOfertaVC, animated: true) } }
apache-2.0
65ecce320ac9fe52e0ba3d5145931926
36.088235
143
0.713323
4.60219
false
false
false
false
masters3d/xswift
exercises/matrix/Sources/MatrixExample.swift
1
671
struct Matrix { let rows: [[Int]] let columns: [[Int]] init(_ stringRepresentation: String) { var rows = [[Int]]() var columns = [[Int]]() let rowItems = stringRepresentation.characters.split(separator: "\n") for item in rowItems { let elements = item.split(separator: " ").flatMap { Int(String($0)) } rows.append(elements) } for i in 0 ..< rows[0].count { var column = [Int]() for row in rows { column.append(row[i]) } columns.append(column) } self.rows = rows self.columns = columns } }
mit
7781d661dba604512c31ca882fe279e5
22.964286
81
0.493294
4.385621
false
false
false
false
avito-tech/Marshroute
Marshroute/Sources/Transitions/TransitionAnimationsLaunching/Modal/Presentation/ModalPresentationAnimationLaunchingContext.swift
1
1508
import UIKit /// Описание параметров запуска анимаций прямого модального перехода на UIViewController public struct ModalPresentationAnimationLaunchingContext { /// контроллер, на который нужно осуществить модальный переход public private(set) weak var targetViewController: UIViewController? /// аниматор, выполняющий анимации прямого и обратного перехода public let animator: ModalTransitionsAnimator public init( targetViewController: UIViewController, animator: ModalTransitionsAnimator) { self.targetViewController = targetViewController self.animator = animator } // контроллер, с которого нужно осуществить модальный переход public weak var sourceViewController: UIViewController? public var isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute: Bool { if targetViewController == nil { return true } if sourceViewController?.presentedViewController == nil { marshrouteAssertionFailure( """ It looks like \(targetViewController as Any) did not deallocate due to some retain cycle! """ ) return true } return false } }
mit
f1a943b53842c38aa6dee3d63582302f
32.179487
106
0.670015
5.601732
false
false
false
false
nanthi1990/CVCalendar
CVCalendar/CVCalendarTouchController.swift
8
4655
// // CVCalendarTouchController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 17/03/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public final class CVCalendarTouchController { private unowned let calendarView: CalendarView // MARK: - Properties public var coordinator: Coordinator { get { return calendarView.coordinator } } /// Init. public init(calendarView: CalendarView) { self.calendarView = calendarView } } // MARK: - Events receive extension CVCalendarTouchController { public func receiveTouchLocation(location: CGPoint, inMonthView monthView: CVCalendarMonthView, withSelectionType selectionType: CVSelectionType) { let weekViews = monthView.weekViews if let dayView = ownerTouchLocation(location, onMonthView: monthView) where dayView.userInteractionEnabled { receiveTouchOnDayView(dayView, withSelectionType: selectionType) } } public func receiveTouchLocation(location: CGPoint, inWeekView weekView: CVCalendarWeekView, withSelectionType selectionType: CVSelectionType) { let monthView = weekView.monthView let index = weekView.index let weekViews = monthView.weekViews if let dayView = ownerTouchLocation(location, onWeekView: weekView) where dayView.userInteractionEnabled { receiveTouchOnDayView(dayView, withSelectionType: selectionType) } } public func receiveTouchOnDayView(dayView: CVCalendarDayView) { coordinator.performDayViewSingleSelection(dayView) } } // MARK: - Events management private extension CVCalendarTouchController { func receiveTouchOnDayView(dayView: CVCalendarDayView, withSelectionType selectionType: CVSelectionType) { if let calendarView = dayView.weekView.monthView.calendarView { switch selectionType { case .Single: coordinator.performDayViewSingleSelection(dayView) calendarView.didSelectDayView(dayView) case let .Range(.Started): println("Received start of range selection.") case let .Range(.Changed): println("Received change of range selection.") case let .Range(.Ended): println("Received end of range selection.") default: break } } } func monthViewLocation(location: CGPoint, doesBelongToDayView dayView: CVCalendarDayView) -> Bool { var dayViewFrame = dayView.frame let weekIndex = dayView.weekView.index let appearance = dayView.calendarView.appearance if weekIndex > 0 { dayViewFrame.origin.y += dayViewFrame.height dayViewFrame.origin.y *= CGFloat(dayView.weekView.index) } if dayView != dayView.weekView.dayViews!.first! { dayViewFrame.origin.y += appearance.spaceBetweenWeekViews! * CGFloat(weekIndex) } if location.x >= dayViewFrame.origin.x && location.x <= CGRectGetMaxX(dayViewFrame) && location.y >= dayViewFrame.origin.y && location.y <= CGRectGetMaxY(dayViewFrame) { return true } else { return false } } func weekViewLocation(location: CGPoint, doesBelongToDayView dayView: CVCalendarDayView) -> Bool { let dayViewFrame = dayView.frame if location.x >= dayViewFrame.origin.x && location.x <= CGRectGetMaxX(dayViewFrame) && location.y >= dayViewFrame.origin.y && location.y <= CGRectGetMaxY(dayViewFrame) { return true } else { return false } } func ownerTouchLocation(location: CGPoint, onMonthView monthView: CVCalendarMonthView) -> DayView? { var owner: DayView? let weekViews = monthView.weekViews for weekView in weekViews { for dayView in weekView.dayViews! { if self.monthViewLocation(location, doesBelongToDayView: dayView) { owner = dayView return owner } } } return owner } func ownerTouchLocation(location: CGPoint, onWeekView weekView: CVCalendarWeekView) -> DayView? { var owner: DayView? let dayViews = weekView.dayViews for dayView in dayViews { if weekViewLocation(location, doesBelongToDayView: dayView) { owner = dayView return owner } } return owner } }
mit
7eaca30d57d57b4d182eb0eef2aee132
33.746269
177
0.633942
5.711656
false
false
false
false