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
Ge3kXm/MXWB
MXWB/Classes/Me/MeVC.swift
1
2914
// // MeVC.swift // mxwb // // Created by maRk on 17/3/31. // Copyright © 2017年 maRk. All rights reserved. // import UIKit class MeVC: BaseTableVC { override func viewDidLoad() { super.viewDidLoad() if !hasLogin { visitorView?.setupViews(imageName: "visitordiscover_image_message", title: "发现一些爆炸出轨新闻~") return } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
75000d7ca7bd047efbf33d5720b97662
29.734043
136
0.650744
4.989637
false
false
false
false
jacobwhite/firefox-ios
Push/PushClient.swift
4
7130
/* 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 Alamofire import Deferred import Shared import SwiftyJSON //public struct PushRemoteError { // static let MissingNecessaryCryptoKeys: Int32 = 101 // static let InvalidURLEndpoint: Int32 = 102 // static let ExpiredURLEndpoint: Int32 = 103 // static let DataPayloadTooLarge: Int32 = 104 // static let EndpointBecameUnavailable: Int32 = 105 // static let InvalidSubscription: Int32 = 106 // static let RouterTypeIsInvalid: Int32 = 108 // static let InvalidAuthentication: Int32 = 109 // static let InvalidCryptoKeysSpecified: Int32 = 110 // static let MissingRequiredHeader: Int32 = 111 // static let InvalidTTLHeaderValue: Int32 = 112 // static let UnknownError: Int32 = 999 //} public let PushClientErrorDomain = "org.mozilla.push.error" private let PushClientUnknownError = NSError(domain: PushClientErrorDomain, code: 999, userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]) private let log = Logger.browserLogger /// Bug 1364403 – This is to be put into the push registration private let apsEnvironment: [String: Any] = [ "mutable-content": 1, "alert": [ "title": " ", "body": " " ], ] public struct PushRemoteError { let code: Int let errno: Int let error: String let message: String? public static func from(json: JSON) -> PushRemoteError? { guard let code = json["code"].int, let errno = json["errno"].int, let error = json["error"].string else { return nil } let message = json["message"].string return PushRemoteError(code: code, errno: errno, error: error, message: message) } } public enum PushClientError: MaybeErrorType { case Remote(PushRemoteError) case Local(Error) public var description: String { switch self { case let .Remote(error): let errorString = error.error let messageString = error.message ?? "" return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>" case let .Local(error): return "<FxAClientError.Local Error \"\(error.localizedDescription)\">" } } } public class PushClient { let endpointURL: NSURL let experimentalMode: Bool lazy fileprivate var alamofire: SessionManager = { let ua = UserAgent.fxaUserAgent let configuration = URLSessionConfiguration.ephemeral var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:] defaultHeaders["User-Agent"] = ua configuration.httpAdditionalHeaders = defaultHeaders return SessionManager(configuration: configuration) }() public init(endpointURL: NSURL, experimentalMode: Bool = false) { self.endpointURL = endpointURL self.experimentalMode = experimentalMode } } public extension PushClient { public func register(_ apnsToken: String) -> Deferred<Maybe<PushRegistration>> { // POST /v1/{type}/{app_id}/registration let registerURL = endpointURL.appendingPathComponent("registration")! var mutableURLRequest = URLRequest(url: registerURL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let parameters: [String: Any] if experimentalMode { parameters = [ "token": apnsToken, "aps": apsEnvironment, ] } else { parameters = ["token": apnsToken] } mutableURLRequest.httpBody = JSON(parameters).stringValue()?.utf8EncodedData if experimentalMode { log.info("curl -X POST \(registerURL.absoluteString) --data '\(JSON(parameters).stringValue()!)'") } return send(request: mutableURLRequest) >>== { json in guard let response = PushRegistration.from(json: json) else { return deferMaybe(PushClientError.Local(PushClientUnknownError)) } return deferMaybe(response) } } public func updateUAID(_ apnsToken: String, withRegistration creds: PushRegistration) -> Deferred<Maybe<PushRegistration>> { // PUT /v1/{type}/{app_id}/registration/{uaid} let registerURL = endpointURL.appendingPathComponent("registration/\(creds.uaid)")! var mutableURLRequest = URLRequest(url: registerURL) mutableURLRequest.httpMethod = HTTPMethod.put.rawValue mutableURLRequest.addValue("Bearer \(creds.secret)", forHTTPHeaderField: "Authorization") mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let parameters = ["token": apnsToken] mutableURLRequest.httpBody = JSON(parameters).stringValue()?.utf8EncodedData return send(request: mutableURLRequest) >>== { json in return deferMaybe(creds) } } public func unregister(_ creds: PushRegistration) -> Success { // DELETE /v1/{type}/{app_id}/registration/{uaid} let unregisterURL = endpointURL.appendingPathComponent("registration/\(creds.uaid)") var mutableURLRequest = URLRequest(url: unregisterURL!) mutableURLRequest.httpMethod = HTTPMethod.delete.rawValue mutableURLRequest.addValue("Bearer \(creds.secret)", forHTTPHeaderField: "Authorization") return send(request: mutableURLRequest) >>> succeed } } /// Utilities extension PushClient { fileprivate func send(request: URLRequest) -> Deferred<Maybe<JSON>> { log.info("\(request.httpMethod!) \(request.url?.absoluteString ?? "nil")") let deferred = Deferred<Maybe<JSON>>() alamofire.request(request) .validate(contentType: ["application/json"]) .responseJSON { response in // Don't cancel requests just because our client is deallocated. withExtendedLifetime(self.alamofire) { let result = response.result if let error = result.error { return deferred.fill(Maybe(failure: PushClientError.Local(error))) } guard let data = response.data else { return deferred.fill(Maybe(failure: PushClientError.Local(PushClientUnknownError))) } let json = JSON(data: data) if let remoteError = PushRemoteError.from(json: json) { return deferred.fill(Maybe(failure: PushClientError.Remote(remoteError))) } deferred.fill(Maybe(success: json)) } } return deferred } }
mpl-2.0
0e1e02c2d61080ae1b56970bcc5ba761
37.112299
128
0.633787
5.112626
false
false
false
false
moltin/ios-sdk
Sources/SDK/Models/Cart.swift
1
7139
// // Cart.swift // moltin iOS // // Created by Craig Tweedy on 26/02/2018. // import Foundation /// The meta information for a `Cart` public class CartMeta: Codable { /// The display price information for this cart public let displayPrice: DisplayPrices enum CodingKeys: String, CodingKey { case displayPrice = "display_price" } } /// The display price for a `CartItem` public struct CartItemDisplayPrice: Codable { /// The unit price for a cart item public let unit: DisplayPrice /// The value price (based on quantity) for a cart item public let value: DisplayPrice } open class CartItemPrice: Codable { /// The price for this cart item public var amount: Int /// The price for this cart item including tax public var includes_tax: Bool? /// The type of this object enum CodingKeys: String, CodingKey { case amount = "amount" case includes_tax = "includes_tax" } /// Create a new address with first name and last name public init( amount: Int, includes_tax: Bool?) { self.amount = amount self.includes_tax = includes_tax } func toDictionary() -> [String: Any] { var data: [String: Any] = [:] data["amount"] = self.amount data["includes_tax"] = self.includes_tax return data } } /// The display prices information for a `CartItem` public struct CartItemDisplayPrices: Codable { /// The display price for this cart item including tax public let withTax: CartItemDisplayPrice /// The display price for this cart item without tax public let withoutTax: CartItemDisplayPrice /// The display price for this cart item's tax amount public let tax: CartItemDisplayPrice enum CodingKeys: String, CodingKey { case withTax = "with_tax" case withoutTax = "without_tax" case tax } } /// The meta information for this `CartItem` public class CartItemMeta: Codable { /// The display price for this cart item public let displayPrice: CartItemDisplayPrices enum CodingKeys: String, CodingKey { case displayPrice = "display_price" } } /// Represents a `Cart` in Moltin open class Cart: Codable { /// The id for this cart public let id: String /// The type of this object public let type: String /// The external links for this cart public let links: [String: String]? /// The meta information for this cart public let meta: CartMeta? } /// Represents a `CartItem` in Moltin open class CartItem: Codable { /// The id for this cart item public let id: String /// The type of this object public let type: String /// The product ID for this `CartItem` public let productId: String? /// The name of this cart item public let name: String /// The description of this cart item public let description: String? /// The SKU of this cart item public let sku: String? /// The quantity of this cart item public let quantity: Int /// The price for this cart item public let unitPrice: ProductPrice /// The price for this cart item, taking into account quantity public let value: ProductPrice /// The tax for this cart item, taking into account quantity public var taxes: [TaxItem]? /// The external links for this cart item public let links: [String: String] /// The meta information for this cart item public let meta: CartItemMeta /// The relationships this item has public let relationships: Relationships? enum CodingKeys: String, CodingKey { case productId = "product_id" case unitPrice = "unit_price" case id case type case name case description case sku case quantity case value case links case meta case relationships } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let includes: IncludesContainer = decoder.userInfo[.includes] as? IncludesContainer ?? [:] self.id = try container.decode(String.self, forKey: .id) self.type = try container.decode(String.self, forKey: .type) self.productId = try? container.decode(String.self, forKey: .productId) self.name = try container.decode(String.self, forKey: .name) self.description = try container.decode(String.self, forKey: .description) self.sku = try container.decode(String.self, forKey: .sku) self.quantity = try container.decode(Int.self, forKey: .quantity) self.unitPrice = try container.decode(ProductPrice.self, forKey: .unitPrice) self.value = try container.decode(ProductPrice.self, forKey: .value) self.links = try container.decode([String: String].self, forKey: .links) self.meta = try container.decode(CartItemMeta.self, forKey: .meta) self.relationships = try? container.decode(Relationships.self, forKey: .relationships) try self.decodeRelationships(fromRelationships: self.relationships, withIncludes: includes) } } extension CartItem { func decodeRelationships( fromRelationships relationships: Relationships?, withIncludes includes: IncludesContainer ) throws { self.taxes = try self.decodeMany( fromRelationships: relationships?[keyPath: \Relationships.taxes], withIncludes: includes["tax_items"]) } } /// Represents various types of cart items public enum CartItemType: String { /// A standard cart item case cartItem = "cart_item" /// A promo item case promotionItem = "promotion_item" } /// A custom cart item open class CustomCartItem: Codable { var name: String var sku: String? var quantity: Int var description: String? var price: CartItemPrice var attributes: [String: String]? public init(withName name: String, sku: String?, quantity: Int, description: String?, price: CartItemPrice, withAttributes attributes: [String: String]? = nil) { self.name = name self.sku = sku self.quantity = quantity self.description = description self.price = price self.attributes = attributes } func toDictionary() -> [String: Any] { var cartItemData: [String: Any] = [:] if let sku = self.sku { cartItemData["sku"] = sku } if let description = self.description { cartItemData["description"] = description } cartItemData["name"] = self.name cartItemData["quantity"] = self.quantity cartItemData["price"] = self.price.toDictionary() if let attributes = self.attributes { cartItemData = attributes } return cartItemData } } /// A tax item open class TaxItem: Codable { public let type: String public let id: String public let jurisdiction: String public let code: String public let name: String public let rate: Float }
mit
101bd011744dce78fd7d56c7e22544da
29.508547
165
0.650932
4.552934
false
false
false
false
mattjgalloway/emoncms-ios
Pods/Former/Former/Cells/FormInlineDatePickerCell.swift
1
2594
// // FormInlineDatePickerCell.swift // Former-Demo // // Created by Ryo Aoyama on 8/1/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit open class FormInlineDatePickerCell: FormCell, InlineDatePickerFormableRow { // MARK: Public public private(set) weak var titleLabel: UILabel! public private(set) weak var displayLabel: UILabel! private weak var rightConst: NSLayoutConstraint! public func formTitleLabel() -> UILabel? { return titleLabel } public func formDisplayLabel() -> UILabel? { return displayLabel } open override func updateWithRowFormer(_ rowFormer: RowFormer) { super.updateWithRowFormer(rowFormer) rightConst.constant = (accessoryType == .none && accessoryView == nil) ? -15 : 0 } open override func setup() { super.setup() let titleLabel = UILabel() titleLabel.setContentHuggingPriority(500, for: .horizontal) titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(titleLabel, at: 0) self.titleLabel = titleLabel let displayLabel = UILabel() displayLabel.textColor = .lightGray displayLabel.textAlignment = .right displayLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(displayLabel, at: 0) self.displayLabel = displayLabel let constraints = [ NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[title]-0-|", options: [], metrics: nil, views: ["title": titleLabel] ), NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[display]-0-|", options: [], metrics: nil, views: ["display": displayLabel] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-15-[title]-10-[display(>=0)]", options: [], metrics: nil, views: ["title": titleLabel, "display": displayLabel] ) ].flatMap { $0 } let rightConst = NSLayoutConstraint( item: displayLabel, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: 0 ) contentView.addConstraints(constraints + [rightConst]) self.rightConst = rightConst } }
mit
1de36e9f5be485658d7bfa1136ba16f5
30.621951
88
0.581566
5.552463
false
false
false
false
proversity-org/edx-app-ios
Source/AuthenticatedWebViewController.swift
1
18716
// // AuthenticatedWebViewController.swift // edX // // Created by Akiva Leffert on 5/26/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit import WebKit class HeaderViewInsets : ContentInsetsSource { weak var insetsDelegate : ContentInsetsSourceDelegate? var view : UIView? var currentInsets : UIEdgeInsets { return UIEdgeInsets(top : view?.frame.size.height ?? 0, left : 0, bottom : 0, right : 0) } var affectsScrollIndicators : Bool { return true } } private protocol WebContentController { var view : UIView {get} var scrollView : UIScrollView {get} var isLoading: Bool {get} var alwaysRequiresOAuthUpdate : Bool { get} var initialContentState : AuthenticatedWebViewController.State { get } func loadURLRequest(request : NSURLRequest) func resetState() } @objc protocol WebViewNavigationDelegate: class { func webView(_ webView: WKWebView, shouldLoad request: URLRequest) -> Bool func webViewContainingController() -> UIViewController } // A class should implement AlwaysRequireAuthenticationOverriding protocol if it always require authentication. protocol AuthenticatedWebViewControllerRequireAuthentication { } protocol AuthenticatedWebViewControllerDelegate { func authenticatedWebViewController(authenticatedController: AuthenticatedWebViewController, didFinishLoading webview: WKWebView) } private class WKWebViewContentController : WebContentController { fileprivate let webView : WKWebView init(configuration: WKWebViewConfiguration) { self.webView = WKWebView(frame: CGRect.zero, configuration: configuration) } var view : UIView { return webView } var scrollView : UIScrollView { return webView.scrollView } func loadURLRequest(request: NSURLRequest) { // If the view initialize before registering userAgent the request goes without the required userAgent, // to solve this we are setting customeUserAgent here. if let userAgent = UserDefaults.standard.string(forKey: "UserAgent"), webView.customUserAgent?.isEmpty ?? false { webView.customUserAgent = userAgent } webView.load(request as URLRequest) } func resetState() { webView.stopLoading() webView.loadHTMLString("", baseURL: nil) } var alwaysRequiresOAuthUpdate : Bool { return false } var initialContentState : AuthenticatedWebViewController.State { return AuthenticatedWebViewController.State.LoadingContent } var isLoading: Bool { return webView.isLoading } } private let OAuthExchangePath = "/oauth2/login/" // Allows access to course content that requires authentication. // Forwarding our oauth token to the server so we can get a web based cookie public class AuthenticatedWebViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate, UIDocumentInteractionControllerDelegate { fileprivate enum State { case CreatingSession case LoadingContent case NeedingSession } public typealias Environment = OEXAnalyticsProvider & OEXConfigProvider & OEXSessionProvider & ReachabilityProvider var delegate: AuthenticatedWebViewControllerDelegate? internal let environment : Environment private let blockID: CourseBlockID private let loadController : LoadStateViewController private let insetsController : ContentInsetsController private let headerInsets : HeaderViewInsets weak var webViewDelegate: WebViewNavigationDelegate? private lazy var webController : WebContentController = { let js : String = "$(document).ready(function() {" + "$('#recap_cmd_" + self.blockID + "').click(function() {" + "window.webkit.messageHandlers.clickPDFDownload.postMessage('clickPDF')" + "});" + "});" let userScript: WKUserScript = WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false) let contentController = WKUserContentController(); contentController.addUserScript(userScript) contentController.add(self, name: "clickPDFDownload") contentController.add(self, name: "downloadPDF") let config = WKWebViewConfiguration(); config.userContentController = contentController; let controller = WKWebViewContentController(configuration: config) controller.webView.navigationDelegate = self controller.webView.uiDelegate = self return controller }() var scrollView: UIScrollView { return webController.scrollView } private var state = State.CreatingSession private var contentRequest : NSURLRequest? = nil var currentUrl: NSURL? { return contentRequest?.url as NSURL? } public func setLoadControllerState(withState state: LoadState) { loadController.state = state } public init(environment : Environment) { self.environment = environment self.blockID = "" loadController = LoadStateViewController() insetsController = ContentInsetsController() headerInsets = HeaderViewInsets() insetsController.addSource(source: headerInsets) super.init(nibName: nil, bundle: nil) automaticallyAdjustsScrollViewInsets = false webController.view.accessibilityIdentifier = "AuthenticatedWebViewController:authenticated-web-view" addObservers() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { // Prevent crash due to stale back pointer, since WKWebView's UIScrollView apparently doesn't // use weak for its delegate webController.scrollView.delegate = nil NotificationCenter.default.removeObserver(self) } override public func viewDidLoad() { super.viewDidLoad() state = webController.initialContentState view.addSubview(webController.view) webController.view.snp.makeConstraints { make in make.edges.equalTo(safeEdges) } loadController.setupInController(controller: self, contentView: webController.view) webController.view.backgroundColor = OEXStyles.shared().standardBackgroundColor() webController.scrollView.backgroundColor = OEXStyles.shared().standardBackgroundColor() insetsController.setupInController(owner: self, scrollView: webController.scrollView) if let request = contentRequest { loadRequest(request: request) } } private func addObservers() { NotificationCenter.default.oex_addObserver(observer: self, name: NOTIFICATION_DYNAMIC_TEXT_TYPE_UPDATE) { (_, observer, _) in observer.reload() } } public func reload() { guard let request = contentRequest, !webController.isLoading else { return } state = .LoadingContent loadRequest(request: request) } private func resetState() { loadController.state = .Initial state = .CreatingSession } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() if view.window == nil { webController.resetState() } resetState() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() insetsController.updateInsets() } public func showError(error : NSError?, icon : Icon? = nil, message : String? = nil) { let buttonInfo = MessageButtonInfo(title: Strings.reload) {[weak self] in if let request = self?.contentRequest, self?.environment.reachability.isReachable() ?? false { self?.loadController.state = .Initial self?.webController.loadURLRequest(request: request) } } loadController.state = LoadState.failed(error: error, icon: icon, message: message, buttonInfo: buttonInfo) refreshAccessibility() } // MARK: Header View var headerView : UIView? { get { return headerInsets.view } set { headerInsets.view?.removeFromSuperview() headerInsets.view = newValue if let headerView = newValue { webController.view.addSubview(headerView) headerView.snp.makeConstraints { make in make.top.equalTo(safeTop) make.leading.equalTo(webController.view) make.trailing.equalTo(webController.view) } webController.view.setNeedsLayout() webController.view.layoutIfNeeded() } } } private func loadOAuthRefreshRequest() { if let hostURL = environment.config.apiHostURL() { let URL = hostURL.appendingPathComponent(OAuthExchangePath) let exchangeRequest = NSMutableURLRequest(url: URL) exchangeRequest.httpMethod = HTTPMethod.POST.rawValue for (key, value) in self.environment.session.authorizationHeaders { exchangeRequest.addValue(value, forHTTPHeaderField: key) } self.webController.loadURLRequest(request: exchangeRequest) } } private func refreshAccessibility() { DispatchQueue.main.async { UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil) } } // MARK: Request Loading public func loadRequest(request : NSURLRequest) { contentRequest = request loadController.state = .Initial state = webController.initialContentState let isAuthRequestRequire = ((parent as? AuthenticatedWebViewControllerRequireAuthentication) != nil) ? true: webController.alwaysRequiresOAuthUpdate if isAuthRequestRequire { self.state = State.CreatingSession loadOAuthRefreshRequest() } else { webController.loadURLRequest(request: request) } } // MARK: WKWebView delegate public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { switch navigationAction.navigationType { case .linkActivated: if let URL = navigationAction.request.url, webViewDelegate?.webView(webView, shouldLoad: navigationAction.request) ?? true { if (self.environment.config.openLinksInsideAppEnabled) { let urlString = URL.absoluteString let apiHostUrlString = self.environment.config.apiHostURL()!.absoluteString if ((urlString.range(of: apiHostUrlString)) != nil) { return decisionHandler(.allow) } } UIApplication.shared.openURL(URL) } decisionHandler(.cancel) case .formSubmitted, .formResubmitted: if let URL = navigationAction.request.url, webViewDelegate?.webView(webView, shouldLoad: navigationAction.request) ?? true { UIApplication.shared.openURL(URL) } decisionHandler(.cancel) default: decisionHandler(.allow) } } public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { if let httpResponse = navigationResponse.response as? HTTPURLResponse, let statusCode = OEXHTTPStatusCode(rawValue: httpResponse.statusCode), let errorGroup = statusCode.errorGroup, state == .LoadingContent { switch errorGroup { case HttpErrorGroup.http4xx: state = .NeedingSession break case HttpErrorGroup.http5xx: loadController.state = LoadState.failed() decisionHandler(.cancel) return } } decisionHandler(.allow) } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { switch state { case .CreatingSession: if let request = contentRequest { state = .LoadingContent webController.loadURLRequest(request: request) } else { loadController.state = LoadState.failed() } case .LoadingContent: //The class which will implement this protocol method will be responsible to set the loadController state as Loaded if delegate?.authenticatedWebViewController(authenticatedController: self, didFinishLoading: webView) == nil { loadController.state = .Loaded } case .NeedingSession: state = .CreatingSession loadOAuthRefreshRequest() } refreshAccessibility() } public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { showError(error: error as NSError?) } public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { showError(error: error as NSError?) } public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // Don't use basic auth on exchange endpoint. That is explicitly non protected // and it screws up the authorization headers if let URL = webView.url, ((URL.absoluteString.hasSuffix(OAuthExchangePath)) != false) { completionHandler(.performDefaultHandling, nil) } else if let credential = environment.config.URLCredentialForHost(challenge.protectionSpace.host as NSString) { completionHandler(.useCredential, credential) } else { completionHandler(.performDefaultHandling, nil) } } public init(environment : Environment, blockID: String) { self.environment = environment self.blockID = blockID loadController = LoadStateViewController() insetsController = ContentInsetsController() headerInsets = HeaderViewInsets() insetsController.addSource(source: headerInsets) super.init(nibName: nil, bundle: nil) automaticallyAdjustsScrollViewInsets = false webController.view.accessibilityIdentifier = "AuthenticatedWebViewController:authenticated-web-view" } public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if(message.name == "clickPDFDownload") { generatePdf() } else if (message.name == "downloadPDF") { showPdf(pdf: message.body as AnyObject); } } public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { return self } public func generatePdf() { let pdfJS : String = "var pdf_element = document.getElementById('recap_answers_" + blockID + "').innerHTML;" + "html2pdf(pdf_element, {" + "margin: [0.8, 1, 0.5, 1]," + "filename: 'PDF.pdf'," + "image: { type: 'jpeg',quality: 0.98 }," + "html2canvas: { dpi: 192, letterRendering: true }," + "jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }" + "}, function(pdf) {" + "window.webkit.messageHandlers.downloadPDF.postMessage(pdf.output('datauristring'));" + "});"; let webView = webController.view as! WKWebView webView.evaluateJavaScript(pdfJS, completionHandler: { (result, error) -> Void in print(result ?? "") print(error ?? "") }) } public func showPdf(pdf: AnyObject) { let url = NSURL(string: pdf as! String) let request = NSURLRequest(url: url! as URL) let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.downloadTask(with: request as URLRequest, completionHandler: { (location, response, error) in let fileManager = FileManager.default let documents = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let fileURL = documents.appendingPathComponent("PDF.pdf") let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String let url = NSURL(fileURLWithPath: path) let filePath = url.appendingPathComponent("PDF.pdf")!.path if fileManager.fileExists(atPath: filePath) { do { try fileManager.removeItem(atPath: filePath) } catch { print(error) } } do { let backgroundQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default) try fileManager.moveItem(at: location!, to: fileURL) backgroundQueue.async(execute: { let documentController = UIDocumentInteractionController.init(url: fileURL) documentController.delegate = self DispatchQueue.main.async(execute: { () -> Void in documentController.presentPreview(animated: true) }) }) } catch { print(error) } }) task.resume() } // public func webView(webView: WKWebView!, createWebViewWithConfiguration configuration: WKWebViewConfiguration!, forNavigationAction navigationAction: WKNavigationAction!, windowFeatures: WKWindowFeatures!) -> WKWebView! { // if navigationAction.targetFrame == nil { // webView.loadRequest(navigationAction.request) // } // return nil // } }
apache-2.0
86d98d8c11b85056e4d38070a6d1bb78
38.319328
231
0.639239
5.776543
false
false
false
false
dvor/Antidote
Antidote/ChatPrivateTitleView.swift
2
2903
// 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 UIKit import SnapKit private struct Constants { static let StatusViewLeftOffset: CGFloat = 5.0 static let StatusViewSize: CGFloat = 10.0 } class ChatPrivateTitleView: UIView { var name: String { get { return nameLabel.text ?? "" } set { nameLabel.text = newValue updateFrame() } } var userStatus: UserStatus { get { return statusView.userStatus } set { statusView.userStatus = newValue statusLabel.text = newValue.toString() updateFrame() } } fileprivate var nameLabel: UILabel! fileprivate var statusView: UserStatusView! fileprivate var statusLabel: UILabel! init(theme: Theme) { super.init(frame: CGRect.zero) backgroundColor = .clear createViews(theme) } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private extension ChatPrivateTitleView { func createViews(_ theme: Theme) { nameLabel = UILabel() nameLabel.textAlignment = .center nameLabel.textColor = theme.colorForType(.NormalText) nameLabel.font = UIFont.antidoteFontWithSize(16.0, weight: .bold) addSubview(nameLabel) statusView = UserStatusView() statusView.showExternalCircle = false statusView.theme = theme addSubview(statusView) statusLabel = UILabel() statusLabel.textAlignment = .center statusLabel.textColor = theme.colorForType(.NormalText) statusLabel.font = UIFont.antidoteFontWithSize(12.0, weight: .light) addSubview(statusLabel) nameLabel.snp.makeConstraints { $0.top.equalTo(self) $0.leading.equalTo(self) } statusView.snp.makeConstraints { $0.centerY.equalTo(nameLabel) $0.leading.equalTo(nameLabel.snp.trailing).offset(Constants.StatusViewLeftOffset) $0.trailing.equalTo(self) $0.size.equalTo(Constants.StatusViewSize) } statusLabel.snp.makeConstraints { $0.top.equalTo(nameLabel.snp.bottom) $0.leading.equalTo(nameLabel) $0.trailing.equalTo(nameLabel) $0.bottom.equalTo(self) } } func updateFrame() { nameLabel.sizeToFit() statusLabel.sizeToFit() frame.size.width = max(nameLabel.frame.size.width, statusLabel.frame.size.width) + Constants.StatusViewLeftOffset + Constants.StatusViewSize frame.size.height = nameLabel.frame.size.height + statusLabel.frame.size.height } }
mit
ccc3dc86b8f9223dde0b5835311064e0
28.03
148
0.631071
4.674718
false
false
false
false
IvanVorobei/RateApp
SPRateApp - project/SPRateApp/sparrow/ui-elements/bezier-paths/icons/SPBezierPathFigureDraw.swift
1
5776
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class SPBezierPathFigureDraw : NSObject { //// Drawing Methods public dynamic class func drawFillChecked(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 26, height: 26), resizing: ResizingBehavior = .aspectFit, fillColor: UIColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 26, height: 26), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 26, y: resizedFrame.height / 26) //// Color Declarations let fillColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 12.89, y: 1)) bezierPath.addCurve(to: CGPoint(x: 1, y: 13.09), controlPoint1: CGPoint(x: 6.33, y: 1), controlPoint2: CGPoint(x: 1, y: 6.43)) bezierPath.addCurve(to: CGPoint(x: 12.89, y: 25.19), controlPoint1: CGPoint(x: 1, y: 19.76), controlPoint2: CGPoint(x: 6.33, y: 25.19)) bezierPath.addCurve(to: CGPoint(x: 24.77, y: 13.09), controlPoint1: CGPoint(x: 19.44, y: 25.19), controlPoint2: CGPoint(x: 24.77, y: 19.76)) bezierPath.addCurve(to: CGPoint(x: 12.89, y: 1), controlPoint1: CGPoint(x: 24.77, y: 6.43), controlPoint2: CGPoint(x: 19.44, y: 1)) bezierPath.close() bezierPath.move(to: CGPoint(x: 18.55, y: 9.98)) bezierPath.addLine(to: CGPoint(x: 12.3, y: 17.14)) bezierPath.addCurve(to: CGPoint(x: 11.71, y: 17.4), controlPoint1: CGPoint(x: 12.14, y: 17.31), controlPoint2: CGPoint(x: 11.93, y: 17.4)) bezierPath.addCurve(to: CGPoint(x: 11.22, y: 17.23), controlPoint1: CGPoint(x: 11.54, y: 17.4), controlPoint2: CGPoint(x: 11.37, y: 17.35)) bezierPath.addLine(to: CGPoint(x: 7.32, y: 14.05)) bezierPath.addCurve(to: CGPoint(x: 7.2, y: 12.93), controlPoint1: CGPoint(x: 6.98, y: 13.78), controlPoint2: CGPoint(x: 6.93, y: 13.28)) bezierPath.addCurve(to: CGPoint(x: 8.3, y: 12.81), controlPoint1: CGPoint(x: 7.47, y: 12.59), controlPoint2: CGPoint(x: 7.96, y: 12.54)) bezierPath.addLine(to: CGPoint(x: 11.62, y: 15.52)) bezierPath.addLine(to: CGPoint(x: 17.38, y: 8.93)) bezierPath.addCurve(to: CGPoint(x: 18.48, y: 8.86), controlPoint1: CGPoint(x: 17.67, y: 8.6), controlPoint2: CGPoint(x: 18.16, y: 8.57)) bezierPath.addCurve(to: CGPoint(x: 18.55, y: 9.98), controlPoint1: CGPoint(x: 18.8, y: 9.15), controlPoint2: CGPoint(x: 18.83, y: 9.66)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc(SPBezierPathIconsDrawResizingBehavior) public enum ResizingBehavior: Int { case aspectFit /// The content is proportionally resized to fit into the target rectangle. case aspectFill /// The content is proportionally resized to completely fill the target rectangle. case stretch /// The content is stretched to match the entire target rectangle. case center /// The content is centered in the target rectangle, but it is NOT resized. public func apply(rect: CGRect, target: CGRect) -> CGRect { if rect == target || target == CGRect.zero { return rect } var scales = CGSize.zero scales.width = abs(target.width / rect.width) scales.height = abs(target.height / rect.height) switch self { case .aspectFit: scales.width = min(scales.width, scales.height) scales.height = scales.width case .aspectFill: scales.width = max(scales.width, scales.height) scales.height = scales.width case .stretch: break case .center: scales.width = 1 scales.height = 1 } var result = rect.standardized result.size.width *= scales.width result.size.height *= scales.height result.origin.x = target.minX + (target.width - result.width) / 2 result.origin.y = target.minY + (target.height - result.height) / 2 return result } } }
mit
312b949471e59af8351985d4c1868ded
52.971963
242
0.635844
3.870643
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/struct-extradata-field_offsets-trailing_flags.swift
3
3151
// RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: [[EXTRA_DATA_PATTERN:@[0-9]+]] = internal constant { // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // : , [4 x i8], // CHECK-SAME: i64 // CHECK-SAME: } { // CHECK-SAME: i32 0, // CHECK-SAME: i32 8, // CHECK-SAME: i32 16, // : [4 x i8] zeroinitializer, // CHECK-SAME: i64 0 // CHECK-SAME: }, align [[ALIGNMENT]] // CHECK: @"$s4main4PairVMP" = internal constant <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16 // : }> <{ // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.type* ( // : %swift.type_descriptor*, // : i8**, // : i8* // : )* @"$s4main4PairVMi" to i64 // : ), // : i64 ptrtoint ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>* // : @"$s4main4PairVMP" to i64 // : ) // : ) to i32 // : ), // : i32 0, // : i32 1073741827, // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.vwtable* @"$s4main4PairVWV" to i64 // : ), // : i64 ptrtoint ( // : i32* getelementptr inbounds ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>, // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // : i32 0, // : i32 3 // : ) to i64 // : ) // : ) to i32 // : ), // : i32 trunc ( // CHECK-SAME: [[INT]] sub ( // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: { // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // : [4 x i8], // CHECK-SAME: i64 // CHECK-SAME: }* [[EXTRA_DATA_PATTERN]] to [[INT]] // CHECK-SAME: ), // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: i32* getelementptr inbounds ( // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>, // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // CHECK-SAME: i32 0, // CHECK-SAME: i32 4 // CHECK-SAME: ) to [[INT]] // CHECK-SAME: ) // CHECK-SAME: ) // : ), // : i16 3, // : i16 3 // : }>, align 8 struct Pair<First, Second, Third> { let first: Int64 let second: Int64 let third: Int64 }
apache-2.0
be8bbcbb5ce20d0412a26154bafbdd02
33.25
173
0.388765
2.947615
false
false
false
false
openHPI/xikolo-ios
Binge/UIImage+crop.swift
1
1177
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import UIKit extension UIImage { func cropped(to targetSize: CGSize) -> UIImage { // Determine the scale factor that preserves aspect ratio let widthRatio = targetSize.width / self.size.width let heightRatio = targetSize.height / self.size.height let scaleFactor = max(widthRatio, heightRatio) // Compute the new image size that preserves aspect ratio let scaledImageSize = CGSize( width: self.size.width * scaleFactor, height: self.size.height * scaleFactor ) let offset = CGPoint( x: (scaledImageSize.width - targetSize.width) / 2 * -1, y: (scaledImageSize.height - targetSize.height) / 2 * -1 ) // Draw and return the resized UIImage let renderer = UIGraphicsImageRenderer( size: targetSize ) let scaledImage = renderer.image { _ in self.draw(in: CGRect( origin: offset, size: scaledImageSize )) } return scaledImage } }
gpl-3.0
2752f908d7de1a6d51da4052e5107d9a
26.348837
68
0.589286
4.839506
false
false
false
false
felipedemetrius/WatchMe
WatchMe/EpisodeRepository.swift
1
1659
// // EpisodeRepository.swift // WatchMe // // Created by Felipe Silva on 1/21/17. // Copyright © 2017 Felipe Silva . All rights reserved. // import SwiftyJSON import ObjectMapper import AlamofireObjectMapper import Alamofire import RealmSwift import ObjectMapper_Realm class EpisodeRepository{ class func getNextEpisode(slug: String, encoding: ParameterEncoding = URLEncoding.queryString, completionHandler: @escaping (EpisodeModel?) -> ()){ let url = TraktUrl.Shows.description + slug + "/" + TraktUrl.NextEpisode.rawValue Alamofire.request(url, method: .get, parameters: nil, encoding: encoding, headers: TraktCredentials.header).responseObject { (response: DataResponse<EpisodeModel>) in completionHandler(response.result.value) } } class func getEpisodeDetail(slug: String, season: Int, episode: Int, completionHandler: @escaping (EpisodeModel?) -> ()){ let url = TraktUrl.Shows.description + slug + "/" + TraktUrl.Seasons.rawValue + season.description + "/" + TraktUrl.Episodes.rawValue + episode.description + TraktUrl.Full.rawValue Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.queryString, headers: TraktCredentials.header).responseObject { (response: DataResponse<EpisodeModel>) in completionHandler(response.result.value) } } class func getLocal(tvdb : Int) -> EpisodeModel? { guard let realm = Realm.safe() else {return nil} return realm.objects(EpisodeModel.self).filter("tvdb == \(tvdb)").first } }
mit
397cfe3f92cbe25d42a0d52aae7368e3
35.844444
189
0.673703
4.819767
false
false
false
false
codeOfRobin/Components-Personal
Sources/SingleSelectViewController.swift
1
3155
// // SingleSelectViewController.swift // SearchableComponent // // Created by Robin Malhotra on 30/08/17. // Copyright © 2017 Robin Malhotra. All rights reserved. // import AsyncDisplayKit import RxSwift public class SingleSelectViewController<ViewModel: Equatable>: UIViewController, ASTableDelegate { let tableNode = ASTableNode() let dataSource: DiffableDataSourceAdapter<ViewModel> let onSelecting: (ViewModel) -> () let disposeBag = DisposeBag() public init(dataSource: DiffableDataSourceAdapter<ViewModel>, title: String, onSelecting: @escaping (ViewModel) -> ()) { self.dataSource = dataSource self.onSelecting = onSelecting super.init(nibName: nil, bundle: nil) self.title = title } public init(dataObservable: Observable<[ViewModel]> , title: String, onSelecting: @escaping (ViewModel) -> (), nodeClosure: @escaping (ViewModel) -> ASCellNode) { self.dataSource = DiffableDataSourceAdapter<ViewModel>.init(dataObservable: dataObservable, nodeClosure: nodeClosure) self.onSelecting = onSelecting super.init(nibName: nil, bundle: nil) self.title = title } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() dataSource.tableNode = tableNode tableNode.dataSource = dataSource dataSource.tableNode = tableNode tableNode.delegate = self tableNode.view.tableFooterView = UIView() self.view.addSubnode(tableNode) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: FrameworkImage.close, style: .plain, target: self, action: #selector(closeButtonPressed)) // Do any additional setup after loading the view. } @objc func closeButtonPressed() { self.dismiss(animated: true, completion: nil) } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableNode.frame = self.view.frame } public func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) { // really bad code smell. See if Swift 4 can fix this let node = tableNode.nodeForRow(at: indexPath)?.subnodes.first as? StatusCellNode let statusVM = dataSource.dataVariable.value[indexPath.row] as? StatusViewModel node?.statusNode.backgroundColor = statusVM?.color tableNode.deselectRow(at: indexPath, animated: true) let viewModel = dataSource.dataVariable.value[indexPath.row] onSelecting(viewModel) self.dismiss(animated: true, completion: nil) } //MARK: Hack for status nodes public func tableNode(_ tableNode: ASTableNode, didHighlightRowAt indexPath: IndexPath) { let node = tableNode.nodeForRow(at: indexPath)?.subnodes.first as? StatusCellNode let statusVM = dataSource.dataVariable.value[indexPath.row] as? StatusViewModel node?.statusNode.backgroundColor = statusVM?.color } public func tableNode(_ tableNode: ASTableNode, didUnhighlightRowAt indexPath: IndexPath) { let node = tableNode.nodeForRow(at: indexPath)?.subnodes.first as? StatusCellNode let statusVM = dataSource.dataVariable.value[indexPath.row] as? StatusViewModel node?.statusNode.backgroundColor = statusVM?.color } }
mit
2e307236d6bcf6bed0f8746f3347b3f3
35.252874
163
0.760938
4.222222
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornKit/Models/Crew.swift
1
2917
import Foundation import ObjectMapper /** Struct for managing crew objects. */ public struct Crew: Person, Equatable { /// Name of the person. public let name: String /// Their job on set. public let job: String /// The group they were part of. public var roleType: Role /// Imdb id of the person. public let imdbId: String /// TMDB id of the person. public let tmdbId: Int /// If headshot image is available, it is returned with size 1000*1500. public var largeImage: String? /// If headshot image is available, it is returned with size 600*900. public var mediumImage: String? { return largeImage?.replacingOccurrences(of: "original", with: "w500") } /// If headshot image is available, it is returned with size 300*450. public var smallImage: String? { return largeImage?.replacingOccurrences(of: "original", with: "w300") } public init?(map: Map) { do { self = try Crew(map) } catch { return nil } } private init(_ map: Map) throws { self.name = try map.value("person.name") self.job = (try? map.value("job")) ?? "" self.largeImage = try? map.value("person.images.headshot.full") self.imdbId = try map.value("person.ids.imdb") self.tmdbId = try map.value("person.ids.tmdb") self.roleType = (try? map.value("roleType")) ?? .unknown // Will only not be `nil` if object is mapped from JSON array, otherwise this is set in `TraktManager` object. } public init(name: String = "Unknown", imdbId: String = "nm0000000", tmdbId: Int = 0000000, largeImage: String? = nil) { self.name = name self.job = "" self.largeImage = largeImage self.imdbId = imdbId self.tmdbId = tmdbId self.roleType = .unknown } public mutating func mapping(map: Map) { switch map.mappingType { case .fromJSON: if let crew = Crew(map: map) { self = crew } case .toJSON: roleType >>> map["roleType"] imdbId >>> map["person.ids.imdb"] tmdbId >>> map["person.ids.tmdb"] largeImage >>> map["person.images.headshot.full"] job >>> map["job"] name >>> map["person.name"] } } } // MARK: - Hashable extension Crew: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(imdbId.hashValue) } } // MARK: Equatable public func ==(rhs: Crew, lhs: Crew) -> Bool { return rhs.imdbId == lhs.imdbId } public enum Role: String { case artist = "art" case cameraman = "camera" case designer = "costume & make-up" case director = "directing" case other = "crew" case producer = "production" case soundEngineer = "sound" case writer = "writing" case unknown = "unknown" }
gpl-3.0
7a07848aed0dcccf179c3f4bcee1baf8
28.464646
175
0.592047
3.952575
false
false
false
false
lvsti/Ilion
Ilion/Ilion.swift
1
6582
// // Ilion.swift // Ilion // // Created by Tamas Lustyik on 2017. 03. 15.. // Copyright © 2017. Tamas Lustyik. All rights reserved. // import Foundation public protocol IlionDelegate: AnyObject { func ilionDidTerminate(_ sender: Ilion) } @objc public final class Ilion: NSObject { fileprivate var browserWindowController: BrowserWindowController? = nil fileprivate var editPanelController: EditPanelController? = nil fileprivate var toolsPanelController: ToolsPanelController? = nil fileprivate var exportFlow: ExportUIFlow? = nil private var observer: NSObjectProtocol? = nil public weak var delegate: IlionDelegate? = nil @objc public static let shared = Ilion() private override init() { super.init() let notifName = Notification.Name(rawValue: "IlionDidRegisterBundle") observer = NotificationCenter.default.addObserver(forName: notifName, object: nil, queue: nil) { [weak self] _ in self?.browserWindowController?.configure(with: StringsManager.defaultManager.db) } } @objc public func start() { if browserWindowController == nil { browserWindowController = BrowserWindowController() browserWindowController?.delegate = self _ = browserWindowController?.window browserWindowController?.configure(with: StringsManager.defaultManager.db) } browserWindowController?.window?.makeKeyAndOrderFront(self) setUpExportFlow() } private func setUpExportFlow() { exportFlow = ExportUIFlow() exportFlow?.onExportStarted = { [weak exportFlow] in guard let flow = exportFlow else { return } do { try StringsManager.defaultManager.exportOverrides(to: flow.destinationURL) flow.reportExportResult(success: true) } catch { flow.reportExportResult(success: false) } } exportFlow?.onExportFinished = { [weak exportFlow] in guard let flow = exportFlow else { return } NSWorkspace.shared.activateFileViewerSelecting([flow.destinationURL]) } } } extension Ilion: BrowserWindowControllerDelegate { func browserWindow(_ sender: BrowserWindowController, willStartEditingEntryFor keyPath: LocKeyPath) { guard editPanelController == nil else { return } editPanelController = EditPanelController() editPanelController?.configure(with: StringsManager.defaultManager.entry(for: keyPath)!, keyPath: keyPath) editPanelController?.delegate = self browserWindowController?.window?.beginSheet(editPanelController!.window!) } func browserWindow(_ sender: BrowserWindowController, didRemoveOverrideFor keyPath: LocKeyPath) { StringsManager.defaultManager.removeOverride(for: keyPath) sender.configure(with: StringsManager.defaultManager.db) } func browserWindowDidResetOverrides(_ sender: BrowserWindowController) { StringsManager.defaultManager.removeAllOverrides() sender.configure(with: StringsManager.defaultManager.db) } func browserWindowDidExportOverrides(_ sender: BrowserWindowController) { guard !exportFlow!.isActive else { return } exportFlow?.start(with: sender.window!) } func browserWindowDidInvokeTools(_ sender: BrowserWindowController) { guard toolsPanelController == nil else { return } toolsPanelController = ToolsPanelController() toolsPanelController?.shouldInsertStartEndMarkers = StringsManager.defaultManager.insertsStartEndMarkers toolsPanelController?.shouldTransformCharacters = StringsManager.defaultManager.transformsCharacters if let factor = StringsManager.defaultManager.expansionFactor { toolsPanelController?.shouldSimulateExpansion = true toolsPanelController?.expansionFactor = factor } else { toolsPanelController?.shouldSimulateExpansion = false } toolsPanelController?.delegate = self browserWindowController?.window?.beginSheet(toolsPanelController!.window!) } func browserWindowWillClose(_ sender: BrowserWindowController) { browserWindowController = nil delegate?.ilionDidTerminate(self) } } extension Ilion: EditPanelControllerDelegate { func editPanelController(_ sender: EditPanelController, validateOverride override: Translation, for keyPath: LocKeyPath) throws { guard let entry = StringsManager.defaultManager.entry(for: keyPath) else { throw OverrideError.invalidKeyPath } try StringsManager.defaultManager.validateOverride(override, for: entry.translation) } func editPanelController(_ sender: EditPanelController, didCancelOverrideFor keyPath: LocKeyPath) { browserWindowController?.window?.endSheet(sender.window!) editPanelController = nil } func editPanelController(_ sender: EditPanelController, didCommitOverride override: Translation, for keyPath: LocKeyPath) { browserWindowController?.window?.endSheet(sender.window!) editPanelController = nil try! StringsManager.defaultManager.addOverride(override, for: keyPath) browserWindowController?.configure(with: StringsManager.defaultManager.db) } } extension Ilion: ToolsPanelControllerDelegate { func toolsPanelControllerDidClose(_ sender: ToolsPanelController) { let markersFlag = toolsPanelController!.shouldInsertStartEndMarkers let transformFlag = toolsPanelController!.shouldTransformCharacters let expansionFlag = toolsPanelController!.shouldSimulateExpansion let factor = toolsPanelController!.expansionFactor browserWindowController?.window?.endSheet(sender.window!) toolsPanelController = nil StringsManager.defaultManager.insertsStartEndMarkers = markersFlag StringsManager.defaultManager.transformsCharacters = transformFlag StringsManager.defaultManager.expansionFactor = expansionFlag ? factor : nil } }
mit
aa3f89ccfb63872f804700786d543d5c
36.180791
121
0.668743
6.150467
false
false
false
false
Kushki/kushki-ios
Kushki/Classes/Struct/Transfer.swift
2
758
public struct Transfer { let amount: Amount let callbackUrl: String let userType: String let documentType: String let documentNumber: String let email: String let currency: String let paymentDescription: String public init(amount: Amount, callbackUrl: String, userType: String, documentType: String, documentNumber: String, email: String,currency :String , paymentDescription:String = "" ) { self.amount = amount self.callbackUrl = callbackUrl self.userType = userType self.documentType = documentType self.documentNumber = documentNumber self.email = email self.currency = currency self.paymentDescription = paymentDescription } }
mit
96a207a7e2e6c2c7a13da722597b90c3
31.956522
107
0.672823
5.227586
false
false
false
false
fluidsonic/JetPack
Sources/UI/z_ImageView+UrlSource.swift
1
16012
// File name prefixed with z_ to avoid compiler crash related to type extensions, nested types and order of Swift source files. import ImageIO import UIKit public extension ImageView { struct UrlSource: ImageView.Source, Equatable { fileprivate var url: URL public var cacheDuration: TimeInterval? public var considersOptimalImageSize = true public var isTemplate: Bool public var placeholder: UIImage? public var urlRequest: URLRequest { didSet { guard let url = urlRequest.url else { preconditionFailure("urlRequest.url must not be nil") } self.url = url } } public init(url: URL, isTemplate: Bool = false, placeholder: UIImage? = nil, cacheDuration: TimeInterval? = nil) { self.init(urlRequest: URLRequest(url: url), isTemplate: isTemplate, placeholder: placeholder, cacheDuration: cacheDuration) } public init(urlRequest: URLRequest, isTemplate: Bool = false, placeholder: UIImage? = nil, cacheDuration: TimeInterval? = nil) { guard let url = urlRequest.url else { preconditionFailure("urlRequest.url must not be nil") } self.cacheDuration = cacheDuration self.isTemplate = isTemplate self.placeholder = placeholder self.url = url self.urlRequest = urlRequest } public static func cachedImage(for url: URL) -> UIImage? { return ImageCache.sharedInstance.image(for: url as NSURL) } public func createSession() -> ImageView.Session? { return UrlSourceSession(source: self) } public static func preload(url: URL, cacheDuration: TimeInterval? = nil) -> Closure { assert(queue: .main) return preload(urlRequest: URLRequest(url: url)) } public static func preload(urlRequest: URLRequest, cacheDuration: TimeInterval? = nil) -> Closure { assert(queue: .main) guard urlRequest.url != nil else { preconditionFailure("urlRequest.url must not be nil") } return ImageDownloadCoordinator.sharedInstance.download(request: urlRequest, cacheDuration: cacheDuration) { _ in } } public static func == (a: ImageView.UrlSource, b: ImageView.UrlSource) -> Bool { return a.urlRequest == b.urlRequest && a.isTemplate == b.isTemplate } } } private final class UrlSourceSession: ImageView.Session { private var stopLoading: Closure? let source: ImageView.UrlSource init(source: ImageView.UrlSource) { self.source = source } func imageViewDidChangeConfiguration(_ imageView: ImageView) { // ignore } func startRetrievingImageForImageView(_ imageView: ImageView, listener: ImageView.SessionListener) { precondition(stopLoading == nil) var isLoadingImage = true func completion(image sourceImage: UIImage) { isLoadingImage = false var image = sourceImage if self.source.isTemplate { image = image.withRenderingMode(.alwaysTemplate) } listener.sessionDidRetrieveImage(image) } if source.url.isFileURL && source.considersOptimalImageSize { let optimalImageSize = imageView.optimalImageSize.scale(by: imageView.optimalImageScale) stopLoading = ImageFileLoader.forURL(source.url, size: max(optimalImageSize.width, optimalImageSize.height)) .load(completion: completion) } else { stopLoading = ImageDownloadCoordinator.sharedInstance.download( request: source.urlRequest, cacheDuration: source.cacheDuration, completion: completion ) } if isLoadingImage, let placeholder = source.placeholder { listener.sessionDidRetrieveImage(placeholder) } } func stopRetrievingImage() { guard let stopLoading = stopLoading else { return } self.stopLoading = nil stopLoading() } } private final class ImageCache { private let cache = NSCache<AnyObject, UIImage>() private init() {} private func cost(for image: UIImage) -> Int { guard let cgImage = image.cgImage else { return 0 } // TODO does cgImage.height include the scale? return cgImage.bytesPerRow * cgImage.height } func image(for key: AnyObject) -> UIImage? { return cache.object(forKey: key) } func set(image: UIImage, for key: AnyObject) { cache.setObject(image, forKey: key, cost: cost(for: image)) } static let sharedInstance = ImageCache() } private final class ImageDownloadCoordinator: NSObject { typealias Completion = (UIImage) -> Void static let sharedInstance = ImageDownloadCoordinator() private let backgroundQueue = DispatchQueue.global(qos: .utility) private var downloadersByURL = [URL : Downloader]() private var downloadersByTaskId = [Int : Downloader]() private lazy var urlSession = URLSession( configuration: URLSession.shared.configuration, delegate: self, // memory leak is fine, we're a shared instance with indefinite lifetime delegateQueue: OperationQueue.main ) private override init() { assert(queue: .main) super.init() } func download(request: URLRequest, cacheDuration: TimeInterval?, completion: @escaping Completion) -> CancelClosure { assert(queue: .main) guard let url = request.url else { fatalError("Cannot handle URLRequest without url") } let downloader = getOrCreateDownloader(for: url) guard let (taskId, cancel) = downloader.download(session: urlSession, request: request, cacheDuration: cacheDuration, completion: completion) else { downloadersByURL[url] = nil return {} } downloadersByTaskId[taskId] = downloader return cancel } private func getOrCreateDownloader(for url: URL) -> Downloader { assert(queue: .main) if let downloader = downloadersByURL[url] { return downloader } let downloader = Downloader(url: url, backgroundQueue: backgroundQueue) downloadersByURL[url] = downloader return downloader } private final class Downloader { private let backgroundQueue: DispatchQueue private var cacheDuration: TimeInterval? private var completions = [Int : Completion]() private var data = Data() private var image: UIImage? private var nextRequestId = 0 private var task: URLSessionDataTask? let url: URL init(url: URL, backgroundQueue: DispatchQueue) { self.backgroundQueue = backgroundQueue self.url = url } private func cancelCompletion(requestId: Int) { assert(queue: .main) completions[requestId] = nil if completions.isEmpty { onMainQueue { // wait one cycle. maybe someone canceled just to retry immediately if self.completions.isEmpty { self.cancelDownload() } } } } private func cancelDownload() { assert(queue: .main) precondition(completions.isEmpty) self.data.removeAll() task?.cancel() task = nil } func download( session: URLSession, request: URLRequest, cacheDuration: TimeInterval?, completion: @escaping Completion ) -> (Int, CancelClosure)? { assert(queue: .main) if let image = image { completion(image) return nil } if let image = ImageCache.sharedInstance.image(for: url as NSURL) { self.image = image runAllCompletions() cancelDownload() completion(image) return nil } let requestId = nextRequestId nextRequestId += 1 completions[requestId] = completion let taskId = startDownload(session: session, cacheDuration: cacheDuration, request: request) return (taskId, { assert(queue: .main) self.cancelCompletion(requestId: requestId) }) } private func runAllCompletions() { assert(queue: .main) guard let image = image else { fatalError("Cannot run completions unless an image was successfully loaded") } // careful: a completion might get removed while we're calling another one so don't copy the dictionary while let (id, completion) = self.completions.first { self.completions.removeValue(forKey: id) completion(image) } } private func startDownload(session: URLSession, cacheDuration: TimeInterval?, request: URLRequest) -> Int { assert(queue: .main) precondition(image == nil) precondition(!completions.isEmpty) if let task = self.task { return task.taskIdentifier } self.cacheDuration = cacheDuration self.data.removeAll() let task = session.dataTask(with: request) self.task = task task.resume() return task.taskIdentifier } func task(_ task: URLSessionTask, didReceive data: Data) { assert(queue: .main) guard task.taskIdentifier == self.task?.taskIdentifier else { return } self.data.append(data) } func task(_ task: URLSessionTask, didCompleteWith error: Error?, downloaderDidFinish: @escaping Closure) { assert(queue: .main) guard task.taskIdentifier == self.task?.taskIdentifier else { return } let data = self.data self.data.removeAll() guard let url = task.originalRequest?.url else { fatalError("Cannot get original URL from task: \(task)") } if let error = error { // TODO retry, handle 4xx, etc. self.task = nil log("Cannot load image from '\(url)': \(error)\n\tresponse: \(task.response.map { String(describing: $0) } ?? "nil")") return } let cacheDuration = self.cacheDuration backgroundQueue.async { guard let image = UIImage(data: data) else { onMainQueue { self.task = nil log("Cannot load image from '\(url)': received data is not an image decodable by UIImage(data:)") } return } if cacheDuration != nil, let currentRequest = task.currentRequest, let originalRequest = task.originalRequest, currentRequest != originalRequest { let cache = URLCache.shared if let cachedResponse = cache.cachedResponse(for: currentRequest) { cache.storeCachedResponse(cachedResponse, for: originalRequest) } } image.inflate() // TODO does UIImage(data:) already inflate the image? onMainQueue { self.image = image self.task = nil ImageCache.sharedInstance.set(image: image, for: url as NSURL) self.runAllCompletions() downloaderDidFinish() } } } func task(_ task: URLSessionTask, willCache proposedResponse: CachedURLResponse) -> CachedURLResponse { assert(queue: .main) guard let cacheDuration = cacheDuration, let response = proposedResponse.response as? HTTPURLResponse, var headerFields = response.allHeaderFields as? [String : String], let url = response.url else { return proposedResponse } headerFields = headerFields.filter { key, _ in !ImageDownloadCoordinator.cachingHeaderFieldsNames.contains(key.lowercased()) } headerFields["Cache-Control"] = "max-age=\(Int(cacheDuration.rounded()))" guard let newResponse = HTTPURLResponse( url: url, statusCode: response.statusCode, httpVersion: "HTTP/1.1", headerFields: headerFields ) else { return proposedResponse } return CachedURLResponse( response: newResponse, data: proposedResponse.data, userInfo: proposedResponse.userInfo, storagePolicy: .allowed ) } } } extension ImageDownloadCoordinator: URLSessionDataDelegate { private static let cachingHeaderFieldsNames = setOf( "cache-control", "expires", "pragma" ) func urlSession(_ session: URLSession, dataTask task: URLSessionDataTask, didReceive data: Data) { assert(queue: .main) guard let downloader = downloadersByTaskId[task.taskIdentifier] else { fatalError("Cannot find downloader for task: \(task)") } downloader.task(task, didReceive: data) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { assert(queue: .main) guard let downloader = downloadersByTaskId[task.taskIdentifier] else { fatalError("Cannot find downloader for task: \(task)") } downloadersByTaskId[task.taskIdentifier] = nil downloader.task(task, didCompleteWith: error) { assert(queue: .main) self.downloadersByURL[downloader.url] = nil } } func urlSession( _ session: URLSession, dataTask task: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void ) { assert(queue: .main) guard let downloader = downloadersByTaskId[task.taskIdentifier] else { // can actually happen when the task was canceled completionHandler(nil) return } completionHandler(downloader.task(task, willCache: proposedResponse)) } } private final class ImageFileLoader { typealias Completion = (UIImage) -> Void private static var loaders = [Query : ImageFileLoader]() private static let operationQueue = OperationQueue() private var completions = [Int : Completion]() private var image: UIImage? private var nextId = 0 private var operation: Operation? private let query: Query private init(query: Query) { self.query = query } private func cancelCompletionWithId(_ id: Int) { completions[id] = nil if completions.isEmpty { onMainQueue { // wait one cycle. maybe someone canceled just to retry immediately if self.completions.isEmpty { self.cancelOperation() } } } } private func cancelOperation() { precondition(completions.isEmpty) operation?.cancel() operation = nil } static func forURL(_ url: URL, size: CGFloat) -> ImageFileLoader { let query = Query(url: url, size: size) if let loader = loaders[query] { return loader } let loader = ImageFileLoader(query: query) loaders[query] = loader return loader } func load(completion: @escaping Completion) -> CancelClosure { if let image = image { completion(image) return {} } if let image = ImageCache.sharedInstance.image(for: query) { self.image = image runAllCompletions() cancelOperation() completion(image) return {} } let id = nextId nextId += 1 completions[id] = completion startOperation() return { self.cancelCompletionWithId(id) } } private func runAllCompletions() { guard let image = image else { fatalError("Cannot run completions unless an image was successfully loaded") } // careful: a completion might get removed while we're calling another one so don't copy the dictionary while let (id, completion) = self.completions.first { self.completions.removeValue(forKey: id) completion(image) } ImageFileLoader.loaders[query] = nil } private func startOperation() { precondition(image == nil) precondition(!completions.isEmpty) guard self.operation == nil else { return } let query = self.query let size = query.size let url = query.url let operation = BlockOperation() { var image: UIImage? defer { onMainQueue { self.operation = nil self.image = image guard let image = image else { return } ImageCache.sharedInstance.set(image: image, for: query) self.runAllCompletions() } } guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { log("Cannot load image '\(url)': Cannot create image source") return } let options: [AnyHashable: Any] = [ kCGImageSourceCreateThumbnailFromImageAlways: kCFBooleanTrue as Any, kCGImageSourceCreateThumbnailWithTransform: kCFBooleanTrue as Any, kCGImageSourceThumbnailMaxPixelSize: size ] guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary?) else { log("Cannot load image '\(url)': Cannot create thumbnail from image source") return } image = UIImage(cgImage: cgImage) image?.inflate() } self.operation = operation ImageFileLoader.operationQueue.addOperation(operation) } final class Query: NSObject { let size: CGFloat let url: URL init(url: URL, size: CGFloat) { self.size = size self.url = url } override func copy() -> Any { return self } override var hash: Int { return url.hashValue ^ size.hashValue } override func isEqual(_ object: Any?) -> Bool { guard let query = object as? Query else { return false } return url == query.url && size == query.size } } }
mit
66a7c1e158dd993b41e0c96da6b480b7
21.488764
150
0.702348
4.004001
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Reduce.swift
5
1141
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // open class ReduceProcedure<Element, U>: TransformProcedure<AnySequence<Element>, U> { public init<S: Sequence>(source: S, initial: U, nextPartialResult block: @escaping (U, Element) throws -> U) where S.Iterator.Element == Element, S.SubSequence: Sequence, S.SubSequence.Iterator.Element == Element, S.SubSequence.SubSequence == S.SubSequence { super.init { try $0.reduce(initial, block) } self.input = .ready(AnySequence(source)) self.output = .ready(.success(initial)) } public convenience init(initial: U, nextPartialResult block: @escaping (U, Element) throws -> U) { self.init(source: [], initial: initial, nextPartialResult: block) } } public extension OutputProcedure where Self.Output: Sequence { func reduce<U>(_ initial: U, nextPartialResult: @escaping (U, Output.Iterator.Element) throws -> U) -> ReduceProcedure<Output.Iterator.Element, U> { return ReduceProcedure(initial: initial, nextPartialResult: nextPartialResult).injectResult(from: self) { AnySequence(Array($0)) } } }
mit
1cbeab77c81908bf5573d74d0febb422
44.6
262
0.704386
4.115523
false
false
false
false
BlurredSoftware/BSWFoundation
Tests/BSWFoundationTests/APIClient/APIClientErrorTests.swift
1
1258
import XCTest @testable import BSWFoundation class APIClientErrorTests: XCTestCase { func testErrorPrinting_encodingRequestFailed() { let localizedDescription = APIClient.Error.encodingRequestFailed.localizedDescription XCTAssert(localizedDescription == "The operation couldn’t be completed. (BSWFoundation.APIClient.Error.encodingRequestFailed)") } func testErrorPrinting_serverStatusCode() { let errorMessageData = """ ["Please try again"] """.data(using: .utf8) let localizedDescription = APIClient.Error.failureStatusCode(400, errorMessageData).localizedDescription XCTAssert(localizedDescription == "The operation couldn’t be completed. (BSWFoundation.APIClient.Error.FailureStatusCode: 400, Message: [\"Please try again\"])") } func testErrorPrinting_serverStatusCode_2() { let errorMessageData = """ "Please try again" """.data(using: .utf8) let localizedDescription = APIClient.Error.failureStatusCode(400, errorMessageData).localizedDescription XCTAssert(localizedDescription == "The operation couldn’t be completed. (BSWFoundation.APIClient.Error.FailureStatusCode: 400, Message: \"Please try again\")") } }
mit
ef2324906c4025ad5ad31594f72dda36
47.153846
169
0.724441
5.238494
false
true
false
false
Kalito98/Find-me-a-band
Find me a band/Find me a band/Utils/HttpRequester.swift
1
4048
// // HttpRequester.swift // Find me a band // // Created by Kaloyan Yanev on 3/23/17. // Copyright © 2017 Kaloyan Yanev. All rights reserved. // import Foundation class HttpRequester { var delegate: HttpRequesterDelegate? func get(fromUrl urlString: String, andHeaders headers: Dictionary<String, String> = [:]){ self.send(withMethod: .get, toUrl: urlString, withBody: nil, andHeaders: headers) } func post(toUrl urlString: String, withBody bodyInput: Any?, andHeaders headers: Dictionary<String, String> = [:]){ self.send(withMethod: .post, toUrl: urlString, withBody: bodyInput, andHeaders: headers) } func delete(atUrl urlString: String, withBody bodyInput: Any?, andHeaders headers: Dictionary<String, String> = [:]) { self.send(withMethod: .delete, toUrl: urlString, withBody: bodyInput, andHeaders: headers) } func put(atUrl urlString: String, withBody bodyInput: Any?, andHeaders headers: Dictionary<String, String> = [:]) { self.send(withMethod: .put, toUrl: urlString, withBody: bodyInput, andHeaders: headers) } func postJson(toUrl urlString: String, withBody bodyInput: Any?, andHeaders headers: Dictionary<String, String> = [:]){ var headersWithJson: Dictionary<String,String>= [:] headers.forEach(){ headersWithJson[$0.key] = $0.value } headersWithJson["Content-Type"] = "application/json" self.post(toUrl: urlString, withBody: bodyInput, andHeaders: headersWithJson) } func putJson(atUrl urlString: String, withBody bodyInput: Any?, andHeaders headers: Dictionary<String, String> = [:]){ var headersWithJson: Dictionary<String,String>= [:] headers.forEach(){ headersWithJson[$0.key] = $0.value } headersWithJson["Content-Type"] = "application/json" self.put(atUrl: urlString, withBody: bodyInput, andHeaders: headersWithJson) } func deleteJson(atUrl urlString: String, withBody bodyInput: Any?, andHeaders headers: Dictionary<String, String> = [:]){ var headersWithJson: Dictionary<String,String>= [:] headers.forEach(){ headersWithJson[$0.key] = $0.value } headersWithJson["Content-Type"] = "application/json" self.delete(atUrl: urlString, withBody: bodyInput, andHeaders: headersWithJson) } func send(withMethod method: HttpMethod, toUrl urlString: String, withBody bodyInput: Any? = nil, andHeaders headers: Dictionary<String, String> = [:]) { let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = method.rawValue if(bodyInput != nil) { do { let body = try JSONSerialization.data(withJSONObject: bodyInput!, options: .prettyPrinted) request.httpBody = body } catch { } } headers.forEach() { request.setValue($0.value, forHTTPHeaderField: $0.key) } weak var weakSelf = self let dataTask = URLSession.shared.dataTask(with: request, completionHandler: { bodyData, response, error in do { let body = try JSONSerialization.jsonObject(with: bodyData!, options: .allowFragments) if((response as! HTTPURLResponse).statusCode >= 400) { weakSelf?.delegate?.didReceiveError(error: .api("404")) return } switch( method) { case .delete: weakSelf?.delegate?.didDeleteData() default: weakSelf?.delegate?.didReceiveData(data: body) } } catch { weakSelf?.delegate?.didReceiveError(error: .api(error.localizedDescription)) } }) dataTask.resume() } }
mit
fd868d3eaae7a05c615ed1b3bdc00cd8
40.721649
125
0.595009
4.97786
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Model/CGSSSkill.swift
1
13799
// // CGSSSkill.swift // CGSSFoundation // // Created by zzk on 16/6/14. // Copyright © 2016年 zzk. All rights reserved. // import Foundation import SwiftyJSON fileprivate let skillDescriptions = [ 1: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成", comment: "技能描述"), 2: NSLocalizedString("使所有PERFECT/GREAT音符获得 %d%% 的分数加成", comment: "技能描述"), 3: NSLocalizedString("使所有PERFECT/GREAT/NICE音符获得 %d%% 的分数加成", comment: "技能描述"), 4: NSLocalizedString("获得额外的 %d%% 的COMBO加成", comment: "技能描述"), 5: NSLocalizedString("使所有GREAT音符改判为PERFECT", comment: "技能描述"), 6: NSLocalizedString("使所有GREAT/NICE音符改判为PERFECT", comment: "技能描述"), 7: NSLocalizedString("使所有GREAT/NICE/BAD音符改判为PERFECT", comment: "技能描述"), 8: NSLocalizedString("所有音符改判为PERFECT", comment: "技能描述"), 9: NSLocalizedString("使NICE音符不会中断COMBO", comment: "技能描述"), 10: NSLocalizedString("使BAD/NICE音符不会中断COMBO", comment: "技能描述"), 11: NSLocalizedString("使你的COMBO不会中断", comment: "技能描述"), 12: NSLocalizedString("使你的生命不会减少", comment: "技能描述"), 13: NSLocalizedString("使所有音符恢复你 %d 点生命", comment: "技能描述"), 14: NSLocalizedString("消耗 %2$d 生命,PERFECT音符获得 %1$d%% 的分数加成,并且NICE/BAD音符不会中断COMBO", comment: "技能描述"), 15: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,且使PERFECT判定区间的时间范围缩小", comment: ""), 16: NSLocalizedString("重复发动上一个其他偶像发动过的技能", comment: ""), 17: NSLocalizedString("使所有PERFECT音符恢复你 %d 点生命", comment: "技能描述"), 18: NSLocalizedString("使所有PERFECT/GREAT音符恢复你 %d 点生命", comment: "技能描述"), 19: NSLocalizedString("使所有PERFECT/GREAT/NICE音符恢复你 %d 点生命", comment: "技能描述"), 20: NSLocalizedString("使当前发动的分数加成和COMBO加成额外提高 %d%%,生命恢复和护盾额外恢复 1 点生命,改判范围增加一档", comment: ""), 21: NSLocalizedString("当仅有Cute偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""), 22: NSLocalizedString("当仅有Cool偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""), 23: NSLocalizedString("当仅有Passion偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""), 24: NSLocalizedString("获得额外的 %d%% 的COMBO加成,并使所有PERFECT音符恢复你 %d 点生命", comment: ""), 25: NSLocalizedString("获得额外的COMBO加成,当前生命值越高加成越高", comment: ""), 26: NSLocalizedString("当Cute、Cool和Passion偶像存在于队伍时,使所有PERFECT音符获得 %1$d%% 的分数加成/恢复你 %3$d 点生命,并获得额外的 %2$d%% 的COMBO加成", comment: "") ] fileprivate let intervalClause = NSLocalizedString("每 %d 秒,", comment: "") fileprivate let probabilityClause = NSLocalizedString("有 %@%% 的几率", comment: "") fileprivate let lengthClause = NSLocalizedString(",持续 %@ 秒。", comment: "") extension CGSSSkill { private var effectValue: Int { var effectValue = value! if [1, 2, 3, 4, 14, 15, 21, 22, 23, 24, 26].contains(skillTypeId) { effectValue -= 100 } else if [20].contains(skillTypeId) { // there is only one possibility: 20% up for combo bonus and perfect bonus, using fixed value here instead of reading it from database table skill_boost_type. if more possiblities are added to the game, fix here. effectValue = 20 } return effectValue } private var effectValue2: Int { var effectValue2 = value2! if [21, 22, 23, 26].contains(skillTypeId) { effectValue2 -= 100 } return effectValue2 } private var effectValue3: Int { return value3 } private var effectExpalin: String { if skillTypeId == 14 { return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, skillTriggerValue) } else { return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, effectValue2, effectValue3) } } private var intervalExplain: String { return String.init(format: intervalClause, condition) } @nonobjc func getLocalizedExplainByRange(_ range: CountableClosedRange<Int>) -> String { let probabilityRangeString = String(format: "%.2f ~ %.2f", self.procChanceOfLevel(range.lowerBound) / 100, self.procChanceOfLevel(range.upperBound) / 100) let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString) let lengthRangeString = String(format: "%.2f ~ %.2f", self.effectLengthOfLevel(range.lowerBound) / 100, self.effectLengthOfLevel(range.upperBound) / 100) let lengthExplain = String.init(format: lengthClause, lengthRangeString) return intervalExplain + probabilityExplain + effectExpalin + lengthExplain } @nonobjc func getLocalizedExplainByLevel(_ level: Int) -> String { let probabilityRangeString = String(format: "%.2f", self.procChanceOfLevel(level) / 100) let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString) let lengthRangeString = String(format: "%.2f", self.effectLengthOfLevel(level) / 100) let lengthExplain = String.init(format: lengthClause, lengthRangeString) return intervalExplain + probabilityExplain + effectExpalin + lengthExplain } var skillFilterType: CGSSSkillTypes { return CGSSSkillTypes(typeID: skillTypeId) } var descriptionShort: String { return "\(condition!)s/\(procTypeShort)/\(skillFilterType.description)" } // 在计算触发几率和持续时间时 要在取每等级增量部分进行一次向下取整 func procChanceOfLevel(_ lv: Int) -> Double { if let p = procChance { let p1 = Double(p[1]) let p0 = Double(p[0]) return (floor((p1 - p0) / 9) * (Double(lv) - 1) + p0) } else { return 0 } } func effectLengthOfLevel(_ lv: Int) -> Double { if let e = effectLength { let e1 = Double(e[1]) let e0 = Double(e[0]) return (floor((e1 - e0) / 9) * (Double(lv) - 1) + e0) } else { return 0 } } var procTypeShort: String { switch maxChance { case 6000: return NSLocalizedString("高", comment: "技能触发几率的简写") case 5250: return NSLocalizedString("中", comment: "技能触发几率的简写") case 4500: return NSLocalizedString("低", comment: "技能触发几率的简写") default: return NSLocalizedString("其他", comment: "通用, 通常不会出现, 为未知字符预留") } } var procType: CGSSProcTypes { switch maxChance { case 6000: return .high case 5250: return .middle case 4500: return .low default: return .none } } var conditionType: CGSSConditionTypes { switch condition { case 4: return .c4 case 6: return .c6 case 7: return .c7 case 9: return .c9 case 11: return .c11 case 13: return .c13 default: return .other } } } class CGSSSkill: CGSSBaseModel { var condition: Int! var cutinType: Int! var effectLength: [Int]! var explain: String! var explainEn: String! var id: Int! var judgeType: Int! var maxChance: Int! var maxDuration: Int! var procChance: [Int]! var skillName: String! var skillTriggerType: Int! var skillTriggerValue: Int! var skillType: String! var value: Int! var skillTypeId: Int! var value2: Int! var value3: Int! /** * Instantiate the instance using the passed json values to set the properties values */ init(fromJson json: JSON!) { super.init() if json == JSON.null { return } condition = json["condition"].intValue cutinType = json["cutin_type"].intValue effectLength = [Int]() let effectLengthArray = json["effect_length"].arrayValue for effectLengthJson in effectLengthArray { effectLength.append(effectLengthJson.intValue) } explain = json["explain"].stringValue explainEn = json["explain_en"].stringValue id = json["id"].intValue judgeType = json["judge_type"].intValue maxChance = json["max_chance"].intValue maxDuration = json["max_duration"].intValue procChance = [Int]() let procChanceArray = json["proc_chance"].arrayValue for procChanceJson in procChanceArray { procChance.append(procChanceJson.intValue) } skillName = json["skill_name"].stringValue skillTriggerType = json["skill_trigger_type"].intValue skillTriggerValue = json["skill_trigger_value"].intValue skillType = json["skill_type"].stringValue if skillType == "" { skillType = NSLocalizedString("未知", comment: "") } value = json["value"].intValue value2 = json["value_2"].intValue value3 = json["value_3"].intValue skillTypeId = json["skill_type_id"].intValue } /** * NSCoding required initializer. * Fills the data from the passed decoder */ required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) condition = aDecoder.decodeObject(forKey: "condition") as? Int cutinType = aDecoder.decodeObject(forKey: "cutin_type") as? Int effectLength = aDecoder.decodeObject(forKey: "effect_length") as? [Int] explain = aDecoder.decodeObject(forKey: "explain") as? String explainEn = aDecoder.decodeObject(forKey: "explain_en") as? String id = aDecoder.decodeObject(forKey: "id") as? Int judgeType = aDecoder.decodeObject(forKey: "judge_type") as? Int maxChance = aDecoder.decodeObject(forKey: "max_chance") as? Int maxDuration = aDecoder.decodeObject(forKey: "max_duration") as? Int procChance = aDecoder.decodeObject(forKey: "proc_chance") as? [Int] skillName = aDecoder.decodeObject(forKey: "skill_name") as? String skillTriggerType = aDecoder.decodeObject(forKey: "skill_trigger_type") as? Int skillTriggerValue = aDecoder.decodeObject(forKey: "skill_trigger_value") as? Int skillType = aDecoder.decodeObject(forKey: "skill_type") as? String ?? NSLocalizedString("未知", comment: "") value = aDecoder.decodeObject(forKey: "value") as? Int skillTypeId = aDecoder.decodeObject(forKey: "skill_type_id") as? Int value2 = aDecoder.decodeObject(forKey: "value_2") as? Int value3 = aDecoder.decodeObject(forKey: "value_3") as? Int } /** * NSCoding required method. * Encodes mode properties into the decoder */ override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) if condition != nil { aCoder.encode(condition, forKey: "condition") } if cutinType != nil { aCoder.encode(cutinType, forKey: "cutin_type") } if effectLength != nil { aCoder.encode(effectLength, forKey: "effect_length") } if explain != nil { aCoder.encode(explain, forKey: "explain") } if explainEn != nil { aCoder.encode(explainEn, forKey: "explain_en") } if id != nil { aCoder.encode(id, forKey: "id") } if judgeType != nil { aCoder.encode(judgeType, forKey: "judge_type") } if maxChance != nil { aCoder.encode(maxChance, forKey: "max_chance") } if maxDuration != nil { aCoder.encode(maxDuration, forKey: "max_duration") } if procChance != nil { aCoder.encode(procChance, forKey: "proc_chance") } if skillName != nil { aCoder.encode(skillName, forKey: "skill_name") } if skillTriggerType != nil { aCoder.encode(skillTriggerType, forKey: "skill_trigger_type") } if skillTriggerValue != nil { aCoder.encode(skillTriggerValue, forKey: "skill_trigger_value") } if skillType != nil { aCoder.encode(skillType, forKey: "skill_type") } if value != nil { aCoder.encode(value, forKey: "value") } if skillTypeId != nil { aCoder.encode(skillTypeId, forKey: "skill_type_id") } if value2 != nil { aCoder.encode(value2, forKey: "value_2") } if value3 != nil { aCoder.encode(value3, forKey: "value_3") } } }
mit
e0720471064963f6103eaa816f1b3901
36.688623
224
0.612488
4.222744
false
false
false
false
TotalDigital/People-iOS
People at Total/Skill.swift
1
855
// // Info.swift // justOne // // Created by Florian Letellier on 29/01/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import Foundation class Skill: NSObject, NSCoding { var skills: [String] = [] var skillsIds: [Int] = [] override init() { } init(skills: [String], skillsIds: [Int]) { self.skills = skills self.skillsIds = skillsIds } required convenience init(coder aDecoder: NSCoder) { let skills = aDecoder.decodeObject(forKey: "skills") as! [String] let skillsIds = aDecoder.decodeObject(forKey: "skillsIds") as! [Int] self.init(skills: skills, skillsIds: skillsIds) } func encode(with aCoder: NSCoder) { aCoder.encode(skills, forKey: "skills") aCoder.encode(skillsIds, forKey: "skillsIds") } }
apache-2.0
8fce1f1761fc4dfa5b246b382e8bb551
23.4
76
0.611241
3.972093
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Services/WalletRecovery/Validation/SeedPhraseValidator.swift
1
3353
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation import HDWalletKit public protocol SeedPhraseValidatorAPI { func validate(phrase: String) -> AnyPublisher<MnemonicValidationScore, Never> } public final class SeedPhraseValidator: SeedPhraseValidatorAPI { // MARK: - Type private enum Constant { static let seedPhraseLength: Int = 12 } // MARK: - Properties private let words: Set<String> // MARK: - Setup public init(words: Set<String> = Set(WordList.default.words)) { self.words = words } // MARK: - API public func validate(phrase: String) -> AnyPublisher<MnemonicValidationScore, Never> { if phrase.isEmpty { return .just(.none) } /// Make an array of the individual words let components = phrase .components(separatedBy: .whitespacesAndNewlines) .filter { !$0.isEmpty } if components.count < Constant.seedPhraseLength { return .just(.incomplete) } if components.count > Constant.seedPhraseLength { return .just(.excess) } /// Separate out the words that are duplicates let duplicates = Set(components.duplicates ?? []) /// The total number of duplicates entered let duplicatesCount = duplicates .map { duplicate in components.filter { $0 == duplicate }.count } .reduce(0, +) /// Make a set for all the individual entries let set = Set(phrase.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty && !duplicates.contains($0) }) guard !set.isEmpty || duplicatesCount > 0 else { return .just(.none) } /// Are all the words entered thus far valid words let entriesAreValid = set.isSubset(of: words) && duplicates.isSubset(of: words) if entriesAreValid { return .just(.valid) } /// Combine the `set` and `duplicates` to form a `Set<String>` of all /// words that are not included in the `WordList` let difference = set.union(duplicates).subtracting(words) /// Find the `NSRange` value for each word or incomplete word that is not /// included in the `WordList` let ranges = difference.map { delta -> [NSRange] in phrase.ranges(of: delta) } .flatMap { $0 } return .just(.invalid(ranges)) } } // MARK: - Convenience extension String { /// A convenience function for getting an array of `NSRange` values /// for a particular substring. fileprivate func ranges(of substring: String) -> [NSRange] { var ranges: [Range<Index>] = [] enumerateSubstrings(in: startIndex..<endIndex, options: .byWords) { word, value, _, _ in if let word = word, word == substring { ranges.append(value) } } return ranges.map { NSRange($0, in: self) } } } extension Array where Element: Hashable { public var duplicates: [Element]? { let dictionary = Dictionary(grouping: self, by: { $0 }) let pairs = dictionary.filter { $1.count > 1 } let duplicates = Array(pairs.keys) return !duplicates.isEmpty ? duplicates : nil } }
lgpl-3.0
4e620e870afb8db2611416bbaabf35a0
29.472727
129
0.604415
4.610729
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Metadata/Sources/MetadataKit/Models/Entry/EntryType.swift
1
882
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation /// The derivation index of each metadata entry currently in use. /// /// The following entry indexes are reserved but deprecated: /// - `2`: `What's New` /// - `3`: `Buy/Sell` /// - `4`: `Contacts` /// - `6`: `Shapeshift` /// - `9`: `Lockbox` /// public enum EntryType: Int32 { /// Second password node case root = -1 /// Ethereum case ethereum = 5 /// Bitcoin Cash case bitcoinCash = 7 /// Bitcoin case bitcoin = 8 /// Nabu User Credentials - **deprecated** case userCredentials = 10 /// Stellar case stellar = 11 /// Wallet Credentials - Used for wallet recovery case walletCredentials = 12 /// WalletConnect case walletConnect = 13 /// Account Credentials for unified accounts case accountCredentials = 14 }
lgpl-3.0
1a95567c2819bb7ce21cb73215d69fd7
19.97619
65
0.623156
4.175355
false
false
false
false
Flank/flank
test_projects/ios/EarlGreyExample/EarlGreyExampleSwiftTests/EarlGrey.swift
3
7769
// // Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import EarlGrey import Foundation public func GREYAssert(_ expression: @autoclosure () -> Bool, reason: String) { GREYAssert(expression(), reason, details: "Expected expression to be true") } public func GREYAssertTrue(_ expression: @autoclosure () -> Bool, reason: String) { GREYAssert(expression(), reason, details: "Expected the boolean expression to be true") } public func GREYAssertFalse(_ expression: @autoclosure () -> Bool, reason: String) { GREYAssert(!expression(), reason, details: "Expected the boolean expression to be false") } public func GREYAssertNotNil(_ expression: @autoclosure ()-> Any?, reason: String) { GREYAssert(expression() != nil, reason, details: "Expected expression to be not nil") } public func GREYAssertNil(_ expression: @autoclosure () -> Any?, reason: String) { GREYAssert(expression() == nil, reason, details: "Expected expression to be nil") } public func GREYAssertEqual(_ left: @autoclosure () -> AnyObject?, _ right: @autoclosure () -> AnyObject?, reason: String) { GREYAssert(left() === right(), reason, details: "Expected left term to be equal to right term") } public func GREYAssertNotEqual(_ left: @autoclosure () -> AnyObject?, _ right: @autoclosure () -> AnyObject?, reason: String) { GREYAssert(left() !== right(), reason, details: "Expected left term to not equal the right term") } public func GREYAssertEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?, _ right: @autoclosure () -> T?, reason: String) { GREYAssert(left() == right(), reason, details: "Expected object of the left term to be equal " + "to the object of the right term") } public func GREYAssertNotEqualObjects<T: Equatable>( _ left: @autoclosure () -> T?, _ right: @autoclosure () -> T?, reason: String) { GREYAssert(left() != right(), reason, details: "Expected object of the left term to not " + "equal the object of the right term") } public func GREYFail(_ reason: String) { EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: "") } public func GREYFailWithDetails(_ reason: String, details: String) { EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: details) } private func GREYAssert(_ expression: @autoclosure () -> Bool, _ reason: String, details: String) { GREYSetCurrentAsFailable() GREYWaitUntilIdle() if !expression() { EarlGrey.handle(exception: GREYFrameworkException(name: kGREYAssertionFailedException, reason: reason), details: details) } } private func GREYSetCurrentAsFailable() { let greyFailureHandlerSelector = #selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:)) let greyFailureHandler = Thread.current.threadDictionary.value(forKey: kGREYFailureHandlerKey) as! GREYFailureHandler if greyFailureHandler.responds(to: greyFailureHandlerSelector) { greyFailureHandler.setInvocationFile!(#file, andInvocationLine:#line) } } private func GREYWaitUntilIdle() { GREYUIThreadExecutor.sharedInstance().drainUntilIdle() } open class EarlGrey: NSObject { public static func selectElement(with matcher: GREYMatcher, file: StaticString = #file, line: UInt = #line) -> GREYInteraction { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .selectElement(with: matcher) } @available(*, deprecated, renamed: "selectElement(with:)") open class func select(elementWithMatcher matcher:GREYMatcher, file: StaticString = #file, line: UInt = #line) -> GREYElementInteraction { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .selectElement(with: matcher) } open class func setFailureHandler(handler: GREYFailureHandler, file: StaticString = #file, line: UInt = #line) { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .setFailureHandler(handler) } open class func handle(exception: GREYFrameworkException, details: String, file: StaticString = #file, line: UInt = #line) { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .handle(exception, details: details) } @discardableResult open class func rotateDeviceTo(orientation: UIDeviceOrientation, errorOrNil: UnsafeMutablePointer<NSError?>!, file: StaticString = #file, line: UInt = #line) -> Bool { return EarlGreyImpl.invoked(fromFile: file.description, lineNumber: line) .rotateDevice(to: orientation, errorOrNil: errorOrNil) } } extension GREYInteraction { @discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher) -> Self { return self.__assert(with: matcher()) } @discardableResult public func assert(_ matcher: @autoclosure () -> GREYMatcher, error:UnsafeMutablePointer<NSError?>!) -> Self { return self.__assert(with: matcher(), error: error) } @available(*, deprecated, renamed: "assert(_:)") @discardableResult public func assert(with matcher: GREYMatcher!) -> Self { return self.__assert(with: matcher) } @available(*, deprecated, renamed: "assert(_:error:)") @discardableResult public func assert(with matcher: GREYMatcher!, error:UnsafeMutablePointer<NSError?>!) -> Self { return self.__assert(with: matcher, error: error) } @discardableResult public func perform(_ action: GREYAction!) -> Self { return self.__perform(action) } @discardableResult public func perform(_ action: GREYAction!, error:UnsafeMutablePointer<NSError?>!) -> Self { return self.__perform(action, error: error) } @discardableResult public func using(searchAction: GREYAction, onElementWithMatcher matcher: GREYMatcher) -> Self { return self.usingSearch(searchAction, onElementWith: matcher) } } extension GREYCondition { open func waitWithTimeout(seconds: CFTimeInterval) -> Bool { return self.wait(withTimeout: seconds) } open func waitWithTimeout(seconds: CFTimeInterval, pollInterval: CFTimeInterval) -> Bool { return self.wait(withTimeout: seconds, pollInterval: pollInterval) } }
apache-2.0
ecec5ac93f4b990f36f1116c22e775b1
40.324468
99
0.626979
5.114549
false
false
false
false
springwong/SnapKitten
SnapKitten/Classes/Core/Cub/CubItem.swift
1
673
// // CubItem.swift // Pods // // Created by Spring Wong on 12/3/2017. // // import UIKit internal final class CubItem { var view : UIView var isCenter : Bool = false var isCenterX : Bool = false var isCenterY : Bool = false var topOffset : Int = 0 var leftOffset : Int = 0 var bottomOffset : Int = 0 var rightOffset : Int = 0 var topAction : CubRelativeAction? var bottomAction : CubRelativeAction? var leftAction : CubRelativeAction? var rightAction : CubRelativeAction? var width : KittenDimension? var height : KittenDimension? init(view : UIView) { self.view = view } }
mit
e498367ed64712b653e8549b242dadfa
18.794118
41
0.624071
3.982249
false
false
false
false
aslecape/cookpad-coding-challenge
SwiftCodingChallenge/Controllers/MenuTableViewController.swift
1
7886
// // MenuTableViewController.swift // SwiftCodingChallenge // // Created by Lea Asle Cape on 5/15/17. // Copyright © 2017 Accenture. All rights reserved. // import Foundation import UIKit private let displaySegueId = "displaySegue" class MenuTableViewController: UITableViewController, MenuButtonsDelegate{ @IBOutlet weak var vwCollection : UIView! @IBOutlet weak var collectionView: UICollectionView! var menus:[Menu] = menuData var photos:[Pinterest] = [] var roundedFrame: CGRect = CGRectMake(0, 0, 0, 0) var index: Int = 0 var indexPath: NSIndexPath = NSIndexPath() var alert: UIAlertController = UIAlertController() private let flipPresentAnimationController = FlipPresentAnimationController() private let flipDismissAnimationController = FlipDismissAnimationController() override func viewDidLoad() { super.viewDidLoad() animateTable() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: TableView override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menus.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MenuTableViewCell", forIndexPath: indexPath) as! MenuTableViewCell cell.delegate = self cell.indexPath = indexPath let menu = menus[indexPath.row] as Menu cell.menu = menu return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath)! as! MenuTableViewCell cell.selectionStyle = .None if indexPath.row == 0 || indexPath.row == 1{ //Animate Unselected Cells let cells = tableView.visibleCells for i in cells { let unSelectedCell: UITableViewCell = i as UITableViewCell if unSelectedCell != cell { UIView.animateWithDuration(1, animations: { () -> Void in unSelectedCell.frame = CGRectMake(tableView.bounds.origin.x, tableView.bounds.origin.y, cell.bounds.size.width, cell.vwLabel.bounds.size.height+25) }) } } //Animate Selected Cell UIView.animateWithDuration(1, animations: { () -> Void in cell.frame = CGRectMake(tableView.bounds.origin.x, tableView.bounds.origin.y, cell.bounds.size.width, cell.vwLabel.bounds.size.height+25) cell.imgMenu.fadeOut() cell.vwLabel.frame = CGRectMake(0, 20, cell.vwLabel.bounds.size.width, cell.vwLabel.bounds.size.height) cell.imgArrow.hidden = false cell.btnName.hidden = false }) //Get array based on selected if indexPath.row == 1 { photos = InstagramData.allPhotos(indexPath.row) }else{ photos = PinterestData.allPhotos(indexPath.row) } collectionView.reloadData() //Animate CollectionTableViewCell UIView.animateWithDuration(1, animations: { () -> Void in self.vwCollection.frame = CGRectMake(tableView.bounds.origin.x, cell.frame.size.height, self.vwCollection.bounds.size.width, self.vwCollection.bounds.size.height) }) } else{ // Alert - No Sample Data alert = UIAlertController(title: "Alert", message: "No sample data", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } // Animate Menu Tableview func animateTable() { tableView.reloadData() let cells = tableView.visibleCells let tableHeight: CGFloat = tableView.bounds.size.height for i in cells { let cell: UITableViewCell = i as UITableViewCell cell.transform = CGAffineTransformMakeTranslation(0, tableHeight) } var index = 0 for a in cells { let cell: UITableViewCell = a as UITableViewCell UIView.animateWithDuration(1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { cell.transform = CGAffineTransformMakeTranslation(0, 0); }, completion: nil) index += 1 } } // Menu button tapped func btnNameTapped(at indexPath: NSIndexPath) { tableView.reloadData() let cells = tableView.visibleCells let selectedCell = cells[indexPath.row] as! MenuTableViewCell selectedCell.imgMenu.alpha = 1.0 selectedCell.imgArrow.hidden = true selectedCell.btnName.hidden = true for i in cells { let cell: UITableViewCell = i as UITableViewCell UIView.animateWithDuration(1, animations: { () -> Void in cell.transform = CGAffineTransformIdentity }) } } } //MARK: CollectionView extension MenuTableViewController : UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int { return photos.count } func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PhotoCollectioViewCell",forIndexPath: indexPath) as! PhotoCollectioViewCell cell.photo = photos[indexPath.row] return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){ let attributes: UICollectionViewLayoutAttributes = collectionView.layoutAttributesForItemAtIndexPath(indexPath)! let cellFrameInView : CGRect = collectionView.convertRect(attributes.frame, toView: self.view) roundedFrame = cellFrameInView index = indexPath.row self.indexPath = indexPath performSegueWithIdentifier(displaySegueId, sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == displaySegueId, let destinationViewController = segue.destinationViewController as? DisplayViewController { destinationViewController.indexPath = self.indexPath destinationViewController.photos = photos destinationViewController.transitioningDelegate = self } } } //MARK: Transition Animation extension MenuTableViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { flipPresentAnimationController.originFrame = roundedFrame return flipPresentAnimationController } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { flipDismissAnimationController.destinationFrame = roundedFrame return flipDismissAnimationController } }
mit
03ddbc2ee1043ea154242d1ce74e6c41
39.435897
217
0.658973
5.80206
false
false
false
false
snazzware/Mergel
HexMatch/Pieces/Buyable/BuyablePiece.swift
2
1286
// // BuyablePiece.swift // HexMatch // // Created by Josh McKee on 1/31/16. // Copyright © 2016 Josh McKee. All rights reserved. // import Foundation import SpriteKit class BuyablePiece: NSObject, NSCoding { var basePrice: Int = 0 var currentPrice: Int = 0 var value: Int = 0 override init () { super.init() } override var description: String { return "Buyable Piece" } func resetPrice() { self.currentPrice = self.basePrice } func wasPurchased() { self.currentPrice = Int(Double(self.currentPrice) * 1.5) } func createPiece() -> HexPiece { let hexPiece = HexPiece() hexPiece.value = self.value return hexPiece } required init(coder decoder: NSCoder) { super.init() self.basePrice = decoder.decodeInteger(forKey: "basePrice") self.currentPrice = decoder.decodeInteger(forKey: "currentPrice") self.value = decoder.decodeInteger(forKey: "value") } func encode(with coder: NSCoder) { coder.encode(self.basePrice, forKey: "basePrice") coder.encode(self.currentPrice, forKey: "currentPrice") coder.encode(self.value, forKey: "value") } }
mit
aa5c3d7ff4b12a604bc044183bb93dbd
21.946429
73
0.599222
4.297659
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/Controllers/LaunchViewController.swift
1
2347
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation import ReactiveCocoa /// ViewController to show while waiting for Core Data to load class LaunchViewController: UIViewController { override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let applicationDataManager = ApplicationDataManager.sharedInstance if(applicationDataManager.isDoneLoading) { checkForOnboarding() } else { RACObserve(applicationDataManager, keyPath: "isDoneLoading").subscribeNext({ [weak self] (isDoneLoading: AnyObject!) in if let isDone = isDoneLoading as? Bool { if isDone && self != nil{ self!.checkForOnboarding() } } }) } } func checkForOnboarding() { if let firstStartup = NSUserDefaults.standardUserDefaults().objectForKey("firstStartup") as? Bool { if !firstStartup { transitionToMainScreen() return } else { displayOnboardingModal() } } else { NSUserDefaults.standardUserDefaults().setValue(true, forKey: "firstStartup") } displayOnboardingModal() } func displayOnboardingModal() { let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let tutorialViewController = mainStoryboard.instantiateViewControllerWithIdentifier("onboardingViewController") NSNotificationCenter.defaultCenter().addObserver(self, selector: "transitionToMainScreen", name: "OnboardingDismissed", object: nil) presentViewController(tutorialViewController, animated: true, completion: {}) } func transitionToMainScreen() { NSNotificationCenter.defaultCenter().removeObserver(self, name: "OnboardingDismissed", object: nil) let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let mainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("tabBarViewController") UIApplication.sharedApplication().delegate!.window!!.rootViewController = mainViewController } }
epl-1.0
fb9fd2233132991f36ce3f2095fcf0f1
36.253968
140
0.64578
6.289544
false
false
false
false
kevinmbeaulieu/Signal-iOS
Signal/src/ViewControllers/ContactsPicker.swift
1
14219
// Originally based on EPContacts // // Created by Prabaharan Elangovan on 12/10/15. // Parts Copyright © 2015 Prabaharan Elangovan. All rights reserved. // // Modified for Signal by Michael Kirk on 11/25/2016 // Parts Copyright © 2016 Open Whisper Systems. All rights reserved. import UIKit import Contacts @available(iOS 9.0, *) public protocol ContactsPickerDelegate { func contactsPicker(_: ContactsPicker, didContactFetchFailed error: NSError) func contactsPicker(_: ContactsPicker, didCancel error: NSError) func contactsPicker(_: ContactsPicker, didSelectContact contact: Contact) func contactsPicker(_: ContactsPicker, didSelectMultipleContacts contacts: [Contact]) func contactsPicker(_: ContactsPicker, shouldSelectContact contact: Contact) -> Bool } @available(iOS 9.0, *) public extension ContactsPickerDelegate { func contactsPicker(_: ContactsPicker, didContactFetchFailed error: NSError) { } func contactsPicker(_: ContactsPicker, didCancel error: NSError) { } func contactsPicker(_: ContactsPicker, didSelectContact contact: Contact) { } func contactsPicker(_: ContactsPicker, didSelectMultipleContacts contacts: [Contact]) { } func contactsPicker(_: ContactsPicker, shouldSelectContact contact: Contact) -> Bool { return true } } public enum SubtitleCellValue{ case phoneNumber case email } @available(iOS 9.0, *) open class ContactsPicker: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { @IBOutlet var tableView: UITableView! @IBOutlet var searchBar: UISearchBar! // MARK: - Properties let TAG = "[ContactsPicker]" let contactCellReuseIdentifier = "contactCellReuseIdentifier" let contactsManager: OWSContactsManager let collation = UILocalizedIndexedCollation.current() let contactStore = CNContactStore() // Data Source State lazy var sections = [[CNContact]]() lazy var filteredSections = [[CNContact]]() lazy var selectedContacts = [Contact]() // Configuration open var contactsPickerDelegate: ContactsPickerDelegate? var subtitleCellValue = SubtitleCellValue.phoneNumber var multiSelectEnabled = false let allowedContactKeys: [CNKeyDescriptor] = [ CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactThumbnailImageDataKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor ] // MARK: - Lifecycle Methods override open func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("INVITE_FRIENDS_PICKER_TITLE", comment: "Navbar title") searchBar.placeholder = NSLocalizedString("INVITE_FRIENDS_PICKER_SEARCHBAR_PLACEHOLDER", comment: "Search") // Prevent content form going under the navigation bar self.edgesForExtendedLayout = [] // Auto size cells for dynamic type tableView.estimatedRowHeight = 60.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.allowsMultipleSelection = multiSelectEnabled registerContactCell() initializeBarButtons() reloadContacts() updateSearchResults(searchText: "") NotificationCenter.default.addObserver(self, selector: #selector(self.didChangePreferredContentSize), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil) } func didChangePreferredContentSize() { self.tableView.reloadData() } func initializeBarButtons() { let cancelButton = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(onTouchCancelButton)) self.navigationItem.leftBarButtonItem = cancelButton if multiSelectEnabled { let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onTouchDoneButton)) self.navigationItem.rightBarButtonItem = doneButton } } fileprivate func registerContactCell() { tableView.register(ContactCell.nib, forCellReuseIdentifier: contactCellReuseIdentifier) } // MARK: - Initializers init() { contactsManager = Environment.getCurrent().contactsManager super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { contactsManager = Environment.getCurrent().contactsManager super.init(coder: aDecoder) } convenience public init(delegate: ContactsPickerDelegate?) { self.init(delegate: delegate, multiSelection: false) } convenience public init(delegate: ContactsPickerDelegate?, multiSelection : Bool) { self.init() multiSelectEnabled = multiSelection contactsPickerDelegate = delegate } convenience public init(delegate: ContactsPickerDelegate?, multiSelection : Bool, subtitleCellType: SubtitleCellValue) { self.init() multiSelectEnabled = multiSelection contactsPickerDelegate = delegate subtitleCellValue = subtitleCellType } // MARK: - Contact Operations open func reloadContacts() { getContacts( onError: { error in Logger.error("\(self.TAG) failed to reload contacts with error:\(error)") }) } func getContacts(onError errorHandler: @escaping (_ error: Error) -> Void) { switch CNContactStore.authorizationStatus(for: CNEntityType.contacts) { case CNAuthorizationStatus.denied, CNAuthorizationStatus.restricted: let title = NSLocalizedString("AB_PERMISSION_MISSING_TITLE", comment: "Alert title when contacts disabled") let body = NSLocalizedString("ADDRESSBOOK_RESTRICTED_ALERT_BODY", comment: "Alert body when contacts disabled") let alert = UIAlertController(title: title, message: body, preferredStyle: UIAlertControllerStyle.alert) let dismissText = NSLocalizedString("DISMISS_BUTTON_TEXT", comment:"") let okAction = UIAlertAction(title: dismissText, style: UIAlertActionStyle.default, handler: { action in let error = NSError(domain: "contactsPickerErrorDomain", code: 1, userInfo: [NSLocalizedDescriptionKey: "No Contacts Access"]) self.contactsPickerDelegate?.contactsPicker(self, didContactFetchFailed: error) errorHandler(error) self.dismiss(animated: true, completion: nil) }) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) case CNAuthorizationStatus.notDetermined: //This case means the user is prompted for the first time for allowing contacts contactStore.requestAccess(for: CNEntityType.contacts) { (granted, error) -> Void in //At this point an alert is provided to the user to provide access to contacts. This will get invoked if a user responds to the alert if granted { self.getContacts(onError: errorHandler) } else { errorHandler(error!) } } case CNAuthorizationStatus.authorized: //Authorization granted by user for this app. var contacts = [CNContact]() do { let contactFetchRequest = CNContactFetchRequest(keysToFetch: allowedContactKeys) try contactStore.enumerateContacts(with: contactFetchRequest) { (contact, stop) -> Void in contacts.append(contact) } self.sections = collatedContacts(contacts) } catch let error as NSError { Logger.error("\(self.TAG) Failed to fetch contacts with error:\(error)") } } } func collatedContacts(_ contacts: [CNContact]) -> [[CNContact]] { let selector: Selector = #selector(getter: CNContact.nameForCollating) var collated = Array(repeating: [CNContact](), count: collation.sectionTitles.count) for contact in contacts { let sectionNumber = collation.section(for: contact, collationStringSelector: selector) collated[sectionNumber].append(contact) } return collated } // MARK: - Table View DataSource open func numberOfSections(in tableView: UITableView) -> Int { return self.collation.sectionTitles.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let dataSource = filteredSections return dataSource[section].count } // MARK: - Table View Delegates open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as! ContactCell let dataSource = filteredSections let cnContact = dataSource[indexPath.section][indexPath.row] let contact = Contact(contact: cnContact) cell.updateContactsinUI(contact, subtitleType: subtitleCellValue, contactsManager: self.contactsManager) let isSelected = selectedContacts.contains(where: { $0.uniqueId == contact.uniqueId }) cell.isSelected = isSelected // Make sure we preserve selection across tableView.reloadData which happens when toggling between // search controller if (isSelected) { self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } else { self.tableView.deselectRow(at: indexPath, animated: false) } return cell } open func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! ContactCell let deselectedContact = cell.contact! selectedContacts = selectedContacts.filter() { return $0.uniqueId != deselectedContact.uniqueId } } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! ContactCell let selectedContact = cell.contact! guard (contactsPickerDelegate == nil || contactsPickerDelegate!.contactsPicker(self, shouldSelectContact: selectedContact)) else { self.tableView.deselectRow(at: indexPath, animated: false) return } selectedContacts.append(selectedContact) if !multiSelectEnabled { //Single selection code self.dismiss(animated: true) { self.contactsPickerDelegate?.contactsPicker(self, didSelectContact: selectedContact) } } } open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return collation.section(forSectionIndexTitle: index) } open func sectionIndexTitles(for tableView: UITableView) -> [String]? { return collation.sectionIndexTitles } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let dataSource = filteredSections if dataSource[section].count > 0 { return collation.sectionTitles[section] } else { return nil } } // MARK: - Button Actions func onTouchCancelButton() { contactsPickerDelegate?.contactsPicker(self, didCancel: NSError(domain: "contactsPickerErrorDomain", code: 2, userInfo: [ NSLocalizedDescriptionKey: "User Canceled Selection"])) dismiss(animated: true, completion: nil) } func onTouchDoneButton() { contactsPickerDelegate?.contactsPicker(self, didSelectMultipleContacts: selectedContacts) dismiss(animated: true, completion: nil) } // MARK: - Search Actions open func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { updateSearchResults(searchText: searchText) } open func updateSearchResults(searchText: String) { let predicate: NSPredicate if searchText.characters.count == 0 { filteredSections = sections } else { do { predicate = CNContact.predicateForContacts(matchingName: searchText) let filteredContacts = try contactStore.unifiedContacts(matching: predicate,keysToFetch: allowedContactKeys) filteredSections = collatedContacts(filteredContacts) } catch let error as NSError { Logger.error("\(self.TAG) updating search results failed with error: \(error)") } } self.tableView.reloadData() } } @available(iOS 9.0, *) let ContactSortOrder = computeSortOrder() @available(iOS 9.0, *) func computeSortOrder() -> CNContactSortOrder { let comparator = CNContact.comparator(forNameSortOrder: .userDefault) let contact0 = CNMutableContact() contact0.givenName = "A" contact0.familyName = "Z" let contact1 = CNMutableContact() contact1.givenName = "Z" contact1.familyName = "A" let result = comparator(contact0, contact1) if result == .orderedAscending { return .givenName } else { return .familyName } } @available(iOS 9.0, *) fileprivate extension CNContact { /** * Sorting Key used by collation */ @objc var nameForCollating: String { get { if self.familyName.isEmpty && self.givenName.isEmpty { return self.emailAddresses.first?.value as? String ?? "" } let compositeName: String if ContactSortOrder == .familyName { compositeName = "\(self.familyName) \(self.givenName)" } else { compositeName = "\(self.givenName) \(self.familyName)" } return compositeName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } }
gpl-3.0
cb22244592497d42b6d68aa7f552dd85
38.273481
185
0.665471
5.564384
false
false
false
false
nodes-ios/nstack-translations-generator
LocalizationsGenerator/Classes/Other/URLSession+Request.swift
1
6185
// // URLSession+Request.swift // NStackSDK // // Created by Dominik Hadl on 25/09/2018. // Copyright © 2018 Nodes ApS. All rights reserved. // import Foundation public typealias Result<T> = Swift.Result<T, Error> public typealias Completion<T> = ((Result<T>) -> Void) struct DataModel<T: Codable>: WrapperModelType { let model: T enum CodingKeys: String, CodingKey { case model = "data" } } protocol WrapperModelType: Codable { associatedtype ModelType: Codable var model: ModelType { get } } extension URLSession { // FIXME: Implement properly func request(_ urlString: String, method: HTTPMethod = .get, parameters: [String: Any]? = nil, headers: [String: String]? = nil) -> URLRequest { let url: URL if method == .get { url = URL(string: urlString + "?" + generateQueryString(from: parameters))! } else { url = URL(string: urlString)! } var request = URLRequest(url: url) request.httpMethod = method.rawValue request.allHTTPHeaderFields = headers return request } func dataTask<T: Codable>(with request: URLRequest, convertFromSnakeCase: Bool, completionHandler: @escaping (Result<T>) -> Void) -> URLSessionDataTask { let handler = dataHandler(convertFromSnakeCase: convertFromSnakeCase, handler: completionHandler) let task = dataTask(with: request, completionHandler: handler) return task } @discardableResult func startDataTask<T: Codable>(with request: URLRequest, convertFromSnakeCase: Bool, completionHandler: @escaping (Result<T>) -> Void) -> URLSessionDataTask { let task = dataTask(with: request, convertFromSnakeCase: convertFromSnakeCase, completionHandler: completionHandler) task.resume() return task } func dataTask<T: WrapperModelType>(with request: URLRequest, wrapperType: T.Type, convertFromSnakeCase: Bool, completionHandler: @escaping (Result<T.ModelType>) -> Void) -> URLSessionDataTask { let handler = dataHandler(convertFromSnakeCase: convertFromSnakeCase, handler: completionHandler, wrapperType: wrapperType) let task = dataTask(with: request, completionHandler: handler) return task } @discardableResult func startDataTask<T: WrapperModelType>(with request: URLRequest, wrapperType: T.Type, convertFromSnakeCase: Bool, completionHandler: @escaping (Result<T.ModelType>) -> Void) -> URLSessionDataTask { let task = dataTask(with: request, wrapperType: wrapperType, convertFromSnakeCase: convertFromSnakeCase, completionHandler: completionHandler) task.resume() return task } private func dataHandler<T: Codable>( convertFromSnakeCase: Bool, handler: @escaping (Result<T>) -> Void) -> ((Data?, URLResponse?, Error?) -> Void) { return { data, response, error in do { let data = try self.validate(data, response, error) let decoder = JSONDecoder() if convertFromSnakeCase { decoder.keyDecodingStrategy = .convertFromSnakeCase } let decoded = try decoder.decode(T.self, from: data) handler(Result.success(decoded)) } catch { handler(.failure(error)) } } } private func dataHandler<T: WrapperModelType>( convertFromSnakeCase: Bool, handler: @escaping (Result<T.ModelType>) -> Void, wrapperType: T.Type) -> ((Data?, URLResponse?, Error?) -> Void) { return { data, response, error in do { let data = try self.validate(data, response, error) let decoder = JSONDecoder() if convertFromSnakeCase { decoder.keyDecodingStrategy = .convertFromSnakeCase } let parentData = try decoder.decode(wrapperType, from: data) handler(Result.success(parentData.model)) } catch { handler(.failure(error)) } } } private func validate(_ data: Data?, _ response: URLResponse?, _ error: Error?) throws -> Data { // FIXME: Finish this guard let response = response as? HTTPURLResponse else { throw NSError(domain: "", code: 0, userInfo: nil) } switch HTTPStatusCode(rawValue: response.statusCode)! { case .ok: // Success guard let data = data else { throw NSError(domain: "", code: 0, userInfo: nil) } return data default: if let data = data, let message = String(data: data, encoding: .utf8) { throw NSError(domain: "", code: response.statusCode, userInfo: ["response": message]) } let error = NSError(domain: "", code: 0, userInfo: nil) throw error } } // MARK: - Helper function private func generateQueryString(from parameters: [String: Any?]?) -> String { guard let parameters = parameters else { return "" } var queryString = "" parameters.forEach { item in if let value = item.value { queryString += "\(item.key)=\(value)&" } } if queryString.last != nil { queryString.removeLast() } //plus was turning into white space when turned into data queryString = queryString.replacingOccurrences(of: "+", with: "%2B") return queryString } }
mit
50e84c218d0f3e806369009986809fea
37.17284
154
0.551746
5.501779
false
false
false
false
FraDeliro/ISaMaterialLogIn
Example/Pods/Material/Sources/iOS/CollectionReusableView.swift
1
9124
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(CollectionReusableView) open class CollectionReusableView: UICollectionReusableView, Pulseable { /** A CAShapeLayer used to manage elements that would be affected by the clipToBounds property of the backing layer. For example, this allows the dropshadow effect on the backing layer, while clipping the image to a desired shape within the visualLayer. */ open let visualLayer = CAShapeLayer() /// A Pulse reference. fileprivate var pulse: Pulse! /// PulseAnimation value. open var pulseAnimation: PulseAnimation { get { return pulse.animation } set(value) { pulse.animation = value } } /// PulseAnimation color. @IBInspectable open var pulseColor: UIColor { get { return pulse.color } set(value) { pulse.color = value } } /// Pulse opacity. @IBInspectable open var pulseOpacity: CGFloat { get { return pulse.opacity } set(value) { pulse.opacity = value } } /** A property that manages an image for the visualLayer's contents property. Images should not be set to the backing layer's contents property to avoid conflicts when using clipsToBounds. */ @IBInspectable open var image: UIImage? { didSet { visualLayer.contents = image?.cgImage } } /** Allows a relative subrectangle within the range of 0 to 1 to be specified for the visualLayer's contents property. This allows much greater flexibility than the contentsGravity property in terms of how the image is cropped and stretched. */ @IBInspectable open var contentsRect: CGRect { get { return visualLayer.contentsRect } set(value) { visualLayer.contentsRect = value } } /** A CGRect that defines a stretchable region inside the visualLayer with a fixed border around the edge. */ @IBInspectable open var contentsCenter: CGRect { get { return visualLayer.contentsCenter } set(value) { visualLayer.contentsCenter = value } } /** A floating point value that defines a ratio between the pixel dimensions of the visualLayer's contents property and the size of the view. By default, this value is set to the Screen.scale. */ @IBInspectable open var contentsScale: CGFloat { get { return visualLayer.contentsScale } set(value) { visualLayer.contentsScale = value } } /// A Preset for the contentsGravity property. open var contentsGravityPreset: Gravity { didSet { contentsGravity = GravityToValue(gravity: contentsGravityPreset) } } /// Determines how content should be aligned within the visualLayer's bounds. @IBInspectable open var contentsGravity: String { get { return visualLayer.contentsGravity } set(value) { visualLayer.contentsGravity = value } } /// A preset wrapper around contentEdgeInsets. open var contentEdgeInsetsPreset: EdgeInsetsPreset { get { return grid.contentEdgeInsetsPreset } set(value) { grid.contentEdgeInsetsPreset = value } } /// A reference to EdgeInsets. @IBInspectable open var contentEdgeInsets: UIEdgeInsets { get { return grid.contentEdgeInsets } set(value) { grid.contentEdgeInsets = value } } /// A preset wrapper around interimSpace. open var interimSpacePreset = InterimSpacePreset.none { didSet { interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset) } } /// A wrapper around grid.interimSpace. @IBInspectable open var interimSpace: InterimSpace { get { return grid.interimSpace } set(value) { grid.interimSpace = value } } /// A property that accesses the backing layer's background @IBInspectable open override var backgroundColor: UIColor? { didSet { layer.backgroundColor = backgroundColor?.cgColor } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { contentsGravityPreset = .resizeAspectFill super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { contentsGravityPreset = .resizeAspectFill super.init(frame: frame) prepare() } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } open override func layoutSubviews() { super.layoutSubviews() layoutShape() layoutVisualLayer() layoutShadowPath() } /** Triggers the pulse animation. - Parameter point: A Optional point to pulse from, otherwise pulses from the center. */ open func pulse(point: CGPoint? = nil) { let p = point ?? center pulse.expandAnimation(point: p) Motion.delay(time: 0.35) { [weak self] in self?.pulse.contractAnimation() } } /** A delegation method that is executed when the view has began a touch event. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) pulse.expandAnimation(point: layer.convert(touches.first!.location(in: self), from: layer)) } /** A delegation method that is executed when the view touch event has ended. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) pulse.contractAnimation() } /** A delegation method that is executed when the view touch event has been cancelled. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) pulse.contractAnimation() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { contentScaleFactor = Screen.scale prepareVisualLayer() preparePulse() } } extension CollectionReusableView { /// Prepares the pulse motion. fileprivate func preparePulse() { pulse = Pulse(pulseView: self, pulseLayer: visualLayer) pulseAnimation = .none } /// Prepares the visualLayer property. fileprivate func prepareVisualLayer() { visualLayer.zPosition = 0 visualLayer.masksToBounds = true layer.addSublayer(visualLayer) } } extension CollectionReusableView { /// Manages the layout for the visualLayer property. fileprivate func layoutVisualLayer() { visualLayer.frame = bounds visualLayer.cornerRadius = cornerRadius } }
mit
ea9a4800ef69b5d0b4c33ad1af8bc00e
27.873418
99
0.68413
4.67418
false
false
false
false
DianQK/LearnRxSwift
LearnRxSwift/Supports/SupportFunction.swift
1
3062
// // SupportFunction.swift // LearnRxSwift // // Created by DianQK on 16/2/26. // Copyright © 2016年 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa #if DEBUG let host = "https://stg-rxswift.leanapp.cn" #else let host = "https://rxswift.leanapp.cn" #endif struct Alert { static func showInfo(title: String, message: String? = nil) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default) { _ in }) UIApplication.topViewController()?.presentViewController(alertController, animated: true, completion: nil) } static func rx_showInfo(title: String, message: String? = nil) -> Observable<UIAlertActionStyle> { return Observable.create { observer in let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default) { action in observer.on(.Next(action.style)) }) UIApplication.topViewController()?.presentViewController(alertController, animated: true, completion: nil) return NopDisposable.instance } } } extension UIApplication { class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = base?.presentedViewController { return topViewController(presented) } return base } public var rx_networkActivityIndicatorVisible: AnyObserver<Bool> { return AnyObserver { event in MainScheduler.ensureExecutingOnScheduler() switch event { case .Next(let value): self.networkActivityIndicatorVisible = value case .Error: self.networkActivityIndicatorVisible = false break case .Completed: break } } } } extension UITableView { public func rx_modelItemSelected<T>(modelType: T.Type) -> ControlEvent<(model: T, item: NSIndexPath)> { let source: Observable<(model: T, item: NSIndexPath)> = rx_itemSelected.flatMap { [weak self] indexPath -> Observable<(model: T, item: NSIndexPath)> in guard let view = self else { return Observable.empty() } return Observable.just((model: try view.rx_modelAtIndexPath(indexPath), item: indexPath)) } return ControlEvent(events: source) } }
mit
bf2a27c5477c0337c196965dc4ad7bbb
32.615385
159
0.61981
5.292388
false
false
false
false
PonyGroup/PonyChatUI-Swift
PonyChatUI/Classes/Application Interface/Manager/ImageDownloadManager.swift
1
1595
// // ImageDownloadManager.swift // PonyChatUIProject // // Created by 崔 明辉 on 15/10/28. // // import Foundation import AsyncDisplayKit import SDWebImage extension PonyChatUI { class ImageDownloadManager: NSObject, ASImageDownloaderProtocol { private static let sharedInstance = ImageDownloadManager() internal class var sharedManager: ImageDownloadManager { return sharedInstance } func downloadImageWithURL(URL: NSURL!, callbackQueue: dispatch_queue_t!, downloadProgressBlock: ((CGFloat) -> Void)!, completion: ((CGImage!, NSError!) -> Void)!) -> AnyObject! { let options: SDWebImageOptions = SDWebImageOptions.RetryFailed let operation = SDWebImageManager.sharedManager().downloadImageWithURL(URL, options: options, progress: nil) { (theImage, theError, _, _, _) -> Void in if theImage != nil { dispatch_async(callbackQueue, { () -> Void in completion(theImage.CGImage, theError) }) } else { dispatch_async(callbackQueue, { () -> Void in completion(nil, theError) }) } } return operation } func cancelImageDownloadForIdentifier(downloadIdentifier: AnyObject!) { if let downloadIdentifier = downloadIdentifier as? SDWebImageOperation { downloadIdentifier.cancel() } } } }
mit
9847d891ab14492ed657d72eb0c9150f
32.125
186
0.569541
5.863469
false
false
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/Common/Nodes/Input/AKMicrophone.swift
1
1484
// // AKMicrophone.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// Audio from the standard input public class AKMicrophone: AKNode, AKToggleable { internal let mixer = AVAudioMixerNode() /// Output Volume (Default 1) public var volume: Double = 1.0 { didSet { if volume < 0 { volume = 0 } mixer.outputVolume = Float(volume) } } private var lastKnownVolume: Double = 1.0 /// Determine if the microphone is currently on. public var isStarted: Bool { return volume != 0.0 } /// Initialize the microphone public override init() { #if !os(tvOS) super.init() self.avAudioNode = mixer AKSettings.audioInputEnabled = true AudioKit.engine.attachNode(mixer) AudioKit.engine.connect(AudioKit.engine.inputNode!, to: self.avAudioNode, format: nil) #endif } /// Function to start, play, or activate the node, all do the same thing public func start() { if isStopped { volume = lastKnownVolume } } /// Function to stop or bypass the node, both are equivalent public func stop() { if isPlaying { lastKnownVolume = volume volume = 0 } } }
apache-2.0
d6fc7ce4f49f0ca216d2b686f20b0181
24.135593
98
0.576534
4.846405
false
false
false
false
darina/omim
iphone/Chart/Chart/Views/ChartView.swift
5
12064
import UIKit enum ChartAnimation: TimeInterval { case none = 0.0 case animated = 0.3 case interactive = 0.1 } public class ChartView: UIView { let chartsContainerView = ExpandedTouchView() let chartPreviewView = ChartPreviewView() let yAxisView = ChartYAxisView() let xAxisView = ChartXAxisView() let chartInfoView = ChartInfoView() var lineViews: [ChartLineView] = [] private var panStartPoint = 0 private var panGR: UIPanGestureRecognizer! private var pinchStartLower = 0 private var pinchStartUpper = 0 private var pinchGR: UIPinchGestureRecognizer! public var myPosition: Double = -1 { didSet { setMyPosition(myPosition) } } public var previewSelectorColor: UIColor = UIColor.lightGray.withAlphaComponent(0.9) { didSet { chartPreviewView.selectorColor = previewSelectorColor } } public var previewTintColor: UIColor = UIColor.lightGray.withAlphaComponent(0.5) { didSet { chartPreviewView.selectorTintColor = previewTintColor } } public var infoBackgroundColor: UIColor = UIColor.white { didSet { chartInfoView.infoBackgroundColor = infoBackgroundColor yAxisView.textBackgroundColor = infoBackgroundColor.withAlphaComponent(0.7) } } public var infoShadowColor: UIColor = UIColor.black { didSet { chartInfoView.infoShadowColor = infoShadowColor } } public var infoShadowOpacity: Float = 0.25 { didSet { chartInfoView.infoShadowOpacity = infoShadowOpacity } } public var font: UIFont = UIFont.systemFont(ofSize: 12, weight: .regular) { didSet { xAxisView.font = font yAxisView.font = font chartInfoView.font = font } } public var textColor: UIColor = UIColor(white: 0, alpha: 0.2) { didSet { xAxisView.textColor = textColor yAxisView.textColor = textColor chartInfoView.textColor = textColor } } public var gridColor: UIColor = UIColor(white: 0, alpha: 0.2) { didSet { yAxisView.gridColor = gridColor } } public override var backgroundColor: UIColor? { didSet { chartInfoView.tooltipBackgroundColor = backgroundColor ?? .white } } public var chartData: ChartPresentationData! { didSet { lineViews.forEach { $0.removeFromSuperview() } lineViews.removeAll() for i in (0..<chartData.linesCount).reversed() { let line = chartData.lineAt(i) let v = ChartLineView() v.clipsToBounds = true v.chartLine = line v.lineWidth = 3 v.frame = chartsContainerView.bounds v.autoresizingMask = [.flexibleWidth, .flexibleHeight] chartsContainerView.addSubview(v) lineViews.insert(v, at: 0) } yAxisView.frame = chartsContainerView.bounds yAxisView.autoresizingMask = [.flexibleWidth, .flexibleHeight] yAxisView.transform = CGAffineTransform.identity.scaledBy(x: 1, y: -1) chartsContainerView.addSubview(yAxisView) chartInfoView.frame = chartsContainerView.bounds chartInfoView.autoresizingMask = [.flexibleWidth, .flexibleHeight] chartInfoView.delegate = self chartInfoView.textColor = textColor chartsContainerView.addSubview(chartInfoView) xAxisView.values = chartData.labels chartPreviewView.chartData = chartData xAxisView.setBounds(lower: chartPreviewView.minX, upper: chartPreviewView.maxX) updateCharts() } } public typealias OnSelectedPointChangedClosure = (_ px: CGFloat) -> Void public var onSelectedPointChanged: OnSelectedPointChangedClosure? override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { xAxisView.font = font xAxisView.textColor = textColor yAxisView.font = font yAxisView.textColor = textColor yAxisView.gridColor = textColor chartInfoView.font = font chartPreviewView.selectorTintColor = previewTintColor chartPreviewView.selectorColor = previewSelectorColor chartInfoView.tooltipBackgroundColor = backgroundColor ?? .white yAxisView.textBackgroundColor = infoBackgroundColor.withAlphaComponent(0.7) panGR = UIPanGestureRecognizer(target: self, action: #selector(onPan(_:))) chartsContainerView.addGestureRecognizer(panGR) pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(onPinch(_:))) chartsContainerView.addGestureRecognizer(pinchGR) addSubview(chartsContainerView) addSubview(chartPreviewView) chartPreviewView.delegate = self addSubview(xAxisView) } public func setSelectedPoint(_ x: Double) { let routeLength = chartData.xAxisValueAt(CGFloat(chartData.pointsCount - 1)) let upper = chartData.xAxisValueAt(CGFloat(chartPreviewView.maxX)) var lower = chartData.xAxisValueAt(CGFloat(chartPreviewView.minX)) let rangeLength = upper - lower if x < lower || x > upper { let current = Double(chartInfoView.infoX) * rangeLength + lower let dx = x - current let dIdx = Int(dx / routeLength * Double(chartData.pointsCount)) var lowerIdx = chartPreviewView.minX + dIdx var upperIdx = chartPreviewView.maxX + dIdx if lowerIdx < 0 { upperIdx -= lowerIdx lowerIdx = 0 } else if upperIdx >= chartData.pointsCount { lowerIdx -= upperIdx - chartData.pointsCount - 1 upperIdx = chartData.pointsCount - 1 } chartPreviewView.setX(min: lowerIdx, max: upperIdx) lower = chartData.xAxisValueAt(CGFloat(chartPreviewView.minX)) } chartInfoView.infoX = CGFloat((x - lower) / rangeLength) } fileprivate func setMyPosition(_ x: Double) { let upper = chartData.xAxisValueAt(CGFloat(chartPreviewView.maxX)) let lower = chartData.xAxisValueAt(CGFloat(chartPreviewView.minX)) let rangeLength = upper - lower chartInfoView.myPositionX = CGFloat((x - lower) / rangeLength) } override public func layoutSubviews() { super.layoutSubviews() let previewFrame = CGRect(x: bounds.minX, y: bounds.maxY - 30, width: bounds.width, height: 30) chartPreviewView.frame = previewFrame let xAxisFrame = CGRect(x: bounds.minX, y: bounds.maxY - previewFrame.height - 26, width: bounds.width, height: 26) xAxisView.frame = xAxisFrame let chartsFrame = CGRect(x: bounds.minX, y: bounds.minY, width: bounds.width, height: bounds.maxY - previewFrame.height - xAxisFrame.height) chartsContainerView.frame = chartsFrame } override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let rect = bounds.insetBy(dx: -30, dy: 0) return rect.contains(point) } @objc func onPinch(_ sender: UIPinchGestureRecognizer) { if sender.state == .began { pinchStartLower = xAxisView.lowerBound pinchStartUpper = xAxisView.upperBound } if sender.state != .changed { return } let rangeLength = CGFloat(pinchStartUpper - pinchStartLower) let dx = Int(round((rangeLength * sender.scale - rangeLength) / 2)) let lower = max(pinchStartLower + dx, 0) let upper = min(pinchStartUpper - dx, chartData.labels.count - 1) if upper - lower < chartData.labels.count / 10 { return } chartPreviewView.setX(min: lower, max: upper) xAxisView.setBounds(lower: lower, upper: upper) updateCharts(animationStyle: .none) chartInfoView.update() } @objc func onPan(_ sender: UIPanGestureRecognizer) { let t = sender.translation(in: chartsContainerView) if sender.state == .began { panStartPoint = xAxisView.lowerBound } if sender.state != .changed { return } let dx = Int(round(t.x / chartsContainerView.bounds.width * CGFloat(xAxisView.upperBound - xAxisView.lowerBound))) let lower = panStartPoint - dx let upper = lower + xAxisView.upperBound - xAxisView.lowerBound if lower < 0 || upper > chartData.labels.count - 1 { return } chartPreviewView.setX(min: lower, max: upper) xAxisView.setBounds(lower: lower, upper: upper) updateCharts(animationStyle: .none) chartInfoView.update() } func updateCharts(animationStyle: ChartAnimation = .none) { var lower = CGFloat(Int.max) var upper = CGFloat(Int.min) for i in 0..<chartData.linesCount { let line = chartData.lineAt(i) let subrange = line.aggregatedValues[xAxisView.lowerBound...xAxisView.upperBound] subrange.forEach { upper = max($0, upper) if line.type == .line || line.type == .lineArea { lower = min($0, lower) } } } let padding = round((upper - lower) / 10) lower = max(0, lower - padding) upper = upper + padding let stepsCount = 3 let step = ceil((upper - lower) / CGFloat(stepsCount)) upper = lower + step * CGFloat(stepsCount) var steps: [CGFloat] = [] for i in 0...stepsCount { steps.append(lower + step * CGFloat(i)) } if yAxisView.upperBound != upper || yAxisView.lowerBound != lower { yAxisView.setBounds(lower: lower, upper: upper, lowerLabel: chartData.formatter.altitudeString(from: Double(lower)), upperLabel: chartData.formatter.altitudeString(from: Double(upper)), steps: steps, animationStyle: animationStyle) } lineViews.forEach { $0.setViewport(minX: xAxisView.lowerBound, maxX: xAxisView.upperBound, minY: lower, maxY: upper, animationStyle: animationStyle) } } } extension ChartView: ChartPreviewViewDelegate { func chartPreviewView(_ view: ChartPreviewView, didChangeMinX minX: Int, maxX: Int) { xAxisView.setBounds(lower: minX, upper: maxX) updateCharts(animationStyle: .none) chartInfoView.update() setMyPosition(myPosition) let x = chartInfoView.infoX * CGFloat(xAxisView.upperBound - xAxisView.lowerBound) + CGFloat(xAxisView.lowerBound) onSelectedPointChanged?(x) } } extension ChartView: ChartInfoViewDelegate { func chartInfoView(_ view: ChartInfoView, didMoveToPoint pointX: CGFloat) { let p = convert(CGPoint(x: pointX, y: 0), from: view) let x = (p.x / bounds.width) * CGFloat(xAxisView.upperBound - xAxisView.lowerBound) + CGFloat(xAxisView.lowerBound) onSelectedPointChanged?(x) } func chartInfoView(_ view: ChartInfoView, didCaptureInfoView captured: Bool) { panGR.isEnabled = !captured } func chartInfoView(_ view: ChartInfoView, infoAtPointX pointX: CGFloat) -> (String, [ChartLineInfo])? { let p = convert(CGPoint(x: pointX, y: 0), from: view) let x = (p.x / bounds.width) * CGFloat(xAxisView.upperBound - xAxisView.lowerBound) + CGFloat(xAxisView.lowerBound) let x1 = Int(floor(x)) let x2 = Int(ceil(x)) guard x1 < chartData.labels.count && x >= 0 else { return nil } let label = chartData.labelAt(x) var result: [ChartLineInfo] = [] for i in 0..<chartData.linesCount { let line = chartData.lineAt(i) guard line.type != .lineArea else { continue } let y1 = line.values[x1] let y2 = line.values[x2] let dx = x - CGFloat(x1) let y = dx * (y2 - y1) + y1 let py = round(chartsContainerView.bounds.height * CGFloat(y - yAxisView.lowerBound) / CGFloat(yAxisView.upperBound - yAxisView.lowerBound)) let v1 = line.originalValues[x1] let v2 = line.originalValues[x2] let v = round(dx * CGFloat(v2 - v1)) + CGFloat(v1) result.append(ChartLineInfo(name: line.name, color: line.color, point: chartsContainerView.convert(CGPoint(x: p.x, y: py), to: view), formattedValue: chartData.formatter.altitudeString(from: Double(v)))) } return (label, result) } }
apache-2.0
cd5ca211d56c4cca0d619a828751b9b6
32.88764
119
0.668021
4.513281
false
false
false
false
apple/swift
test/TypeDecoder/typealias.swift
31
3415
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-executable %s -g -o %t/typealias -emit-module // RUN: sed -ne '/\/\/ *DEMANGLE-TYPE: /s/\/\/ *DEMANGLE-TYPE: *//p' < %s > %t/input // RUN: %lldb-moduleimport-test-with-sdk %t/typealias -type-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-TYPE // RUN: sed -ne '/\/\/ *DEMANGLE-DECL: /s/\/\/ *DEMANGLE-DECL: *//p' < %s > %t/input // RUN: %lldb-moduleimport-test-with-sdk %t/typealias -decl-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-DECL typealias Alias = Int struct Outer { typealias Alias = Int struct Inner { typealias Alias = Int } } struct GenericOuter<T> { typealias Alias = Int struct Inner { typealias Alias = Int } } protocol Proto { typealias Alias = Int } extension Proto { typealias OtherAlias = Int } extension GenericOuter where T : Proto { typealias ConditionalAlias = Int } struct Conforms : Proto {} func blackHole(_: Any...) {} do { let x1: Alias = 0 let x2: Outer.Alias = 0 let x3: Outer.Inner.Alias = 0 blackHole(x1, x2, x3) } do { let x1: GenericOuter<Int>.Alias = 0 let x2: GenericOuter<Int>.Inner.Alias = 0 blackHole(x1, x2) } do { // Note that the first two are not sugared because of representational issues. let x1: Proto.Alias = 0 let x2: Proto.OtherAlias = 0 let x3: Conforms.Alias = 0 let x4: Conforms.OtherAlias = 0 blackHole(x1, x2, x3, x4) } func generic<T : Proto>(_: T) { let x1: T.Alias = 0 let x2: T.OtherAlias = 0 blackHole(x1, x2) } do { let x1: GenericOuter<Conforms>.ConditionalAlias = 0 blackHole(x1) } // DEMANGLE-TYPE: $s9typealias5AliasaD // DEMANGLE-TYPE: $s9typealias5OuterV5AliasaD // DEMANGLE-TYPE: $s9typealias5OuterV5InnerV5AliasaD // CHECK-TYPE: Alias // CHECK-TYPE: Outer.Alias // CHECK-TYPE: Outer.Inner.Alias // DEMANGLE-TYPE: $s9typealias12GenericOuterV5AliasaySi_GD // DEMANGLE-TYPE: $s9typealias12GenericOuterV5InnerV5AliasaySi__GD // CHECK-TYPE: GenericOuter<Int>.Alias // CHECK-TYPE: GenericOuter<Int>.Inner.Alias // DEMANGLE-TYPE: $s9typealias5ProtoP5AliasayAA8ConformsV_GD // DEMANGLE-TYPE: $s9typealias5ProtoPAAE10OtherAliasayAA8ConformsV_GD // CHECK-TYPE: Conforms.Alias // CHECK-TYPE: Conforms.OtherAlias // DEMANGLE-TYPE: $s9typealias5ProtoP5Aliasayx_GD // DEMANGLE-TYPE: $s9typealias5ProtoPAAE10OtherAliasayx_GD // CHECK-TYPE: τ_0_0.Alias // CHECK-TYPE: τ_0_0.OtherAlias // DEMANGLE-TYPE: $s9typealias12GenericOuterVA2A5ProtoRzlE16ConditionalAliasayAA8ConformsV_GD // CHECK-TYPE: GenericOuter<Conforms>.ConditionalAlias // DEMANGLE-DECL: $s9typealias5Aliasa // DEMANGLE-DECL: $s9typealias5OuterV5Aliasa // DEMANGLE-DECL: $s9typealias5OuterV5InnerV5Aliasa // DEMANGLE-DECL: $s9typealias12GenericOuterV5Aliasa // DEMANGLE-DECL: $s9typealias12GenericOuterV5InnerV5Aliasa // DEMANGLE-DECL: $s9typealias5ProtoP5Aliasa // DEMANGLE-DECL: $s9typealias5ProtoPAAE10OtherAliasa // DEMANGLE-DECL: $s9typealias12GenericOuterVA2A5ProtoRzlE16ConditionalAliasa // CHECK-DECL: typealias.(file).Alias // CHECK-DECL: typealias.(file).Outer.Alias // CHECK-DECL: typealias.(file).Outer.Inner.Alias // CHECK-DECL: typealias.(file).GenericOuter.Alias // CHECK-DECL: typealias.(file).GenericOuter.Inner.Alias // CHECK-DECL: typealias.(file).Proto.Alias // CHECK-DECL: typealias.(file).Proto extension.OtherAlias // CHECK-DECL: typealias.(file).GenericOuter extension.ConditionalAlias
apache-2.0
2ff029a778253ecfa88deea3ebab12f8
25.061069
123
0.729563
3.210724
false
false
false
false
vitkuzmenko/TableCollectionStructured
Source/Managers/TableStructuredController.swift
1
13319
// // TableStructuredViewController.swift // TableCollectionStructured // // Created by Vitaliy Kuzmenko on 06/10/16. // Copyright © 2016 Vitaliy Kuzmenko. All rights reserved. // import UIKit open class TableStructuredController: NSObject, UITableViewDataSource, UITableViewDelegate { @IBOutlet open weak var tableView: UITableView! { didSet { tableView.dataSource = self tableView.delegate = self configureTableView() } } open var structure: [StructuredSection] = [] open var shouldReloadData: Bool { return true } private var previousStructure: [StructuredSection] = [] { didSet { structure.forEach { section in section.rows.forEach { object in if let invalidatableCell = object.value as? StructuredCellInvalidatable { invalidatableCell.invalidated() } } } } } open func indexPath<T: StructuredCell>(for object: T) -> IndexPath? { let obj = StructuredObject(value: object) return structure.indexPath(of: obj) } open func isSafe(indexPath: IndexPath) -> Bool { if structure.isEmpty { return false } else if structure.count - 1 >= indexPath.section { if structure[indexPath.section].isEmpty { return false } else if structure[indexPath.section].count - 1 >= indexPath.row { return true } } return false } open func object(at indexPath: IndexPath) -> Any { return structure[indexPath.section][indexPath.row] } open func set(structure: [StructuredSection], animation: UITableView.RowAnimation = .fade) { beginBuilding() self.structure = structure buildStructure(with: animation) } open func beginBuilding() { previousStructure = structure structure = [] } open func newSection(identifier: String? = nil) -> StructuredSection { return StructuredSection(identifier: identifier) } open func append(section: StructuredSection) { section.isClosed = true if structure.contains(section) { fatalError("TableCollectionStructured: Table structure is contains section with \"\(section.identifier!)\" identifier") } if section.identifier == nil { section.identifier = String(format: "#Section%d", structure.count) } for _section in structure { for row in section.rows { if _section.rows.contains(where: { (obj) -> Bool in return obj == row }) { } } } structure.append(section) } open func append(section: inout StructuredSection, new identifier: String? = nil) { append(section: section) section = StructuredSection(identifier: identifier) } open func configureTableView() { tableView.tableFooterView = UIView() } open func buildStructure(with animation: UITableView.RowAnimation? = nil) { if let animation = animation { self.performReload(with: animation) } } open func reloadData() { tableView.reloadData() } var queue: Int = 0 open func performReload(with animation: UITableView.RowAnimation = .fade) { if animation == .none { if shouldReloadData { reloadData() } return } let diff = StructuredDifference(from: previousStructure, to: structure) if !diff.reloadConstraint.isEmpty || tableView.window == nil { return reloadData() } CATransaction.begin() tableView.beginUpdates() if shouldReloadData { CATransaction.setCompletionBlock { [weak self] in self?.tableView?.reloadData() } } for movement in diff.sectionsToMove { tableView.moveSection(movement.from, toSection: movement.to) } if !diff.sectionsToDelete.isEmpty { tableView.deleteSections(diff.sectionsToDelete, with: animation) } if !diff.sectionsToInsert.isEmpty { tableView.insertSections(diff.sectionsToInsert, with: animation) } for movement in diff.rowsToMove { tableView.moveRow(at: movement.from, to: movement.to) } if !diff.rowsToDelete.isEmpty { tableView.deleteRows(at: diff.rowsToDelete, with: animation) } if !diff.rowsToInsert.isEmpty { tableView.insertRows(at: diff.rowsToInsert, with: animation) } tableView.endUpdates() CATransaction.commit() } public func numberOfSections(in tableView: UITableView) -> Int { return structure.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return structure[section].count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let model = object(at: indexPath) as? StructuredCell else { fatalError("Model should be StructuredCellModelProtocol") } let cell = tableView.dequeueReusableCell(withModel: model, for: indexPath) return cell } @available(*, deprecated, message: "deprecated") open func tableView(_ tableView: UITableView, reuseIdentifierFor object: Any) -> String? { fatalError("Depreacted") } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return structure[section].headerTitle } public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return structure[section].footerTitle } @available(*, deprecated, message: "deprecated") open func tableView(_ tableView: UITableView, configure cell: UITableViewCell, for object: Any, at indexPath: IndexPath) { } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let object = self.object(at: indexPath) as? StructuredCellWillDisplay { object.willDisplay?() } } // @available(*, deprecated, message: "") // open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, for object: Any) { // // } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let object = self.object(at: indexPath) as? StructuredCellDynamicHeight { return object.height(for: tableView) } else { return tableView.rowHeight } } @available(*, deprecated, message: "deprecated") open func rowHeight(forIdentifier identifier: String) -> CGFloat { return tableView.rowHeight } @available(*, deprecated, message: "deprecated") open func rowHeight(forObject object: Any) -> CGFloat { if let object = object as? String { return rowHeight(forIdentifier: object) } return tableView.rowHeight } open var automaticallyDeselect: Bool { return true } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let object = self.object(at: indexPath) as? StructuredCellSelectable, let cell = tableView.cellForRow(at: indexPath) { if let deselect = object.didSelect?(cell), deselect { self.tableView.deselectRow(at: indexPath, animated: false) } } } @available(*, deprecated, message: "deprecated") open func tableView(_ tableView: UITableView, didSelect cell: UITableViewCell, with identifier: String, object: Any, at indexPath: IndexPath) { } public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if let object = self.object(at: indexPath) as? StructuredCellDeselectable { object.didDeselect?() } } @available(*, deprecated, message: "deprecated") open func tableView(_ tableView: UITableView, didDeselect cell: UITableViewCell, with identifier: String, object: Any, at indexPath: IndexPath) { } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let object = self.object(at: indexPath) return self.tableView(tableView, canEditRowWith: object, at: indexPath) } open func tableView(_ tableView: UITableView, canEditRowWith object: Any, at indexPath: IndexPath) -> Bool { return false } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { let object = self.object(at: indexPath) self.tableView(tableView, commit: editingStyle, for: object, forRowAt: indexPath) } open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, for object: Any, forRowAt indexPath: IndexPath) { } public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { let object = self.object(at: indexPath) return self.tableView(tableView, canMove: object, at: indexPath) } open func tableView(_ tableView: UITableView, canMove object: Any, at indexPath: IndexPath) -> Bool { return false } public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let object = self.object(at: sourceIndexPath) self.tableView(tableView, move: object, from: sourceIndexPath, to: destinationIndexPath) } open func tableView(_ tableView: UITableView, move object: Any, from sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { } open func reloadRows<T: StructuredCell>(objects: [T], with animation: UITableView.RowAnimation = .fade) { var indexPaths: [IndexPath] = [] for object in objects { if let indexPath = self.indexPath(for: object) { indexPaths.append(indexPath) } } tableView.reloadRows(at: indexPaths, with: animation) } public func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { guard let reuseIdentifier = tableView.cellForRow(at: indexPath)?.reuseIdentifier else { return true } return self.tableView(tableView, canFocus: object(at: indexPath), with: reuseIdentifier, at: indexPath) } open func tableView(_ tableView: UITableView, canFocus object: Any, with identifier: String, at indexPath: IndexPath) -> Bool { return true } open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return nil } open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0 } open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0 } // MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { } open func scrollViewDidZoom(_ scrollView: UIScrollView) { } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { } open func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { } open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { } open func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { } open func viewForZooming(in scrollView: UIScrollView) -> UIView? { return nil } open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { } open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { } open func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { return true } open func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { } open func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) { } }
apache-2.0
a73f1c2b86c089958cbe10452051741a
32.631313
153
0.623667
5.507858
false
false
false
false
debugsquad/nubecero
nubecero/Model/AdminUsersPhotos/MAdminUsersPhotosItemStatusLoading.swift
1
1993
import UIKit class MAdminUsersPhotosItemStatusLoading:MAdminUsersPhotosItemStatus { override init(model:MAdminUsersPhotosItem) { super.init(model:model) DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.getImage() } } override func loadImage() -> UIImage? { return nil } //MARK: private private func getImage() { guard let userId:MSession.UserId = model?.userId, let pictureId:MPhotos.PhotoId = model?.photoId else { let unknownError:String = NSLocalizedString( "MAdminUsersPhotosItemStatusLoading_errorUnknown", comment:"") model?.modeError(error:unknownError) return } let parentUser:String = FStorage.Parent.user.rawValue let pathImage:String = "\(parentUser)/\(userId)/\(pictureId)" FMain.sharedInstance.storage.loadData( path:pathImage) { [weak self] (data:Data?, error:Error?) in guard let dataStrong:Data = data, let image:UIImage = UIImage(data:dataStrong) else { if let errorString:String = error?.localizedDescription { self?.model?.modeError(error:errorString) } else { let unknownError:String = NSLocalizedString( "MAdminUsersPhotosItemStatusLoading_errorUnknown", comment:"") self?.model?.modeError(error:unknownError) } return } self?.model?.modeLoaded(image:image) } } }
mit
06ce7964ce958ff2e352e6dbecf2bb06
25.932432
74
0.483191
5.879056
false
false
false
false
azarovalex/Simple-Ciphers
Theory Of Information, Lab 1/Column.swift
1
5306
// // Column.swift // Theory Of Information, Lab 1 // // Created by Alex Azarov on 20/09/2017. // Copyright © 2017 Alex Azarov. All rights reserved. // import Cocoa func dialogError(question: String, text: String) { let alert = NSAlert() alert.messageText = question alert.informativeText = text alert.alertStyle = .critical alert.addButton(withTitle: "OK") alert.runModal() } class Column: NSViewController { var path: String = "" func browseFile(sender: AnyObject) -> String { let dialog = NSOpenPanel(); dialog.title = "Choose a .txt file"; dialog.showsResizeIndicator = true; dialog.showsHiddenFiles = false; dialog.canChooseDirectories = true; dialog.canCreateDirectories = true; dialog.allowsMultipleSelection = false; dialog.allowedFileTypes = ["txt"]; if (dialog.runModal() == NSApplication.ModalResponse.OK) { let result = dialog.url // Pathname of the file if (result != nil) { path = result!.path return path } } else { // User clicked on "Cancel" return "" } return "" } var fileURL = URL(fileURLWithPath: "/Users/azarovalex/Desktop/Rail Fence/plaintext.txt") @IBOutlet weak var keywordField: NSTextField! @IBOutlet weak var plaintextField: NSTextField! @IBOutlet weak var ciphertextField: NSTextField! @IBOutlet weak var columnsField: NSTextField! var ciphertext = "" var plaintext = "" var keyword = "" var columns = "" override func viewDidLoad() { super.viewDidLoad() } @IBAction func loadText(_ sender: NSButton) { fileURL = URL(fileURLWithPath: browseFile(sender: self)) switch sender.tag { case 1: do { plaintextField.stringValue = try String(contentsOf: fileURL) } catch { dialogError(question: "Failed reading from URL: \(fileURL)", text: "Error: " + error.localizedDescription) } case 2: do { ciphertextField.stringValue = try String(contentsOf: fileURL) } catch { dialogError(question: "Failed reading from URL: \(fileURL)", text: "Error: " + error.localizedDescription) } default: break } } @IBAction func storeText(_ sender: NSButton) { fileURL = URL(fileURLWithPath: browseFile(sender: self)) switch sender.tag { case 1: do { try plaintextField.stringValue.write(to: fileURL, atomically: true, encoding: .utf8) } catch { dialogError(question: "Failed writing to URL \(fileURL)", text: "Error: " + error.localizedDescription) } case 2: do { try ciphertextField.stringValue.write(to: fileURL, atomically: true, encoding: .utf8) } catch { dialogError(question: "Failed writing to URL \(fileURL)", text: "Error: " + error.localizedDescription) } default: break } } @IBAction func encodeBtnPressed(_ sender: Any) { plaintext = plaintextField.stringValue if plaintext == "" { dialogError(question: "Your ciphertext is an empty string!", text: "Error: Nothing to encipher.") return } keyword = keywordField.stringValue keyword = keyword.components(separatedBy: CharacterSet.letters.inverted) .joined() keyword = keyword.uppercased() keywordField.stringValue = keyword keyword = String(cString: SaveSpecialSymbols(keyword)) keywordField.stringValue = keyword if keyword == "" { dialogError(question: "Please, specify the keyword!", text: "Error: No keyword.") return } plaintext = String(cString: SaveSpecialSymbols(plaintext)) ciphertext = String(cString: ColumnEncipher(plaintext, keyword)) columns = String(cString: GetColumns()) columnsField.stringValue = columns ciphertextField.stringValue = ciphertext } @IBAction func decodeBtnPressed(_ sender: Any) { ciphertext = ciphertextField.stringValue guard ciphertext != "" else { dialogError(question: "Your ciphertext is an empty string!", text: "Error: Nothing to encipher.") return } keyword = keywordField.stringValue guard keyword != "" else { dialogError(question: "Your keyword is an empty string!", text: "Error: Nothing to encipher.") return } ciphertext = ciphertext.components(separatedBy: CharacterSet.letters.inverted).joined() plaintext = String(cString: ColumnDecipher(ciphertext, keyword)) plaintextField.stringValue = plaintext ColumnEncipher(plaintext, keyword) columns = String(cString: GetColumns()) columnsField.stringValue = columns } }
mit
25adccfb8ec8a9453e29645b6fed0933
32.575949
122
0.576626
5.140504
false
false
false
false
brentdax/swift
test/SILGen/lying_about_optional_return_objc.swift
2
4190
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -enable-objc-interop -import-objc-header %S/Inputs/block_property_in_objc_class.h -enable-sil-ownership %s | %FileCheck %s // CHECK-LABEL: sil hidden @$s32lying_about_optional_return_objc0C37ChainingForeignFunctionTypeProperties{{[_0-9a-zA-Z]*}}F func optionalChainingForeignFunctionTypeProperties(b: BlockProperty?) { // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() b?.readWriteBlock() // CHECK: enum $Optional _ = b?.readWriteBlock // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() b?.readOnlyBlock() // CHECK: enum $Optional _ = b?.readOnlyBlock // CHECK: unchecked_trivial_bit_cast _ = b?.selector // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() _ = b?.voidReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.voidPointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.opaquePointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.pointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.constPointerReturning() // CHECK: unchecked_trivial_bit_cast _ = b?.selectorReturning() // CHECK: unchecked_ref_cast _ = b?.objectReturning() // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.voidReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.voidPointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.opaquePointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.pointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.constPointerReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.selectorReturning // CHECK: enum $Optional<{{.*}} -> {{.*}}> _ = b?.objectReturning // CHECK-LABEL: debug_value {{.*}} name "dynamic" let dynamic: AnyObject? = b! // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() _ = dynamic?.voidReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafeMutableRawPointer to $Optional _ = dynamic?.voidPointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $OpaquePointer to $Optional _ = dynamic?.opaquePointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafeMutablePointer{{.*}} to $Optional _ = dynamic?.pointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafePointer{{.*}} to $Optional _ = dynamic?.constPointerReturning() // CHECK: unchecked_trivial_bit_cast {{.*}} $Selector to $Optional _ = dynamic?.selectorReturning() // CHECK: unchecked_ref_cast {{.*}} $BlockProperty to $Optional _ = dynamic?.objectReturning() // FIXME: Doesn't opaquely cast the selector result! // C/HECK: unchecked_trivial_bit_cast {{.*}} $Selector to $Optional _ = dynamic?.selector // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> ()>, #Optional.some _ = dynamic?.voidReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafeMutableRawPointer>, #Optional.some _ = dynamic?.voidPointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> OpaquePointer>, #Optional.some _ = dynamic?.opaquePointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafeMutablePointer{{.*}}>, #Optional.some _ = dynamic?.pointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafePointer{{.*}}>, #Optional.some _ = dynamic?.constPointerReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> Selector>, #Optional.some _ = dynamic?.selectorReturning // CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> @owned BlockProperty>, #Optional.some _ = dynamic?.objectReturning // CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $() _ = dynamic?.voidReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.voidPointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.opaquePointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.pointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.constPointerReturning?() // CHECK: unchecked_trivial_bit_cast _ = dynamic?.selectorReturning?() _ = dynamic?.objectReturning?() }
apache-2.0
1be199f0893a96671f7377da37fe501c
40.485149
187
0.631981
4.144411
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Views/PresentAnimator.swift
1
3512
// // PresentAnimator.swift // HiPDA // // Created by leizh007 on 2016/10/15. // Copyright © 2016年 HiPDA. All rights reserved. // import UIKit /// Present转场动画类型 /// /// - present: 展示 /// - dismiss: 消失 enum UIViewControllerTransitioningType { case present case dismiss } class PresentAnimator: NSObject { var duration = 0.4 var transitioningType = UIViewControllerTransitioningType.present } extension PresentAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView containerView.backgroundColor = .black guard let fromView = transitionContext.viewController(forKey: .from)?.view else { return } guard let toView = transitionContext.viewController(forKey: .to)?.view else { return } containerView.addSubview(toView) if transitioningType == .present { containerView.bringSubview(toFront: toView) fromView.layer.anchorPoint = CGPoint(x: 0.5, y: 1) fromView.frame = containerView.bounds fromView.center = CGPoint(x: containerView.bounds.size.width / 2.0, y: containerView.bounds.size.height) fromView.layer.shouldRasterize = true fromView.layer.rasterizationScale = UIScreen.main.scale toView.frame = CGRect(x: 0, y: containerView.bounds.size.height, width: containerView.bounds.size.width, height: containerView.bounds.size.height) var transform = CATransform3DIdentity transform.m34 = -1.0 / 1000 transform = CATransform3DRotate(transform, CGFloat.pi / 16.0, 1.0, 0, 0) UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseInOut, animations: { toView.frame = containerView.bounds fromView.layer.transform = transform }, completion: { _ in fromView.layer.shouldRasterize = false transitionContext.completeTransition(true) }) } else { containerView.bringSubview(toFront: fromView) fromView.frame = containerView.bounds toView.frame = containerView.bounds toView.layer.shouldRasterize = true toView.layer.rasterizationScale = UIScreen.main.scale UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseInOut, animations: { fromView.frame = CGRect(x: 0, y: containerView.bounds.size.height, width: containerView.bounds.size.width, height: containerView.bounds.size.height) toView.layer.transform = CATransform3DIdentity }, completion: { _ in toView.setNeedsUpdateConstraints() toView.layoutIfNeeded() toView.layer.shouldRasterize = false containerView.backgroundColor = .white transitionContext.completeTransition(true) }) } } }
mit
86e64f01eba0ed002cbf014564cd3bef
39.569767
109
0.599599
5.5824
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Storyboard/UIFont+Storyboard.swift
1
1363
// // UIFont+Storyboard.swift // APExtensions // // Created by Anton Plebanovich on 6/20/17. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import UIKit import RoutableLogger public extension UIFont { /// Returns screen scaled font. Assuming source font is for 2208x1242 screen. var screenFitFont: UIFont { var newFontSize = pointSize * c.screenResizeCoef newFontSize = newFontSize.rounded() return UIFont(descriptor: fontDescriptor, size: newFontSize) } /// Returns scalable font depending on device content size category @available(iOS 11.0, *) var scalable: UIFont { let style: UIFont.TextStyle switch pointSize { case 34...: style = .largeTitle case 28..<34: style = .title1 case 22..<28: style = .title2 case 20..<22: style = .title3 case 17..<20: style = .body case 16..<17: style = .callout case 15..<16: style = .subheadline case 13..<15: style = .footnote case 12..<13: style = .caption1 case ..<12: style = .caption2 default: RoutableLogger.logError("Unexpected default case", data: ["pointSize": pointSize]) style = .body } return UIFontMetrics(forTextStyle: style).scaledFont(for: self) } }
mit
bb029b44188ce4f8503af7ab95f58120
29.266667
94
0.605727
4.436482
false
false
false
false
karivalkama/Agricola-Scripture-Editor
TranslationEditor/SelectProjectVC.swift
1
9251
// // SelectProjectVC.swift // TranslationEditor // // Created by Mikko Hilpinen on 6.3.2017. // Copyright © 2017 SIL. All rights reserved. // import UIKit // TODO: Remove keyboard reactions if necessary, there's no input areas available // This VC handles project selection (including accepting invitations to other people's projects) class SelectProjectVC: UIViewController, LiveQueryListener, UITableViewDataSource, UITableViewDelegate, StackDismissable { // TYPES ------------------ typealias QueryTarget = ProjectView // OUTLETS ------------------ @IBOutlet weak var projectTableView: UITableView! @IBOutlet weak var contentBottomConstraint: NSLayoutConstraint! @IBOutlet weak var contentTopConstraint: NSLayoutConstraint! @IBOutlet weak var contentView: KeyboardReactiveView! @IBOutlet weak var createProjectButton: BasicButton! @IBOutlet weak var topBar: TopBarUIView! @IBOutlet weak var projectContentStackView: StatefulStackView! // ATTRIBUTES -------------- private var queryManager: LiveQueryManager<QueryTarget>? private var projects = [Project]() // Language id -> language name private var languageNames = [String: String]() private var selectedWithSharedAccount = false // COMPUTED PROPERTIES ------ var shouldDismissBelow: Bool { return selectedWithSharedAccount } // INIT ---------------------- override func viewDidLoad() { super.viewDidLoad() projectTableView.delegate = self projectTableView.dataSource = self topBar.configure(hostVC: self, title: "Select Project", leftButtonText: "Log Out") { Session.instance.logout() self.dismiss(animated: true, completion: nil) } topBar.connectionCompletionHandler = onConnectionDialogClose projectContentStackView.register(projectTableView, for: .data) let noDataView = ConnectPromptNoDataView() noDataView.connectButtonAction = { [weak self] in self?.topBar.performConnect(using: self!) } noDataView.title = "You don't have access to any projects" noDataView.hint = "You can join another person's project by connecting with them" projectContentStackView.register(noDataView, for: .empty) // If using a shared account, selects the project automatically guard let accountId = Session.instance.accountId else { print("ERROR: No logged account -> Cannot find any projects.") projectContentStackView.setState(.error) return } projectContentStackView.setState(.loading) queryManager = ProjectView.instance.projectQuery(forContributorId: accountId).liveQueryManager queryManager?.addListener(AnyLiveQueryListener(self)) contentView.configure(mainView: view, elements: [createProjectButton], topConstraint: contentTopConstraint, bottomConstraint: contentBottomConstraint, style: .squish) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) topBar.updateUserView() // If project is already selected, moves to the next view // Otherwise listens to project data changes var continuesWithProject = false if let projectId = Session.instance.projectId, let accountId = Session.instance.accountId { do { if let project = try Project.get(projectId) { // The user must still have access to the project though if project.contributorIds.contains(accountId) { // Checks whether this login should be considered shared selectedWithSharedAccount = project.sharedAccountId == accountId continuesWithProject = true } else { Session.instance.bookId = nil Session.instance.avatarId = nil Session.instance.projectId = nil } } } catch { print("ERROR: Failed to read project data. \(error)") } } if continuesWithProject { performSegue(withIdentifier: "SelectAvatar", sender: nil) } else { queryManager?.start() contentView.startKeyboardListening() } } override func viewDidDisappear(_ animated: Bool) { print("STATUS: Project view disappeared") contentView.endKeyboardListening() queryManager?.stop() } // ACTIONS ------------------ @IBAction func createProjectPressed(_ sender: Any) { displayAlert(withIdentifier: "CreateProject", storyBoardId: "Login") { vc in (vc as! CreateProjectVC).configure { if let project = $0 { Session.instance.projectId = project.idString self.performSegue(withIdentifier: "SelectAvatar", sender: nil) } } } } // IMPLEMENTED METHODS ------ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return projects.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ProjectCell.identifier, for: indexPath) as! ProjectCell let project = projects[indexPath.row] let languageName = languageNames[project.languageId].or("") cell.configure(name: project.name, languageName: languageName, created: Date(timeIntervalSince1970: project.created)) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Remembers the selected project and moves to the next view let project = projects[indexPath.row] Session.instance.projectId = project.idString performSegue(withIdentifier: "SelectAvatar", sender: nil) } func rowsUpdated(rows: [Row<ProjectView>]) { // Updates the project data in the table do { projects = try rows.map { try $0.object() } // for project in projects // { // if !languageNames.containsKey(project.languageId) // { // if let language = try Language.get(project.languageId) // { // languageNames[project.languageId] = language.name // } // } // } projectContentStackView.dataLoaded(isEmpty: projects.isEmpty) projectTableView.reloadData() } catch { print("ERROR: Failed to read project data from DB. \(error)") projectContentStackView.errorOccurred() } if let accountId = Session.instance.accountId { var selectedWithSharedAccount = false // Also checks if the user has logged in with a shared account for any of the projects // If so, proceeds with that project automatically for project in projects { if project.sharedAccountId == accountId { selectedWithSharedAccount = true Session.instance.projectId = project.idString performSegue(withIdentifier: "SelectAvatar", sender: nil) break } } self.selectedWithSharedAccount = selectedWithSharedAccount } } func willDissmissBelow() { print("STATUS: Project view will be dismissed from below") // Logs the user out before dimissing into login Session.instance.logout() } // OTHER METHODS ------------------ private func onConnectionDialogClose() { if P2PClientSession.isConnected { do { guard let projectId = P2PClientSession.instance?.projectId, let project = try Project.get(projectId) else { return } // Makes sure the current user also has access to the project if let accountId = Session.instance.accountId { if !project.contributorIds.contains(accountId) { project.contributorIds.append(accountId) try project.push() } } } catch { print("ERROR: Failed to provide project access. \(error)") } } } }
mit
f0f941407f378f76dfc72dec709a5863
32.882784
174
0.565081
5.843335
false
false
false
false
JaySonGD/SwiftDayToDay
UMDemo/UMDemo/ViewController.swift
1
2647
// // ViewController.swift // UMDemo // // Created by czljcb on 16/3/16. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { //注意:分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法 // MARK: - 各平台分享 // UMSocialSnsService.presentSnsIconSheetView(self, appKey: "56e97ab667e58e2aaf003278", shareText: "来自友们分享", shareImage: nil, shareToSnsNames:[UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,UMShareToQQ,UMShareToQzone], delegate: nil) // MARK: - 微博登录 // let snsPlatform: UMSocialSnsPlatform = UMSocialSnsPlatformManager.getSocialPlatformWithName(UMShareToSina) // // snsPlatform.loginClickHandler!(self,UMSocialControllerService.defaultControllerService(),true,{ // (response) -> () // in // if (response.responseCode == UMSResponseCodeSuccess) { // let snsAccount = UMSocialAccountManager.socialAccountDictionary()[UMShareToSina] // // guard let account: UMSocialAccountEntity = snsAccount as? UMSocialAccountEntity else{ // return // } // // print(account.userName ) // } // // }) let snsPlatform: UMSocialSnsPlatform = UMSocialSnsPlatformManager.getSocialPlatformWithName(UMShareToQQ) snsPlatform.loginClickHandler!(self,UMSocialControllerService.defaultControllerService(),true,{ (response) -> () in if (response.responseCode == UMSResponseCodeSuccess) { let snsAccount = UMSocialAccountManager.socialAccountDictionary()[UMShareToQQ] guard let account: UMSocialAccountEntity = snsAccount as? UMSocialAccountEntity else{ return } print(account.userName ) } }) } }
mit
949ead7b28b22dee473ba86dad8cc423
34.971014
278
0.616841
4.782274
false
false
false
false
zisko/swift
stdlib/public/core/RangeReplaceableCollection.swift
1
40872
//===--- RangeReplaceableCollection.swift ---------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // A Collection protocol with replaceSubrange. // //===----------------------------------------------------------------------===// /// A type that supports replacement of an arbitrary subrange of elements with /// the elements of another collection. /// /// In most cases, it's best to ignore this protocol and use the /// `RangeReplaceableCollection` protocol instead, because it has a more /// complete interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'RandomAccessCollection' instead") public typealias RangeReplaceableIndexable = RangeReplaceableCollection /// A collection that supports replacement of an arbitrary subrange of elements /// with the elements of another collection. /// /// Range-replaceable collections provide operations that insert and remove /// elements. For example, you can add elements to an array of strings by /// calling any of the inserting or appending operations that the /// `RangeReplaceableCollection` protocol defines. /// /// var bugs = ["Aphid", "Damselfly"] /// bugs.append("Earwig") /// bugs.insert(contentsOf: ["Bumblebee", "Cicada"], at: 1) /// print(bugs) /// // Prints "["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Likewise, `RangeReplaceableCollection` types can remove one or more /// elements using a single operation. /// /// bugs.removeLast() /// bugs.removeSubrange(1...2) /// print(bugs) /// // Prints "["Aphid", "Damselfly"]" /// /// bugs.removeAll() /// print(bugs) /// // Prints "[]" /// /// Lastly, use the eponymous `replaceSubrange(_:with:)` method to replace /// a subrange of elements with the contents of another collection. Here, /// three elements in the middle of an array of integers are replaced by the /// five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// Conforming to the RangeReplaceableCollection Protocol /// ===================================================== /// /// To add `RangeReplaceableCollection` conformance to your custom collection, /// add an empty initializer and the `replaceSubrange(_:with:)` method to your /// custom type. `RangeReplaceableCollection` provides default implementations /// of all its other methods using this initializer and method. For example, /// the `removeSubrange(_:)` method is implemented by calling /// `replaceSubrange(_:with:)` with an empty collection for the `newElements` /// parameter. You can override any of the protocol's required methods to /// provide your own custom implementation. public protocol RangeReplaceableCollection : Collection where SubSequence : RangeReplaceableCollection { // FIXME(ABI): Associated type inference requires this. associatedtype SubSequence //===--- Fundamental Requirements ---------------------------------------===// /// Creates a new, empty collection. init() /// Replaces the specified subrange of elements with the given collection. /// /// This method has the effect of removing the specified range of elements /// from the collection and inserting the new elements at the same location. /// The number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameters: /// - subrange: The subrange of the collection to replace. The bounds of /// the range must be valid indices of the collection. /// - newElements: The new elements to add to the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If the call to `replaceSubrange` simply appends the /// contents of `newElements` to the collection, the complexity is O(*n*), /// where *n* is the length of `newElements`. mutating func replaceSubrange<C>( _ subrange: Range<Index>, with newElements: C ) where C : Collection, C.Element == Element /// Prepares the collection to store the specified number of elements, when /// doing so is appropriate for the underlying type. /// /// If you are adding a known number of elements to a collection, use this /// method to avoid multiple reallocations. A type that conforms to /// `RangeReplaceableCollection` can choose how to respond when this method /// is called. Depending on the type, it may make sense to allocate more or /// less storage than requested, or to take no action at all. /// /// - Parameter n: The requested number of elements to store. mutating func reserveCapacity(_ n: Int) //===--- Derivable Requirements -----------------------------------------===// /// Creates a new collection containing the specified number of a single, /// repeated value. /// /// The following example creates an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. init(repeating repeatedValue: Element, count: Int) /// Creates a new instance of a collection containing the elements of a /// sequence. /// /// - Parameter elements: The sequence of elements for the new collection. /// `elements` must be finite. init<S : Sequence>(_ elements: S) where S.Element == Element /// Adds an element to the end of the collection. /// /// If the collection does not have sufficient capacity for another element, /// additional storage is allocated before appending `newElement`. The /// following example adds a new number to an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// - Parameter newElement: The element to append to the collection. /// /// - Complexity: O(1) on average, over many additions to the same /// collection. mutating func append(_ newElement: Element) /// Adds the elements of a sequence or collection to the end of this /// collection. /// /// The collection being appended to allocates any additional necessary /// storage to hold the new elements. /// /// The following example appends the elements of a `Range<Int>` instance to /// an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the collection. /// /// - Complexity: O(*n*), where *n* is the length of the resulting /// collection. // FIXME(ABI)#166 (Evolution): Consider replacing .append(contentsOf) with += // suggestion in SE-91 mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Element /// Inserts a new element into the collection at the specified position. /// /// The new element is inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as /// the `index` parameter, the new element is appended to the /// collection. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElement: The new element to insert into the collection. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index into the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func insert(_ newElement: Element, at i: Index) /// Inserts the elements of a sequence into the collection at the specified /// position. /// /// The new elements are inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as the /// `index` parameter, the new elements are appended to the collection. /// /// Here's an example of inserting a range of integers into an array of the /// same type: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(contentsOf: 100...103, at: 3) /// print(numbers) /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElements: The new elements to insert into the collection. /// - Parameter i: The position at which to insert the new elements. `index` /// must be a valid index of the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If `i` is equal to the collection's `endIndex` /// property, the complexity is O(*n*), where *n* is the length of /// `newElements`. mutating func insert<S : Collection>(contentsOf newElements: S, at i: Index) where S.Element == Element /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved to close the /// gap. This example removes the middle element from an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.2, 1.5, 1.2, 1.6]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter i: The position of the element to remove. `index` must be /// a valid index of the collection that is not equal to the collection's /// end index. /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @discardableResult mutating func remove(at i: Index) -> Element /// Removes the specified subrange of elements from the collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeSubrange(1...3) /// print(bugs) /// // Prints "["Aphid", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The subrange of the collection to remove. The bounds /// of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeSubrange(_ bounds: Range<Index>) /// Customization point for `removeLast()`. Implement this function if you /// want to replace the default implementation. /// /// - Returns: A non-nil value if the operation was performed. mutating func _customRemoveLast() -> Element? /// Customization point for `removeLast(_:)`. Implement this function if you /// want to replace the default implementation. /// /// - Returns: `true` if the operation was performed. mutating func _customRemoveLast(_ n: Int) -> Bool /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst() /// print(bugs) /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @discardableResult mutating func removeFirst() -> Element /// Removes the specified number of elements from the beginning of the /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeFirst(_ n: Int) /// Removes all elements from the collection. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter keepCapacity: Pass `true` to request that the collection /// avoid releasing its storage. Retaining the collection's storage can /// be a useful optimization when you're planning to grow the collection /// again. The default value is `false`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. mutating func removeAll(keepingCapacity keepCapacity: Bool /*= false*/) // FIXME(ABI): Associated type inference requires this. subscript(bounds: Index) -> Element { get } // FIXME(ABI): Associated type inference requires this. subscript(bounds: Range<Index>) -> SubSequence { get } } //===----------------------------------------------------------------------===// // Default implementations for RangeReplaceableCollection //===----------------------------------------------------------------------===// extension RangeReplaceableCollection { /// Creates a new collection containing the specified number of a single, /// repeated value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @_inlineable public init(repeating repeatedValue: Element, count: Int) { self.init() if count != 0 { let elements = Repeated(_repeating: repeatedValue, count: count) append(contentsOf: elements) } } /// Creates a new instance of a collection containing the elements of a /// sequence. /// /// - Parameter elements: The sequence of elements for the new collection. @_inlineable public init<S : Sequence>(_ elements: S) where S.Element == Element { self.init() append(contentsOf: elements) } /// Adds an element to the end of the collection. /// /// If the collection does not have sufficient capacity for another element, /// additional storage is allocated before appending `newElement`. The /// following example adds a new number to an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// - Parameter newElement: The element to append to the collection. /// /// - Complexity: O(1) on average, over many additions to the same /// collection. @_inlineable public mutating func append(_ newElement: Element) { insert(newElement, at: endIndex) } /// Adds the elements of a sequence or collection to the end of this /// collection. /// /// The collection being appended to allocates any additional necessary /// storage to hold the new elements. /// /// The following example appends the elements of a `Range<Int>` instance to /// an array of integers: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the collection. /// /// - Complexity: O(*n*), where *n* is the length of the resulting /// collection. @_inlineable public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Element { let approximateCapacity = self.count + numericCast(newElements.underestimatedCount) self.reserveCapacity(approximateCapacity) for element in newElements { append(element) } } /// Inserts a new element into the collection at the specified position. /// /// The new element is inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as /// the `index` parameter, the new element is appended to the /// collection. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElement: The new element to insert into the collection. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index into the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func insert( _ newElement: Element, at i: Index ) { replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Inserts the elements of a sequence into the collection at the specified /// position. /// /// The new elements are inserted before the element currently at the /// specified index. If you pass the collection's `endIndex` property as the /// `index` parameter, the new elements are appended to the collection. /// /// Here's an example of inserting a range of integers into an array of the /// same type: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(contentsOf: 100...103, at: 3) /// print(numbers) /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter newElements: The new elements to insert into the collection. /// - Parameter i: The position at which to insert the new elements. `index` /// must be a valid index of the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If `i` is equal to the collection's `endIndex` /// property, the complexity is O(*n*), where *n* is the length of /// `newElements`. @_inlineable public mutating func insert<C : Collection>( contentsOf newElements: C, at i: Index ) where C.Element == Element { replaceSubrange(i..<i, with: newElements) } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved to close the /// gap. This example removes the middle element from an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.2, 1.5, 1.2, 1.6]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter position: The position of the element to remove. `position` must be /// a valid index of the collection that is not equal to the collection's /// end index. /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable @discardableResult public mutating func remove(at position: Index) -> Element { _precondition(!isEmpty, "Can't remove from an empty collection") let result: Element = self[position] replaceSubrange(position..<index(after: position), with: EmptyCollection()) return result } /// Removes the elements in the specified subrange from the collection. /// /// All the elements following the specified position are moved to close the /// gap. This example removes two elements from the middle of an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5] /// measurements.removeSubrange(1..<4) /// print(measurements) /// // Prints "[1.2, 1.5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The range of the collection to be removed. The /// bounds of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeSubrange(_ bounds: Range<Index>) { replaceSubrange(bounds, with: EmptyCollection()) } /// Removes the specified number of elements from the beginning of the /// collection. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst(3) /// print(bugs) /// // Prints "["Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it has") let end = index(startIndex, offsetBy: numericCast(n)) removeSubrange(startIndex..<end) } /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// bugs.removeFirst() /// print(bugs) /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Returns: The removed element. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable @discardableResult public mutating func removeFirst() -> Element { _precondition(!isEmpty, "Can't remove first element from an empty collection") let firstElement = first! removeFirst(1) return firstElement } /// Removes all elements from the collection. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter keepCapacity: Pass `true` to request that the collection /// avoid releasing its storage. Retaining the collection's storage can /// be a useful optimization when you're planning to grow the collection /// again. The default value is `false`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { self = Self() } else { replaceSubrange(startIndex..<endIndex, with: EmptyCollection()) } } /// Prepares the collection to store the specified number of elements, when /// doing so is appropriate for the underlying type. /// /// If you will be adding a known number of elements to a collection, use /// this method to avoid multiple reallocations. A type that conforms to /// `RangeReplaceableCollection` can choose how to respond when this method /// is called. Depending on the type, it may make sense to allocate more or /// less storage than requested or to take no action at all. /// /// - Parameter n: The requested number of elements to store. @_inlineable public mutating func reserveCapacity(_ n: Int) {} } extension RangeReplaceableCollection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The first element of the collection. /// /// - Complexity: O(1) /// - Precondition: `!self.isEmpty`. @_inlineable @discardableResult public mutating func removeFirst() -> Element { _precondition(!isEmpty, "Can't remove items from an empty collection") let element = first! self = self[index(after: startIndex)..<endIndex] return element } /// Removes the specified number of elements from the beginning of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(1) @_inlineable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex] } } extension RangeReplaceableCollection { /// Replaces the specified subrange of elements with the given collection. /// /// This method has the effect of removing the specified range of elements /// from the collection and inserting the new elements at the same location. /// The number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameters: /// - subrange: The subrange of the collection to replace. The bounds of /// the range must be valid indices of the collection. /// - newElements: The new elements to add to the collection. /// /// - Complexity: O(*m*), where *m* is the combined length of the collection /// and `newElements`. If the call to `replaceSubrange` simply appends the /// contents of `newElements` to the collection, the complexity is O(*n*), /// where *n* is the length of `newElements`. @_inlineable public mutating func replaceSubrange<C: Collection, R: RangeExpression>( _ subrange: R, with newElements: C ) where C.Element == Element, R.Bound == Index { self.replaceSubrange(subrange.relative(to: self), with: newElements) } /// Removes the elements in the specified subrange from the collection. /// /// All the elements following the specified position are moved to close the /// gap. This example removes two elements from the middle of an array of /// measurements. /// /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5] /// measurements.removeSubrange(1..<4) /// print(measurements) /// // Prints "[1.2, 1.5]" /// /// Calling this method may invalidate any existing indices for use with this /// collection. /// /// - Parameter bounds: The range of the collection to be removed. The /// bounds of the range must be valid indices of the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public mutating func removeSubrange<R: RangeExpression>( _ bounds: R ) where R.Bound == Index { removeSubrange(bounds.relative(to: self)) } } extension RangeReplaceableCollection { @_inlineable public mutating func _customRemoveLast() -> Element? { return nil } @_inlineable public mutating func _customRemoveLast(_ n: Int) -> Bool { return false } } extension RangeReplaceableCollection where Self : BidirectionalCollection, SubSequence == Self { @_inlineable public mutating func _customRemoveLast() -> Element? { let element = last! self = self[startIndex..<index(before: endIndex)] return element } @_inlineable public mutating func _customRemoveLast(_ n: Int) -> Bool { self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))] return true } } extension RangeReplaceableCollection where Self : BidirectionalCollection { /// Removes and returns the last element of the collection. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection if the collection is not /// empty; otherwise, `nil`. /// /// - Complexity: O(1) @_inlineable public mutating func popLast() -> Element? { if isEmpty { return nil } // duplicate of removeLast logic below, to avoid redundant precondition if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @_inlineable @discardableResult public mutating func removeLast() -> Element { _precondition(!isEmpty, "Can't remove last element from an empty collection") // NOTE if you change this implementation, change popLast above as well if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes the specified number of elements from the end of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the specified number of elements. @_inlineable public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") if _customRemoveLast(n) { return } let end = endIndex removeSubrange(index(end, offsetBy: numericCast(-n))..<end) } } // FIXME: swift-3-indexing-model: file a bug for the compiler? /// Ambiguity breakers. extension RangeReplaceableCollection where Self : BidirectionalCollection, SubSequence == Self { /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @_inlineable @discardableResult public mutating func removeLast() -> Element { _precondition(!isEmpty, "Can't remove last element from an empty collection") if let result = _customRemoveLast() { return result } return remove(at: index(before: endIndex)) } /// Removes the specified number of elements from the end of the /// collection. /// /// Attempting to remove more elements than exist in the collection /// triggers a runtime error. /// /// Calling this method may invalidate all saved indices of this /// collection. Do not rely on a previously stored index value after /// altering a collection with any operation that can change its length. /// /// - Parameter n: The number of elements to remove from the collection. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the collection. /// /// - Complexity: O(*n*), where *n* is the specified number of elements. @_inlineable public mutating func removeLast(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "Number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "Can't remove more items from a collection than it contains") if _customRemoveLast(n) { return } let end = endIndex removeSubrange(index(end, offsetBy: numericCast(-n))..<end) } } extension RangeReplaceableCollection { /// Creates a new collection by concatenating the elements of a collection and /// a sequence. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of an integer array and a `Range<Int>` instance. /// /// let numbers = [1, 2, 3, 4] /// let moreNumbers = numbers + 5...10 /// print(moreNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of the argument on the left-hand /// side. In the example above, `moreNumbers` has the same type as `numbers`, /// which is `[Int]`. /// /// - Parameters: /// - lhs: A range-replaceable collection. /// - rhs: A collection or finite sequence. @_inlineable public static func + < Other : Sequence >(lhs: Self, rhs: Other) -> Self where Element == Other.Element { var lhs = lhs // FIXME: what if lhs is a reference type? This will mutate it. lhs.append(contentsOf: rhs) return lhs } /// Creates a new collection by concatenating the elements of a sequence and a /// collection. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of a `Range<Int>` instance and an integer array. /// /// let numbers = [7, 8, 9, 10] /// let moreNumbers = 1...6 + numbers /// print(moreNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of argument on the right-hand side. /// In the example above, `moreNumbers` has the same type as `numbers`, which /// is `[Int]`. /// /// - Parameters: /// - lhs: A collection or finite sequence. /// - rhs: A range-replaceable collection. @_inlineable public static func + < Other : Sequence >(lhs: Other, rhs: Self) -> Self where Element == Other.Element { var result = Self() result.reserveCapacity(rhs.count + numericCast(lhs.underestimatedCount)) result.append(contentsOf: lhs) result.append(contentsOf: rhs) return result } /// Appends the elements of a sequence to a range-replaceable collection. /// /// Use this operator to append the elements of a sequence to the end of /// range-replaceable collection with same `Element` type. This example appends /// the elements of a `Range<Int>` instance to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers += 10...15 /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameters: /// - lhs: The array to append to. /// - rhs: A collection or finite sequence. /// /// - Complexity: O(*n*), where *n* is the length of the resulting array. @_inlineable public static func += < Other : Sequence >(lhs: inout Self, rhs: Other) where Element == Other.Element { lhs.append(contentsOf: rhs) } /// Creates a new collection by concatenating the elements of two collections. /// /// The two arguments must have the same `Element` type. For example, you can /// concatenate the elements of two integer arrays. /// /// let lowerNumbers = [1, 2, 3, 4] /// let higherNumbers: ContiguousArray = [5, 6, 7, 8, 9, 10] /// let allNumbers = lowerNumbers + higherNumbers /// print(allNumbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" /// /// The resulting collection has the type of the argument on the left-hand /// side. In the example above, `moreNumbers` has the same type as `numbers`, /// which is `[Int]`. /// /// - Parameters: /// - lhs: A range-replaceable collection. /// - rhs: Another range-replaceable collection. @_inlineable public static func + < Other : RangeReplaceableCollection >(lhs: Self, rhs: Other) -> Self where Element == Other.Element { var lhs = lhs // FIXME: what if lhs is a reference type? This will mutate it. lhs.append(contentsOf: rhs) return lhs } } extension RangeReplaceableCollection { /// Returns a new collection of the same type containing, in order, the /// elements of the original collection that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. @_inlineable @available(swift, introduced: 4.0) public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { return try Self(self.lazy.filter(isIncluded)) } }
apache-2.0
2d136d9c1d7b2ed34e39f4bb00a1ef8d
37.558491
115
0.650005
4.323249
false
false
false
false
S2dentik/Taylor
TaylorFrameworkTests/ScissorsTests/TestFiles/TestFileMoreThan500.swift
4
22892
// // ExtendedComponent.swift // Scissors // // Created by Alex Culeva on 9/17/15. // Copyright © 2015 com.yopeso.aculeva. All rights reserved. // import Foundation import SourceKittenFramework import SwiftXPC class ExtendedComponent { var offsetRange: OffsetRange var type: ComponentType var name: String? var parent: ExtendedComponent? var components: [ExtendedComponent] init(type: ComponentType, range: OffsetRange, name: String? = nil, parent: ExtendedComponent? = nil) { self.type = type self.offsetRange = range self.parent = parent self.components = [] self.name = name } init(dict: [String: AnyObject]) { self.type = ComponentType(type: dict["type"] as! String) let startOffset = dict["offset"] as! Int let endOffset = startOffset + (dict["length"] as! Int) self.offsetRange = OffsetRange(start: startOffset, end: endOffset - 1) self.name = nil self.components = [] } func appendComponents(var components: [ExtendedComponent], array: XPCArray) -> [ExtendedComponent] { var braces = 0 for (var childNumber = 0; childNumber < array.count; childNumber++) { let structure = array[childNumber] let typeString = structure.asDictionary.type var offsetRange = structure.asDictionary.offsetRange var componentType = ComponentType(type: typeString) if isElseIf(componentType) { componentType = .ElseIf } else if isElse(componentType) && childNumber == array.count-1 && braces > 0 { componentType = .Else } else if componentType.isVariable { let bodyOffsetEnd = structure.asDictionary.bodyLength + structure.asDictionary.bodyOffset if bodyOffsetEnd != 0 { offsetRange.end = bodyOffsetEnd } } else if componentType.isOther { continue } if componentType.isBrace { braces++ } let child = ExtendedComponent(type: componentType, range: offsetRange, name: structure.asDictionary.name) components.append(child) components = child.appendComponents(components, array: structure.asDictionary.substructure) } return components } func addChild(child: ExtendedComponent) -> ExtendedComponent { self.components.append(child) child.parent = self return child } func addChild(type: ComponentType, range: OffsetRange, name: String? = nil) -> ExtendedComponent { let child = ExtendedComponent(type: type, range: range, name: name, parent: self) self.components.append(child) return child } func contains(node: ExtendedComponent) -> Bool { return (node.offsetRange.start >= self.offsetRange.start) && (node.offsetRange.end <= self.offsetRange.end) } func insert(node: ExtendedComponent) { for child in self.components { if child.contains(node) { child.insert(node) return } else if node.contains(child) { remove(child) node.addChild(child) } } self.addChild(node) } func remove(component: ExtendedComponent) { components = components.filter { $0 != component } } func insert(components: [ExtendedComponent]) { let _ = components.map { self.insert($0) } } func variablesToFunctions() { for component in self.components { if component.hasNoChildrenExceptELComment { if component.isActuallyClosure { component.components[0].name = component.name component.parent?.components.append(component.components[0]) component.parent?.remove(component) } component.type = ComponentType.Function } else if component.type == .Brace && component.containsParameter { component.type = .Closure } component.variablesToFunctions() } } func removeRedundantClosures() { for component in components { component.removeRedundantClosures() } removeRedundantClosuresInSelf() } func removeRedundantClosuresInSelf() { components = components.filter { !($0.type == .Closure && $0.components.count == 0) } } func processBracedType() { if self.children > 1 { self.changeChildToParent(1) } self.takeChildrenOfChild(0) if type != .Repeat { self.offsetRange.end = self.components[0].offsetRange.end } self.components.removeAtIndex(0) } func sortChildren() { self.components = self.components.sort({ $0.offsetRange.start < $1.offsetRange.start }) } } struct OffsetRange { var start: Int var end: Int init(start: Int, end: Int) { self.start = start self.end = end } } // // Tree.swift // Scissors // // Created by Alex Culeva on 9/14/15. // Copyright © 2015 com.yopeso.aculeva. All rights reserved. // import Foundation import BoundariesKit import SwiftXPC import SourceKittenFramework class Tree { let file: File let dictionary: XPCDictionary let syntaxMap: SyntaxMap let parts: [File] init(file: File) { let structure = Structure(file: file) self.file = file dictionary = structure.dictionary syntaxMap = structure.syntaxMap self.parts = file.divideByLines() } //MARK: Dictionary to tree methods func makeTree() -> Component { let root = ExtendedComponent(type: .Other, range: dictionary.offsetRange) let noStringsText = replaceStringsWithSpaces(parts.map() { $0.contents }) let finder = Finder(text: noStringsText, syntaxMap: syntaxMap) var componentsArray = root.appendComponents([], array: dictionary.substructure) componentsArray += finder.findGetters(componentsArray) arrayToTree(componentsArray, root: root) root.removeRedundantClosures() processBraces(root) arrayToTree(additionalComponents(finder), root: root) root.variablesToFunctions() sortTree(root) return convertTree(root) } func additionalComponents(finder: Finder) -> [ExtendedComponent] { return finder.findComments() + finder.findLogicalOperators() + finder.findEmptyLines() } //MARK: Conversion to Component type func convertTree(root: ExtendedComponent) -> Component { let rootComponent = Component(type: root.type, range: ComponentRange(sl: 1, el: file.lines.count)) convertToComponent(root, componentNode: rootComponent) return rootComponent } func convertToComponent(node: ExtendedComponent, componentNode: Component) { for component in node.components { let child = componentNode.makeComponent(type: component.type, range: offsetToLine(component.offsetRange)) child.name = component.name convertToComponent(component, componentNode: child) } } func offsetToLine(offsetRange: OffsetRange) -> ComponentRange { // guard parts[0].size > 0 else { // return ComponentRange(sl: 0, el: 0) // } let startIndex = parts.filter { $0.startOffset <= offsetRange.start }.count - 1 let endIndex = parts.filter { $0.startOffset <= offsetRange.end }.count - 1 return ComponentRange(sl: parts[startIndex].getLineRange(offsetRange.start), el: parts[endIndex].getLineRange(offsetRange.end)) } func arrayToTree(components: [ExtendedComponent], root: ExtendedComponent) -> ExtendedComponent { let parent = root parent.insert(components) return parent } //MARK: Processing the tree func processBraces(parent: ExtendedComponent) { var i = 0 while i < parent.components.count { let component = parent.components[i]; i++ let type = component.type let bracedTypes = [ComponentType.If, .ElseIf, .For, .While, .Repeat, .Closure] if bracedTypes.contains(type) { guard component.isFirstComponentBrace else { continue } component.processBracedType() } processBraces(component) } } func sortTree(root: ExtendedComponent) { for component in root.components { sortTree(component) component.sortChildren() } } //MARK: Text filtering methods func replaceStringsWithSpaces(text: [String]) -> String { var noStrings = "" for var part in text { if part.isEmpty { continue } for string in re.findall("\\\".*?\\\"", part, flags: [NSRegularExpressionOptions.DotMatchesLineSeparators]) { let len = string.characters.count part = part.stringByReplacingOccurrencesOfString(string, withString: " "*len) } noStrings += part + "\n" } return noStrings } } // // Finder.swift // Scissors // // Created by Alex Culeva on 10/2/15. // Copyright © 2015 com.yopeso.aculeva. All rights reserved. // import Foundation import SourceKittenFramework import BoundariesKit class Finder { let text: String let syntaxMap: SyntaxMap init(text: String, syntaxMap: SyntaxMap = SyntaxMap(tokens: [])) { self.text = text self.syntaxMap = syntaxMap } func findRanges(pattern: String, text: String) -> [OffsetRange] { var ranges = [OffsetRange]() let r = re.compile(pattern, flags: [.DotMatchesLineSeparators]) for match in r.finditer(text) { if let range = match.spanNSRange() { ranges.append(OffsetRange(start: range.location, end: range.location+range.length)) } } return ranges } func findLogicalOperators() -> [ExtendedComponent] { var operators = [ExtendedComponent]() for ternaryRange in findRanges("(\\s+\\?(?!\\?).*?:)", text: text) { operators.append(ExtendedComponent(type: .Ternary, range: ternaryRange)) } for nilcRange in findRanges("(\\?\\?)", text: text) { operators.append(ExtendedComponent(type: .NilCoalescing, range: nilcRange)) } for orRange in findRanges("(\\|\\|)", text: text) { operators.append(ExtendedComponent(type: .Or, range: orRange)) } for andRange in findRanges("(\\&\\&)", text: text) { operators.append(ExtendedComponent(type: .And, range: andRange)) } return operators } func findComments() -> [ExtendedComponent] { var components = [ExtendedComponent]() for token in syntaxMap.tokens { if ComponentType(type: token.type) == ComponentType.Comment { components.append(ExtendedComponent(dict: token.dictionaryValue)) } } return components } func findEmptyLines() -> [ExtendedComponent] { var emptyLines = [ExtendedComponent]() for emptyLineRange in findRanges("(\\n[ \\t\\n]*\\n)", text: text) { let correctEmptyRange = OffsetRange(start: emptyLineRange.start + 1, end: emptyLineRange.end - 1) emptyLines.append(ExtendedComponent(type: .EmptyLines, range: correctEmptyRange)) } return emptyLines } //Ending points of getters and setters will most probably be wrong unless a nice coding-style is being used "} set {" func findGetters(components: [ExtendedComponent]) -> [ExtendedComponent] { let variableComponents = components.filter { $0.type == .Variable } let nsText = text as NSString var getters = [ExtendedComponent]() for component in variableComponents { let range = NSMakeRange(component.offsetRange.start, component.offsetRange.end - component.offsetRange.start) let variableText = nsText.substringWithRange(range) let functions = findGetterAndSetter(variableText) for function in functions { function.offsetRange.start += component.offsetRange.start function.offsetRange.end += component.offsetRange.start getters.append(function) } } return getters } func findGetterAndSetter(text: String) -> [ExtendedComponent] { var accessors = [ExtendedComponent]() let gettersRanges = findRanges("(get($|[ \\t\\n{}]))", text: text) let settersRanges = findRanges("(set($|[ \\t\\n{}]))", text: text) if gettersRanges.count == 0 { return findObserverGetters(text) } accessors.append(ExtendedComponent(type: .Function, range: gettersRanges[0], name: "get", parent: nil)) if settersRanges.count > 0 { accessors.append(ExtendedComponent(type: .Function, range: settersRanges[0], name: "set", parent: nil)) } accessors.sortInPlace( { $0.offsetRange.start < $1.offsetRange.start } ) if accessors.count == 1 { accessors[0].offsetRange.end = text.characters.count - 1 } else { accessors[0].offsetRange.end = accessors[1].offsetRange.start - 1 accessors[1].offsetRange.end = text.characters.count - 1 } return accessors } func findObserverGetters(text:String) -> [ExtendedComponent] { var willSetRanges = findRanges("(willSet($|[ \\t\\n{}]))", text: text) var didSetRanges = findRanges("(didSet($|[ \\t\\n{}]))", text: text) var observers = [ExtendedComponent]() if willSetRanges.count > 0 { observers.append(ExtendedComponent(type: .Function, range: willSetRanges[0], name: "willSet", parent: nil)) } if didSetRanges.count > 0 { observers.append(ExtendedComponent(type: .Function, range: didSetRanges[0], name: "didSet", parent: nil)) } observers.sortInPlace( { $0.offsetRange.start < $1.offsetRange.start } ) switch observers.count { case 0: return [] case 1: observers[0].offsetRange.end = text.characters.count - 1 case 2: observers[0].offsetRange.end = observers[1].offsetRange.start - 1 observers[1].offsetRange.end = text.characters.count - 1 default: break } return observers } } // // Extensions.swift // Scissors // // Created by Alex Culeva on 9/18/15. // Copyright © 2015 com.yopeso.aculeva. All rights reserved. // import Foundation import BoundariesKit import SwiftXPC import SourceKittenFramework //MARK: BoundariesKit extensions let types = [ "source.lang.swift.decl.class": ComponentType.Class, "source.lang.swift.decl.struct": .Struct, "source.lang.swift.decl.enum": .Enum, "source.lang.swift.decl.protocol": .Protocol, "source.lang.swift.decl.function.method.instance": .Function, "source.lang.swift.decl.function.method.static": .Function, "source.lang.swift.decl.function.method.class": .Function, "source.lang.swift.decl.function.accessor.getter": .Function, "source.lang.swift.decl.function.accessor.setter": .Function, "source.lang.swift.decl.function.accessor.willset": .Function, "source.lang.swift.decl.function.accessor.didset": .Function, "source.lang.swift.decl.function.accessor.address": .Function, "source.lang.swift.decl.function.accessor.mutableaddress": .Function, "source.lang.swift.decl.function.constructor": .Function, "source.lang.swift.decl.function.destructor": .Function, "source.lang.swift.decl.function.free": .Function, "source.lang.swift.decl.function.accessor.operator": .Function, "source.lang.swift.decl.function.accessor.subscript": .Function, "source.lang.swift.decl.var.parameter": .Parameter, "source.lang.swift.decl.extension": .Extension, "source.lang.swift.decl.extension.struct": .Extension, "source.lang.swift.decl.extension.class": .Extension, "source.lang.swift.decl.extension.enum": .Extension, "source.lang.swift.decl.extension.protocol": .Extension, "source.lang.swift.stmt.for": .For, "source.lang.swift.stmt.foreach": .For, "source.lang.swift.stmt.if": .If, "source.lang.swift.stmt.repeatwhile": .Repeat, "source.lang.swift.stmt.while": .While, "source.lang.swift.stmt.switch": .Switch, "source.lang.swift.stmt.case": .Case, "source.lang.swift.stmt.brace": .Brace, "source.lang.swift.syntaxtype.comment": .Comment, "source.lang.swift.syntaxtype.doccomment": .Comment, "source.lang.swift.decl.var.instance": .Variable, "source.lang.swift.decl.var.global": .Variable, "source.lang.swift.expr.call": .Closure ] extension ComponentType { init(type: String) { self = types[type] ?? .Other } } extension ComponentType { var isOther: Bool { return self == .Other } var isBrace: Bool { return self == .Brace } var isVariable: Bool { return self == .Variable } var isComment: Bool { return self == .Comment } var isEmptyLine: Bool { return self == .EmptyLines } } //MARK: SwiftXPC extensions protocol StringType {} extension String: StringType {} extension XPCRepresentable { var asDictionary: XPCDictionary { return self as! XPCDictionary } } protocol XPCType { var value: XPCDictionary { get } } extension Dictionary where Key: StringType { var offsetRange: OffsetRange { let startOffset = SwiftDocKey.getOffset(self.asDictionary) ?? 0 let length = SwiftDocKey.getLength(self.asDictionary) ?? 0 let endOffset = Int(startOffset + length) return OffsetRange(start: Int(startOffset), end: endOffset) } var name: String? { return SwiftDocKey.getName(self.asDictionary) } var substructure: XPCArray { return SwiftDocKey.getSubstructure(self.asDictionary) ?? [] } var type: String { return SwiftDocKey.getKind(self.asDictionary) ?? "" } var bodyLength: Int { return Int(SwiftDocKey.getBodyLength(self.asDictionary) ?? 0) } var bodyOffset: Int { return Int(SwiftDocKey.getBodyOffset(self.asDictionary) ?? 0) } } extension File { func chunkSize(numberOfLines: Int) -> Int { func numberOfCharacters(m: Double, b: Double) -> Int { return Double(numberOfLines).linearFunction(slope: m, intercept: b).intValue } if numberOfLines < 500 { return contents.characters.count } if numberOfLines < 1000 { return numberOfCharacters(m: 0.8, b: 0) } if numberOfLines < 2000 { return numberOfCharacters(m: 0.45, b: 350) } if numberOfLines < 3000 { return numberOfCharacters(m: 0.2, b: 850) } else { return numberOfCharacters(m: 0.18, b: 900) } } func divideByLines() -> [File] { guard chunkSize(lines.count) > 0 else { return [self] } let partitions = contents.characters.count / chunkSize(lines.count) if partitions <= 1 { return [self] } let size = lines.count / partitions var temporaryParts = [File]() var startOffset = 0 for(var i = 0; i < partitions; i++) { let slice = lines.part(from: i * size, to: i == partitions - 1 ? lines.count : (i + 1) * size) let file = File(lines: slice.map() { $0.content }, startLine: i * size + 1, startOffset: startOffset) temporaryParts.append(file) startOffset += file.contents.characters.count } return temporaryParts } func getLineRange(offset: Int) -> Int { return startLine + getLineByOffset(offset - startOffset, length: 0).0 - 1 } } extension Array { func part(from a: Int, to b: Int) -> Array<Element> { return Array(self[a ..< b]) } } //MARK: ExtendedComponent extensions extension ExtendedComponent { var isElseIfOrIf: Bool { return self.type == .If || self.type == .ElseIf } var children: Int { return self.components.count } var containsClosure: Bool { return self.components.filter(){ $0.type == ComponentType.Closure }.count > 0 } var containsParameter: Bool { return self.components.filter(){ $0.type == ComponentType.Parameter }.count > 0 } var isVariableWithChildren: Bool { return self.type == .Variable && self.components.count > 0 } var hasNoChildrenExceptELComment: Bool { return self.components.filter { !$0.type.isComment && !$0.type.isEmptyLine }.count > 0 && self.type == .Variable } var isActuallyClosure: Bool { return self.children == 1 && self.containsClosure } var isFirstComponentBrace: Bool { guard self.components.count > 0 else { return false } return self.components[0].type == .Brace } func isElseIf(type: ComponentType) -> Bool { return type == .If && self.isElseIfOrIf } func isElse(type: ComponentType) -> Bool { return type == .Brace && self.isElseIfOrIf } func changeChildToParent(index: Int) { parent?.addChild(components[index]) components.removeAtIndex(index) } func takeChildrenOfChild(index: Int) { for child in components[index].components { addChild(child) } } } extension ExtendedComponent : Hashable { var hashValue: Int { return components.reduce(offsetRange.start.hashValue + offsetRange.end.hashValue + type.hashValue) { $0 + $1.hashValue } } } extension ExtendedComponent : Equatable {} func ==(lhs: ExtendedComponent, rhs: ExtendedComponent) -> Bool { if !(lhs.offsetRange == rhs.offsetRange) { return false } if lhs.type != rhs.type { return false } if !(Set(lhs.components) == Set(rhs.components)) { return false } return true } func ==(lhs: OffsetRange, rhs: OffsetRange) -> Bool { if lhs.end == rhs.end && lhs.start == rhs.start { return true } return false } //MARK: Linear function on double x extension Double { func linearFunction(slope: Double, intercept: Double) -> Double { return slope * self + intercept } var intValue: Int { return Int(self) } } //MARK: Operators overloading func *(left: String, right: Int) -> String { var result = "" for _ in 0..<right { result += left } return result }
mit
c6eb6819457877e0bd731af63180d6e5
34.706708
135
0.622116
4.422802
false
false
false
false
jianghongbing/APIReferenceDemo
UIKit/UISegmentControl/UISegmentControl/ViewController.swift
1
6944
// // ViewController.swift // UISegmentControl // // Created by pantosoft on 2017/7/11. // Copyright © 2017年 jianghongbing. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var topSegmentControl: UISegmentedControl! @IBOutlet weak var centerSegmentControl: UISegmentedControl! @IBOutlet weak var bottomSegmentControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() //UISegmentControl:分段控件,只能同时显示文字或者图片,不同既显示文字又显示图片 //1.是否短暂提示某一段被选中,默认为false,当为false,某一段被选中后,会以后选中的状态呈现,如果为ture,只会短暂的显示一下,然后又恢复之前的状态 topSegmentControl.isMomentary = true //2.segment的数量 let numberOfSegment = topSegmentControl.numberOfSegments print(numberOfSegment) //3.是否根据segment的内容来计算宽度,默认为false topSegmentControl.apportionsSegmentWidthsByContent = true //4.insert segment topSegmentControl.insertSegment(withTitle: "third Item", at: 2, animated: true) topSegmentControl.insertSegment(with: #imageLiteral(resourceName: "test.jpg"), at: 2, animated: true) //5.移除segment topSegmentControl.removeSegment(at: 2, animated: true) // topSegmentControl.removeAllSegments() //6.设置指定位置的segment的title topSegmentControl.setTitle("one item", forSegmentAt: 0) topSegmentControl.setTitle("two item", forSegmentAt: 1) //7.获取指定位置的segment的title if let title = topSegmentControl.titleForSegment(at: 1) { print("title:\(title)") } //8.设置指定位置的segment的width topSegmentControl.setWidth(80, forSegmentAt: 0) topSegmentControl.setWidth(100, forSegmentAt: 1) topSegmentControl.setWidth(120, forSegmentAt: 2) //9.获取指定位置的segment的width let segmentWidth = topSegmentControl.widthForSegment(at: 1) print(segmentWidth) //10.设置指定位置的segment的contentOffset内容的偏移量 topSegmentControl.setContentOffset(CGSize(width: -10, height: -8), forSegmentAt: 1) topSegmentControl.setContentOffset(CGSize(width: 20, height: 8), forSegmentAt: 2) //11.获取指定segment的偏移 let offset = topSegmentControl.contentOffsetForSegment(at: 1) print(offset) //12.设置指定位置的segment的enable状态 topSegmentControl.setEnabled(false, forSegmentAt: 2) //13.获取指定位置的segmenet的enable状态 let isEnable = topSegmentControl.isEnabledForSegment(at: 2) print(isEnable) //13.设置和获取选中的segment bottomSegmentControl.selectedSegmentIndex = 1 //14.设置tintColor bottomSegmentControl.tintColor = .orange //15.设置不同状态下的背景图片 bottomSegmentControl.setBackgroundImage(#imageLiteral(resourceName: "test.jpg"), for: .normal, barMetrics: .default) bottomSegmentControl.setBackgroundImage(#imageLiteral(resourceName: "test1.jpg"), for: .selected, barMetrics: .default) //16.获取不同状态下的图片 if let _ = bottomSegmentControl.backgroundImage(for: .normal, barMetrics: .default) { print("has background image") }else { print("no backgournd image") } //17.设置分割线的图片 bottomSegmentControl.setDividerImage(UIImage.imageForColor(color: .red, imageSize: CGSize(width: 5, height: 20)), forLeftSegmentState: .normal, rightSegmentState: .selected, barMetrics: .default) bottomSegmentControl.setDividerImage(UIImage.imageForColor(color: .blue, imageSize: CGSize(width: 5, height: 20)), forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default) //18.获取分割线的图片 if let _ = bottomSegmentControl.dividerImage(forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default) { print("has dividerImage for this state") }else { print("no dividerImage for this state") } //19.设置title的属性 bottomSegmentControl.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .normal) bottomSegmentControl.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blue], for: .selected) //20.获取title的对应状态下的属性 if let attributes = bottomSegmentControl.titleTextAttributes(for: .normal) { print(attributes) }else { print("no attributes") } //21.set content position adjust bottomSegmentControl.setContentPositionAdjustment(UIOffsetMake(10, 10), forSegmentType: .any, barMetrics: .default) //22.获取content position adjust let positionAdjust = bottomSegmentControl.contentPositionAdjustment(forSegmentType: .any, barMetrics: .default) print(positionAdjust) //23.add target centerSegmentControl.addTarget(self, action: #selector(segmentControlValueChange(_:)), for: .valueChanged) //24.image segmentControl imageTypeSegmentControl() } @objc private func segmentControlValueChange(_ segmentControl: UISegmentedControl) { print(#function) } private func imageTypeSegmentControl() { let imageOne = UIImage.imageForColor(color: UIColor.red, imageSize: CGSize(width: 100, height: 30))!; let imageTwo = UIImage.imageForColor(color: UIColor.blue, imageSize: CGSize(width: 100, height: 30))!; let imageSegmentControl = UISegmentedControl(items: [imageOne, imageTwo]) imageSegmentControl.translatesAutoresizingMaskIntoConstraints = false // imageSegmentControl.tintColor = .clear view.addSubview(imageSegmentControl) imageSegmentControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true imageSegmentControl.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true } } extension UIImage { fileprivate class func imageForColor(color: UIColor?, imageSize: CGSize) -> UIImage? { guard !(color == nil || imageSize.width <= 0 || imageSize.height <= 0) else { return nil } UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color!.cgColor) context?.fill(CGRect(origin: .zero, size: imageSize)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image?.withRenderingMode(.alwaysOriginal) } }
mit
a188cb841c7289c9469dc2bb03eda889
46.116788
204
0.691712
4.923722
false
false
false
false
seandavidmcgee/HumanKontactBeta
src/keyboardTest/Classes/CGPointEx.swift
53
2226
// // CGPointEx.swift // LiquidLoading // // Created by Takuma Yoshida on 2015/08/17. // Copyright (c) 2015年 yoavlt. All rights reserved. // import Foundation import UIKit extension CGPoint { // 足し算 func plus(point: CGPoint) -> CGPoint { return CGPoint(x: self.x + point.x, y: self.y + point.y) } // 引き算 func minus(point: CGPoint) -> CGPoint { return CGPoint(x: self.x - point.x, y: self.y - point.y) } func minusX(dx: CGFloat) -> CGPoint { return CGPoint(x: self.x - dx, y: self.y) } func minusY(dy: CGFloat) -> CGPoint { return CGPoint(x: self.x, y: self.y - dy) } // 掛け算 func mul(rhs: CGFloat) -> CGPoint { return CGPoint(x: self.x * rhs, y: self.y * rhs) } // 割り算 func div(rhs: CGFloat) -> CGPoint { return CGPoint(x: self.x / rhs, y: self.y / rhs) } // 長さ func length() -> CGFloat { return sqrt(self.x * self.x + self.y * self.y) } // 正規化 func normalized() -> CGPoint { return self.div(self.length()) } // 内積 func dot(point: CGPoint) -> CGFloat { return self.x * point.x + self.y * point.y } // 外積 func cross(point: CGPoint) -> CGFloat { return self.x * point.y - self.y * point.x } func split(point: CGPoint, ratio: CGFloat) -> CGPoint { return self.mul(ratio).plus(point.mul(1.0 - ratio)) } func mid(point: CGPoint) -> CGPoint { return split(point, ratio: 0.5) } static func intersection(from: CGPoint, to: CGPoint, from2: CGPoint, to2: CGPoint) -> CGPoint? { let ac = CGPoint(x: to.x - from.x, y: to.y - from.y) let bd = CGPoint(x: to2.x - from2.x, y: to2.y - from2.y) let ab = CGPoint(x: from2.x - from.x, y: from2.y - from.y) let bc = CGPoint(x: to.x - from2.x, y: to.y - from2.y) let area = bd.cross(ab) let area2 = bd.cross(bc) if abs(area + area2) >= 0.1 { let ratio = area / (area + area2) return CGPoint(x: from.x + ratio * ac.x, y: from.y + ratio * ac.y) } return nil } }
mit
486b7388619a3c781378e6a3e629e1ae
24.091954
100
0.529789
3.112696
false
false
false
false
PjGeeroms/IOSRecipeDB
YummlyProject/Drawings/TrashCan.swift
1
7832
// // TrashCan.swift // RecipeDB // // Created by PieterJanGeeroms on 31/12/2016. // Copyright © 2016 PJ Inc. All rights reserved. // // Generated by PaintCode // http://www.paintcodeapp.com // // This code was generated by Trial version of PaintCode, therefore cannot be used for commercial purposes. // import UIKit public class TrashCan : NSObject { //// Drawing Methods public dynamic class func drawCanvas1(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 416, height: 512), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 416, height: 512), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 416, y: resizedFrame.height / 512) //// Color Declarations let fillColor = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000) //// garbage.svg Group //// Group 2 //// Rectangle Drawing let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 199.32, y: 138.85, width: 17.35, height: 303.75), cornerRadius: 8.6) fillColor.setFill() rectanglePath.fill() //// Rectangle 2 Drawing let rectangle2Path = UIBezierPath(roundedRect: CGRect(x: 112.53, y: 138.85, width: 17.35, height: 303.75), cornerRadius: 8.6) fillColor.setFill() rectangle2Path.fill() //// Rectangle 3 Drawing let rectangle3Path = UIBezierPath(roundedRect: CGRect(x: 286.12, y: 138.85, width: 17.35, height: 303.75), cornerRadius: 8.6) fillColor.setFill() rectangle3Path.fill() //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 407.59, y: 52.07)) bezierPath.addLine(to: CGPoint(x: 285.72, y: 52.07)) bezierPath.addCurve(to: CGPoint(x: 269.99, y: 11.19), controlPoint1: CGPoint(x: 284.77, y: 41.22), controlPoint2: CGPoint(x: 281.42, y: 22.93)) bezierPath.addCurve(to: CGPoint(x: 242.7, y: 0), controlPoint1: CGPoint(x: 262.75, y: 3.77), controlPoint2: CGPoint(x: 253.57, y: 0)) bezierPath.addLine(to: CGPoint(x: 155.93, y: 0)) bezierPath.addCurve(to: CGPoint(x: 128.65, y: 11.19), controlPoint1: CGPoint(x: 145.07, y: 0), controlPoint2: CGPoint(x: 135.89, y: 3.77)) bezierPath.addCurve(to: CGPoint(x: 112.92, y: 52.07), controlPoint1: CGPoint(x: 117.21, y: 22.93), controlPoint2: CGPoint(x: 113.87, y: 41.22)) bezierPath.addLine(to: CGPoint(x: 8.41, y: 52.07)) bezierPath.addCurve(to: CGPoint(x: -0.27, y: 60.75), controlPoint1: CGPoint(x: 3.62, y: 52.07), controlPoint2: CGPoint(x: -0.27, y: 55.95)) bezierPath.addCurve(to: CGPoint(x: 8.41, y: 69.42), controlPoint1: CGPoint(x: -0.27, y: 65.54), controlPoint2: CGPoint(x: 3.62, y: 69.42)) bezierPath.addLine(to: CGPoint(x: 26.12, y: 69.42)) bezierPath.addLine(to: CGPoint(x: 42.74, y: 468.79)) bezierPath.addCurve(to: CGPoint(x: 85.33, y: 512), controlPoint1: CGPoint(x: 43.06, y: 483.74), controlPoint2: CGPoint(x: 52.36, y: 512)) bezierPath.addLine(to: CGPoint(x: 330.67, y: 512)) bezierPath.addCurve(to: CGPoint(x: 373.25, y: 468.97), controlPoint1: CGPoint(x: 363.64, y: 512), controlPoint2: CGPoint(x: 372.94, y: 483.74)) bezierPath.addLine(to: CGPoint(x: 389.88, y: 69.42)) bezierPath.addLine(to: CGPoint(x: 407.59, y: 69.42)) bezierPath.addCurve(to: CGPoint(x: 416.27, y: 60.75), controlPoint1: CGPoint(x: 412.38, y: 69.42), controlPoint2: CGPoint(x: 416.27, y: 65.54)) bezierPath.addCurve(to: CGPoint(x: 407.59, y: 52.07), controlPoint1: CGPoint(x: 416.27, y: 55.95), controlPoint2: CGPoint(x: 412.38, y: 52.07)) bezierPath.close() bezierPath.move(to: CGPoint(x: 141.11, y: 23.27)) bezierPath.addCurve(to: CGPoint(x: 155.93, y: 17.36), controlPoint1: CGPoint(x: 145, y: 19.29), controlPoint2: CGPoint(x: 149.85, y: 17.36)) bezierPath.addLine(to: CGPoint(x: 242.7, y: 17.36)) bezierPath.addCurve(to: CGPoint(x: 257.53, y: 23.27), controlPoint1: CGPoint(x: 248.79, y: 17.36), controlPoint2: CGPoint(x: 253.64, y: 19.29)) bezierPath.addCurve(to: CGPoint(x: 268.29, y: 52.07), controlPoint1: CGPoint(x: 264.51, y: 30.41), controlPoint2: CGPoint(x: 267.31, y: 42.97)) bezierPath.addLine(to: CGPoint(x: 130.36, y: 52.07)) bezierPath.addCurve(to: CGPoint(x: 141.11, y: 23.27), controlPoint1: CGPoint(x: 131.33, y: 42.97), controlPoint2: CGPoint(x: 134.13, y: 30.41)) bezierPath.close() bezierPath.move(to: CGPoint(x: 355.91, y: 468.43)) bezierPath.addCurve(to: CGPoint(x: 330.67, y: 494.64), controlPoint1: CGPoint(x: 355.86, y: 471.11), controlPoint2: CGPoint(x: 354.66, y: 494.64)) bezierPath.addLine(to: CGPoint(x: 85.33, y: 494.64)) bezierPath.addCurve(to: CGPoint(x: 60.08, y: 468.25), controlPoint1: CGPoint(x: 61.6, y: 494.64), controlPoint2: CGPoint(x: 60.18, y: 471.07)) bezierPath.addLine(to: CGPoint(x: 43.48, y: 69.42)) bezierPath.addLine(to: CGPoint(x: 372.51, y: 69.42)) bezierPath.addLine(to: CGPoint(x: 355.91, y: 468.43)) bezierPath.close() fillColor.setFill() bezierPath.fill() //// Group 3 //// Group 4 //// Group 5 //// Group 6 //// Group 7 //// Group 8 //// Group 9 //// Group 10 //// Group 11 //// Group 12 //// Group 13 //// Group 14 //// Group 15 //// Group 16 //// Group 17 context.restoreGState() } @objc public enum ResizingBehavior: Int { case aspectFit /// The content is proportionally resized to fit into the target rectangle. case aspectFill /// The content is proportionally resized to completely fill the target rectangle. case stretch /// The content is stretched to match the entire target rectangle. case center /// The content is centered in the target rectangle, but it is NOT resized. public func apply(rect: CGRect, target: CGRect) -> CGRect { if rect == target || target == CGRect.zero { return rect } var scales = CGSize.zero scales.width = abs(target.width / rect.width) scales.height = abs(target.height / rect.height) switch self { case .aspectFit: scales.width = min(scales.width, scales.height) scales.height = scales.width case .aspectFill: scales.width = max(scales.width, scales.height) scales.height = scales.width case .stretch: break case .center: scales.width = 1 scales.height = 1 } var result = rect.standardized result.size.width *= scales.width result.size.height *= scales.height result.origin.x = target.minX + (target.width - result.width) / 2 result.origin.y = target.minY + (target.height - result.height) / 2 return result } } }
mit
24fbdab65d051efa078e8cf80cf0d84c
40.654255
157
0.572596
3.754075
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Jetpack/Jetpack Scan/JetpackScanThreatCell.swift
2
1361
import UIKit class JetpackScanThreatCell: UITableViewCell, NibReusable { @IBOutlet weak var iconBackgroundImageView: UIImageView! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! func configure(with model: JetpackScanThreatViewModel) { applyStyles() iconBackgroundImageView.backgroundColor = model.iconImageColor iconImageView.image = model.iconImage titleLabel.text = model.title detailLabel.text = model.description ?? "" detailLabel.isHidden = model.description == nil iconImageView.isHidden = model.isFixing iconBackgroundImageView.isHidden = model.isFixing selectionStyle = model.isFixing ? .none : .default accessoryType = model.isFixing ? .none : .disclosureIndicator if model.isFixing { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } private func applyStyles() { titleLabel.font = WPStyleGuide.fontForTextStyle(.body, fontWeight: .medium) titleLabel.textColor = .text detailLabel.textColor = .textSubtle detailLabel.font = WPStyleGuide.fontForTextStyle(.subheadline) } }
gpl-2.0
eea566cf8d8c2f7f6cf5eb3cfa6bfca0
33.025
83
0.696547
5.791489
false
false
false
false
TwoRingSoft/shared-utils
Sources/PippinCore/Components/Environment.swift
1
6384
// // Environment.swift // Pippin // // Created by Andrew McKnight on 12/22/17. // import Foundation import PippinLibrary private class PippinDummyRDNSBundleSearchClass {} extension String { init(asRDNSForPippinSubpaths subpaths: [String]) { precondition(subpaths.count > 0) precondition(subpaths.filter({ $0.count > 0 }).count > 0) self = String(asRDNSWithSubpaths: [Bundle(for: PippinDummyRDNSBundleSearchClass.self).identifier] + subpaths) } } /// A protocol that components are tagged with that provides them a way to reach into their environment to use other components, like a logger. Please use responsibly :) public protocol EnvironmentallyConscious { var environment: Environment? { get set } } public extension Environment { /// Errors that may be used by apps to describe adverse situations related to the environment. enum Error: NSErrorConvertible { /// Expected an initialized `CoreDataController` but none was present. case missingCoreDataController /// Expected an initialized `InAppPurchaseVendor` but none was present. case missingInAppPurchaseVendor public var code: Int { switch self { case .missingCoreDataController: return 0 case .missingInAppPurchaseVendor: return 1 } } public var nsError: NSError { return NSError(domain: String(asRDNSForPippinSubpaths: ["environment", "error"]), code: code, userInfo: [:]) } } } /// A collection of references to objects containing app information and infrastructure. public class Environment: NSObject { // MARK: app information public let appName: String public let currentBuild: Build public let semanticVersion: SemanticVersion public let lastLaunchedBuild: Build? // MARK: infrastructure public var model: Model? public var crashReporter: CrashReporter? public var logger: Logger? public var alerter: Alerter? public var activityIndicator: ActivityIndicator? public var defaults: Defaults // MARK: components public var bugReporter: BugReporter? public var inAppPurchaseVendor: InAppPurchaseVendor? // MARK: sensors public var locator: Locator? // MARK: testing/development utilities #if DEBUG public var debugging: DebugMenuPresenter? #endif public var touchVisualizer: TouchVisualization? // MARK: look/feel public var fonts: Fonts public var colors: Colors public var sharedAssetsBundle: Bundle /// Initialize a new app environment. Sets up `appName`, `semanticVersion` and `currentBuild` propertiew from the main bundle. Wipes out the standard `UserDefaults` if the launch argument for it is activated. /// - Parameters: /// - defaults: Optionally provide an object conforming to `Defaults`. It's `environment?` property will be automatically set. If you don't need this, an instance of `DefaultDefaults` is generated for Pippin's internal use. /// - fonts: Optionally provide an object conforming to `Fonts`, otherwise Pippin constructs an instance of `DefaultFonts` for use in UI extensions like `InfoViewController`. /// - sharedAssetsBundle: If you use Pippin UI components that draw images to screen, specify which bundle they'll come from. Defaults to `Bundle.main`. /// - colors: Optionally provide an object conforming to `Colors`, otherwise Pippin constructs an instande of `DefaultColors` for use in UI extensions like `InfoViewController`. public init( defaults: Defaults = DefaultDefaults(), fonts: Fonts = DefaultFonts(), sharedAssetsBundle: Bundle = Bundle.main, colors: Colors = DefaultColors() ) { let bundle = Bundle.main self.appName = bundle.getAppName() self.semanticVersion = bundle.getSemanticVersion() self.currentBuild = bundle.getBuild() self.defaults = defaults self.fonts = fonts self.sharedAssetsBundle = sharedAssetsBundle self.colors = colors // get previous launch version self.lastLaunchedBuild = self.defaults.lastLaunchedBuild // memoize this launch version self.defaults.lastLaunchedVersion = semanticVersion self.defaults.lastLaunchedBuild = currentBuild super.init() self.defaults.environment = self if ProcessInfo.launchedWith(launchArgument: LaunchArgument.wipeDefaults) { let defaults = UserDefaults.standard defaults.dictionaryRepresentation().keys.forEach { defaults.setValue(nil, forKey: $0) } defaults.synchronize() } } /// Check a few standard override locations for the logging level to use with a new `Logger`. /// - Returns: A `LogLevel` found in an override, or `debug` for debugging builds or `info` for non-debug builds.. public func logLevel() -> LogLevel { // log verbosely for ui tests if ProcessInfo.launchedWith(launchArgument: LaunchArgument.uiTest) { return .verbose } // see if we have an xcode scheme launch argument if let launchArgumentValue = EnvironmentVariable.logLevel.value(), let logLevel = LogLevel(launchArgumentValue), logLevel != LogLevel.unknown { return logLevel } // see if we have a user default saved if let defaultsLevel = defaults.logLevel, defaultsLevel != LogLevel.unknown { return defaultsLevel } #if DEBUG return .debug #else return .info #endif } /// Goes through each property that conforms to `EnvironmentallyConscious` and assigns the back reference to the `Environment` to which it belongs. public func connectEnvironment() { logger?.environment = self alerter?.environment = self model?.environment = self crashReporter?.environment = self activityIndicator?.environment = self bugReporter?.environment = self inAppPurchaseVendor?.environment = self locator?.environment = self #if DEBUG debugging?.environment = self #endif touchVisualizer?.environment = self defaults.environment = self } }
mit
d82fcb3fc5e72fd535b47a8042132ad8
37.926829
230
0.675439
5.054632
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InputFormatterPopover.swift
1
6479
// // InputFormatterPopover.swift // Telegram // // Created by keepcoder on 27/10/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit private enum InputFormatterViewState { case normal case link } private class InputFormatterView : NSView { let link: TitleButton = TitleButton() let linkField: NSTextField = NSTextField(frame: NSMakeRect(0, 0, 30, 18)) let dismissLink:ImageButton = ImageButton() fileprivate var state: InputFormatterViewState = .link required override init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(linkField) addSubview(link) addSubview(dismissLink) dismissLink.set(image: theme.icons.recentDismiss, for: .Normal) _ = dismissLink.sizeToFit() // linkField.placeholderAttributedString = NSAttributedString.initialize(string: strings().inputFormatterSetLink, color: theme.colors.grayText, font: .normal(.text)) linkField.font = .normal(.text) linkField.wantsLayer = true linkField.isEditable = true linkField.isSelectable = true linkField.maximumNumberOfLines = 1 linkField.backgroundColor = .clear linkField.drawsBackground = false linkField.isBezeled = false linkField.isBordered = false linkField.focusRingType = .none // linkField.delegate = self link.set(handler: { [weak self] _ in self?.change(state: .link, animated: true) }, for: .Click) dismissLink.centerY(x: frame.width - 10 - dismissLink.frame.width) dismissLink.isHidden = true change(state: .link, animated: false) } func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if commandSelector == #selector(insertNewline(_:)) { return true } return false } func change(state: InputFormatterViewState, animated: Bool) { self.state = state switch state { case .normal: link.isHidden = false link._change(opacity: 1.0, animated: animated) dismissLink._change(opacity: 0, animated: animated, completion: { [weak self] completed in if completed { self?.dismissLink.isHidden = true } }) linkField._change(opacity: 0, animated: animated, completion: { [weak self] completed in if completed { self?.linkField.isHidden = true } }) case .link: linkField.isHidden = false dismissLink.isHidden = false linkField._change(opacity: 1.0, animated: animated) dismissLink._change(opacity: 1.0, animated: animated) link._change(opacity: 0, animated: animated, completion: { [weak self] completed in if completed { self?.link.isHidden = true } }) } } override func layout() { super.layout() linkField.setFrameSize(frame.width - link.frame.width - 10, 18) linkField.centerY(x: 10) linkField.textView?.frame = linkField.bounds switch state { case .normal: link.centerY(x: 0) case .link: link.centerY(x: frame.width - link.frame.width) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } final class InputFormatterArguments { let link:(String)->Void init(link:@escaping(String)->Void) { self.link = link } } private final class FormatterViewController : NSViewController { override var acceptsFirstResponder: Bool { return true } } class InputFormatterPopover: NSPopover { private let window: Window init(_ arguments: InputFormatterArguments, window: Window) { self.window = window super.init() let controller = FormatterViewController() let view = InputFormatterView(frame: NSMakeRect(0, 0, 240, 40)) controller.view = view view.dismissLink.set(handler: { [weak self] _ in self?.close() }, for: .Click) self.contentViewController = controller window.set(handler: { [weak view] _ -> KeyHandlerResult in if let view = view { if view.state == .link { let attr = view.linkField.attributedStringValue.mutableCopy() as! NSMutableAttributedString attr.detectLinks(type: [.Links]) var url:String? = nil attr.enumerateAttribute(NSAttributedString.Key.link, in: attr.range, options: NSAttributedString.EnumerationOptions(rawValue: 0), using: { (value, range, stop) in if let value = value as? inAppLink { switch value { case let .external(link, _): url = link break default: break } } let s: ObjCBool = (url != nil) ? true : false stop.pointee = s }) if let url = url { arguments.link(url) } else { view.shake() } } return .invoked } return .rejected }, with: self, for: .Return, priority: .modal) window.set(handler: { [weak self] _ -> KeyHandlerResult in self?.close() return .invoked }, with: self, for: .Escape, priority: .modal) } deinit { window.removeAllHandlers(for: self) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
a4e34a3a7d3fd72398ce588c9d2e1b1b
29.271028
182
0.521457
5.318555
false
false
false
false
s-aska/Justaway-for-iOS
Justaway/TwitterUserCell.swift
1
5425
// // TwitterUserCell.swift // Justaway // // Created by Shinichiro Aska on 6/7/15. // Copyright (c) 2015 Shinichiro Aska. All rights reserved. // import UIKit class TwitterUserCell: BackgroundTableViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var displayNameLabel: DisplayNameLable! @IBOutlet weak var screenNameLabel: ScreenNameLable! @IBOutlet weak var protectedLabel: UILabel! @IBOutlet weak var descriptionLabel: StatusLable! @IBOutlet weak var textHeightConstraint: NSLayoutConstraint! @IBOutlet weak var followButton: FollowButton! @IBOutlet weak var unfollowButton: BaseButton! @IBOutlet weak var blockLabel: TextLable! @IBOutlet weak var muteLabel: TextLable! @IBOutlet weak var retweetLabel: TextLable! @IBOutlet weak var retweetDeleteLabel: TextLable! @IBOutlet weak var followingLabel: TextLable! @IBOutlet weak var followerLabel: TextLable! @IBOutlet weak var listsLabel: TextLable! var user: TwitterUserFull? // MARK: - View Life Cycle override func awakeFromNib() { super.awakeFromNib() configureView() } // MARK: - Configuration func configureView() { selectionStyle = .none separatorInset = UIEdgeInsets.zero layoutMargins = UIEdgeInsets.zero preservesSuperviewLayoutMargins = false iconImageView.layer.cornerRadius = 6 iconImageView.clipsToBounds = true iconImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openProfile(_:)))) iconImageView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(openUserMenu(_:)))) followButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(openUserMenu(_:)))) } func openProfile(_ sender: UIGestureRecognizer) { if let user = user { ProfileViewController.show(user) } } func openUserMenu(_ sender: UILongPressGestureRecognizer) { if sender.state != .began { return } guard let account = AccountSettingsStore.get()?.account(), let view = sender.view else { return } if let user = user { Relationship.checkUser(account.userID, targetUserID: user.userID, callback: { (relationshop) in UserAlert.show(view, user: TwitterUser(user), userFull: user, relationship: relationshop) }) } } @IBAction func follow(_ sender: UIButton) { guard let account = AccountSettingsStore.get()?.account() else { return } if let user = user { Relationship.checkUser(account.userID, targetUserID: user.userID, callback: { (relationshop) in if relationshop.following { let actionSheet = UIAlertController(title: "Unfollow @\(user.screenName)?", message: nil, preferredStyle: .alert) actionSheet.addAction(UIAlertAction( title: "Cancel", style: .cancel, handler: { action in })) actionSheet.addAction(UIAlertAction( title: "Unfollow", style: .default, handler: { action in Twitter.unfollow(user.userID) { self.followButton.isHidden = false self.unfollowButton.isHidden = true } })) // iPad actionSheet.popoverPresentationController?.sourceView = sender actionSheet.popoverPresentationController?.sourceRect = sender.bounds AlertController.showViewController(actionSheet) } else { let actionSheet = UIAlertController(title: "Follow @\(user.screenName)?", message: nil, preferredStyle: .alert) actionSheet.addAction(UIAlertAction( title: "Cancel", style: .cancel, handler: { action in })) actionSheet.addAction(UIAlertAction( title: "Follow", style: .default, handler: { action in Twitter.follow(user.userID) { self.followButton.isHidden = true self.unfollowButton.isHidden = false } })) // iPad actionSheet.popoverPresentationController?.sourceView = sender actionSheet.popoverPresentationController?.sourceRect = sender.bounds AlertController.showViewController(actionSheet) } }) } } @IBAction func menu(_ sender: UIButton) { guard let account = AccountSettingsStore.get()?.account() else { return } if let user = user { Relationship.checkUser(account.userID, targetUserID: user.userID, callback: { (relationshop) in UserAlert.show(sender, user: TwitterUser(user), userFull: user, relationship: relationshop) }) } } }
mit
97820917342126d530b33ad48cbc8aaa
38.59854
133
0.577696
5.916031
false
false
false
false
hollance/swift-algorithm-club
Topological Sort/TopologicalSort1.swift
2
988
extension Graph { private func depthFirstSearch(_ source: Node, visited: inout [Node : Bool]) -> [Node] { var result = [Node]() visited[source] = true if let adjacencyList = adjacencyList(forNode: source) { for nodeInAdjacencyList in adjacencyList { if let seen = visited[nodeInAdjacencyList], !seen { result = depthFirstSearch(nodeInAdjacencyList, visited: &visited) + result } } } return [source] + result } /* Topological sort using depth-first search. */ public func topologicalSort() -> [Node] { let startNodes = calculateInDegreeOfNodes().filter({ _, indegree in return indegree == 0 }).map({ node, _ in return node }) var visited = [Node: Bool]() for (node, _) in adjacencyLists { visited[node] = false } var result = [Node]() for startNode in startNodes { result = depthFirstSearch(startNode, visited: &visited) + result } return result } }
mit
e98680e95c22033aa42ad6fe4a229c44
25
89
0.620445
4.430493
false
false
false
false
V-FEXrt/DebuggedPodcast
Sources/App/Utilities/Validator.swift
1
1558
// // Validator.swift // DebuggedPodcast // // Created by Ashley Coleman on 4/8/17. // // import Vapor import HTTP enum Type { case Int case String case Bool } class Validator { static func validate(req: Request, expected:[String: Type]) throws -> (string: [String: String], int: [String: Int], bool: [String: Bool]) { var stringParams:[String:String] = [:] var intParams:[String:Int] = [:] var boolParams:[String:Bool] = [:] for item in expected{ switch item.value { case .Int: if let val = req.data[item.key]?.int { intParams[item.key] = val }else{ throw Abort.custom(status: Status.badRequest, message: "\(item.key) should be type: Int") } break case .String: if let val = req.data[item.key]?.string { stringParams[item.key] = val }else{ throw Abort.custom(status: Status.badRequest, message: "\(item.key) should be type: String") } break case .Bool: if let val = req.data[item.key]?.bool { boolParams[item.key] = val }else{ throw Abort.custom(status: Status.badRequest, message: "\(item.key) should be type: Bool") } break } } return (stringParams, intParams, boolParams) } }
mit
6db99f14e166d82d8fbf63d3b6a2591e
27.851852
144
0.486521
4.376404
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/ViewControllers/Views/ImageCollectionViewHeader.swift
2
1720
// // ImageCollectionViewHeader.swift // SwiftNetworkImages // // Created by Arseniy on 4/5/16. // Copyright © 2016 Arseniy Kuznetsov. All rights reserved. // import UIKit /// A custom UICollectionReusableView section header class ImageCollectionViewHeader: UICollectionReusableView { var sectionHeaderLabel: UILabel? var sectionHeaderText: String? { didSet { sectionHeaderLabel?.text = sectionHeaderText } } // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) sectionHeaderLabel = UILabel().configure { $0.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) $0.text = "Section Header" $0.textAlignment = .center self.addSubview($0) $0.translatesAutoresizingMaskIntoConstraints = false } backgroundColor = .lightGray setConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } extension ImageCollectionViewHeader { // MARK: - 📐Constraints func setConstraints() { guard let sectionHeaderLabel = sectionHeaderLabel else {return} NSLayoutConstraint.activate([ sectionHeaderLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor), sectionHeaderLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor), sectionHeaderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20) ]) } } // MARK: - 🐞Debug configuration extension ImageCollectionViewHeader: DebugConfigurable { func _configureForDebug() { backgroundColor = .magenta } }
mit
9b4aff447cc784cafedea32fd765706e
26.190476
98
0.663748
5.254601
false
true
false
false
austinzheng/swift
test/ClangImporter/ctypes_parse_objc.swift
12
2321
// RUN: %target-typecheck-verify-swift %clang-importer-sdk -enable-objc-interop import ctypes import CoreGraphics import Foundation import CoreFoundation var cgPointVar: CGPoint // FIXME: Import arrays as real array-looking things. func testArrays() { let fes: NSFastEnumerationState var ulong: CUnsignedLong var pulong: UnsafeMutablePointer<CUnsignedLong> ulong = fes.state pulong = fes.mutationsPtr ulong = fes.extra.0 ulong = fes.extra.1 ulong = fes.extra.2 ulong = fes.extra.3 ulong = fes.extra.4 _ = ulong; _ = pulong } // FIXME: Import pointers to opaque types as unique types. func testPointers() { let cfstr: CFString? _ = cfstr as CFTypeRef? } // Ensure that imported structs can be extended, even if typedef'ed on the C // side. extension NSFastEnumerationState { func reset() {} } extension CGRectTy { init(x: Double, y: Double, w: Double, h: Double) { origin.x = CGFloat(x) origin.y = CGFloat(y) size.width = CGFloat(w) size.height = CGFloat(h) } } extension CGRect { func printAsX11Geometry() { print("\(size.width)x\(size.height)+\(origin.x)+\(origin.y)", terminator: "") } } func testImportMacTypes() { // Test that we import integer and floating-point types as swift stdlib // types. var a : UInt32 = UInt32_test a = a + 1 var b : Float64 = Float64_test b = b + 1 var t9_unqual : Float32 = Float32_test var t10_unqual : Float64 = Float64_test var t9_qual : ctypes.Float32 = 0.0 // expected-error {{no type named 'Float32' in module 'ctypes'}} var t10_qual : ctypes.Float64 = 0.0 // expected-error {{no type named 'Float64' in module 'ctypes'}} } func testImportCFTypes() { let t1_unqual: UInt = CFTypeID_test _ = t1_unqual as CoreFoundation.CFTypeID let t2_unqual: UInt = CFOptionFlags_test _ = t2_unqual as CoreFoundation.CFOptionFlags let t3_unqual: UInt = CFHashCode_test _ = t3_unqual as CoreFoundation.CFHashCode let t4_unqual: Int = CFIndex_test _ = t4_unqual as CoreFoundation.CFIndex } func testImportSEL() { var t1 : SEL // expected-error {{use of undeclared type 'SEL'}} {{12-15=Selector}} var t2 : ctypes.SEL // expected-error {{no type named 'SEL' in module 'ctypes'}} } func testStructDefaultInit() { let _ = NonNilableReferences() // expected-error{{missing argument}} }
apache-2.0
c586cf02e24fc976aa54d302e50a29f5
23.956989
102
0.691943
3.490226
false
true
false
false
eastsss/ErrorDispatching
ErrorDispatching/Classes/Core/Utilities/StandardErrorString.swift
1
1229
// // StandardErrorString.swift // ErrorDispatching // // Created by Anatoliy Radchenko on 04/03/2017. // // import Foundation enum LocalizationPrefix: String { case title = "com.errordispatching.title" case message = "com.errordispatching.message" case action = "com.errordispatching.action" } class StandardErrorString { static func title(forKey key: String) -> String { return loadString(for: .title, postfix: key) } static func message(forKey key: String) -> String { return loadString(for: .message, postfix: key) } static func action(forKey key: String) -> String { return loadString(for: .action, postfix: key) } } //MARK: Supporting methods private extension StandardErrorString { static func loadString(for prefix: LocalizationPrefix, postfix: String) -> String { let framework = Bundle(for: StandardErrorString.self) let path = NSURL(fileURLWithPath: framework.resourcePath!).appendingPathComponent("ErrorDispatching.bundle") let bundle = Bundle(url: path!)! let key = "\(prefix.rawValue).\(postfix)" return bundle.localizedString(forKey: key, value: nil, table: "StandardErrors") } }
mit
c14bab2fe128116649bcbf30dbefbc7f
28.97561
116
0.679414
4.267361
false
false
false
false
kzaher/RxSwift
Tests/RxSwiftTests/Observable+TakeLastTests.swift
6
6841
// // Observable+TakeLastTests.swift // Tests // // Created by Krunoslav Zaher on 4/29/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxTest class ObservableTakeLastTest : RxTest { } extension ObservableTakeLastTest { func testTakeLast_Complete_Less() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13), .next(270, 7), .next(280, 1), .next(300, -1), .completed(300) ]) let res = scheduler.start { xs.takeLast(7) } XCTAssertEqual(res.events, [ .next(300, 9), .next(300, 13), .next(300, 7), .next(300, 1), .next(300, -1), .completed(300) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 300) ]) } func testTakeLast_Complete_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13), .next(270, 7), .next(280, 1), .next(300, -1), .completed(310) ]) let res = scheduler.start { xs.takeLast(5) } XCTAssertEqual(res.events, [ .next(310, 9), .next(310, 13), .next(310, 7), .next(310, 1), .next(310, -1), .completed(310) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 310) ]) } func testTakeLast_Complete_More() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13), .next(270, 7), .next(280, 1), .next(300, -1), .next(310, 3), .next(340, 8), .completed(350) ]) let res = scheduler.start { xs.takeLast(5) } XCTAssertEqual(res.events, [ .next(350, 7), .next(350, 1), .next(350, -1), .next(350, 3), .next(350, 8), .completed(350) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 350) ]) } func testTakeLast_Error_Less() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13), .next(270, 7), .next(280, 1), .next(290, 64), .error(300, testError) ]) let res = scheduler.start { xs.takeLast(7) } XCTAssertEqual(res.events, [ .error(300, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 300) ]) } func testTakeLast_Error_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13), .next(270, 7), .next(280, 1), .next(300, -1), .error(310, testError) ]) let res = scheduler.start { xs.takeLast(5) } XCTAssertEqual(res.events, [ .error(310, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 310) ]) } func testTakeLast_Error_More() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13), .next(270, 7), .next(280, 1), .next(300, -1), .next(310, 3), .next(340, 64), .error(360, testError) ]) let res = scheduler.start { xs.takeLast(5) } XCTAssertEqual(res.events, [ .error(360, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 360) ]) } func testTakeLast_0_DefaultScheduler() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13) ]) let res = scheduler.start { xs.takeLast(0) } XCTAssertEqual(res.events, [ ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) } func testTakeLast_TakeLast1() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ .next(70, 6), .next(150, 4), .next(210, 9), .next(230, 13), .next(270, 7), .next(280, 1), .next(300, -1), .next(310, 3), .next(340, 8), .next(370, 11), .completed(400) ]) let res = scheduler.start { xs.takeLast(3) } XCTAssertEqual(res.events, [ .next(400, 3), .next(400, 8), .next(400, 11), .completed(400) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } func testTakeLast_DecrementCountsFirst() { let k = BehaviorSubject(value: false) var elements = [Bool]() _ = k.takeLast(1).subscribe(onNext: { n in elements.append(n) k.on(.next(!n)) }) k.on(.completed) XCTAssertEqual(elements, [false]) } #if TRACE_RESOURCES func testTakeLastReleasesResourcesOnComplete() { _ = Observable<Int>.of(1, 2).takeLast(1).subscribe() } func testTakeLastReleasesResourcesOnError() { _ = Observable<Int>.error(testError).takeLast(1).subscribe() } #endif }
mit
49018a95ac094cf3b9632ed0b05de9db
23.782609
68
0.436257
4.430052
false
true
false
false
piv199/EZSwiftExtensions
Sources/CGFloatExtensions.swift
2
2659
// // CGFloatExtensions.swift // EZSwiftExtensions // // Created by Cem Olcay on 12/08/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension CGFloat { /// EZSE: Return the central value of CGFloat. public var center: CGFloat { return (self / 2) } @available(*, deprecated: 1.8, renamed: "degreesToRadians") public func toRadians() -> CGFloat { return (.pi * self) / 180.0 } /// EZSwiftExtensions public func degreesToRadians() -> CGFloat { return (.pi * self) / 180.0 } /// EZSwiftExtensions public mutating func toRadiansInPlace() { self = (.pi * self) / 180.0 } /// EZSE: Converts angle degrees to radians. public static func degreesToRadians(_ angle: CGFloat) -> CGFloat { return (.pi * angle) / 180.0 } /// EZSE: Converts radians to degrees. public func radiansToDegrees() -> CGFloat { return (180.0 * self) / .pi } /// EZSE: Converts angle radians to degrees mutable version. public mutating func toDegreesInPlace() { self = (180.0 * self) / .pi } /// EZSE : Converts angle radians to degrees static version. public static func radiansToDegrees(_ angleInDegrees: CGFloat) -> CGFloat { return (180.0 * angleInDegrees) / .pi } /// EZSE: Returns a random floating point number between 0.0 and 1.0, inclusive. public static func random() -> CGFloat { return CGFloat(Float(arc4random()) / 0xFFFFFFFF) } /// EZSE: Returns a random floating point number in the range min...max, inclusive. public static func random(within: Range<CGFloat>) -> CGFloat { return CGFloat.random() * (within.upperBound - within.lowerBound) + within.lowerBound } /// EZSE: Returns a random floating point number in the range min...max, inclusive. public static func random(within: ClosedRange<CGFloat>) -> CGFloat { return CGFloat.random() * (within.upperBound - within.lowerBound) + within.lowerBound } /** EZSE :Returns the shortest angle between two angles. The result is always between -π and π. Inspired from : https://github.com/raywenderlich/SKTUtils/blob/master/SKTUtils/CGFloat%2BExtensions.swift */ public static func shortestAngleInRadians(from first: CGFloat, to second: CGFloat) -> CGFloat { let twoPi = CGFloat(.pi * 2.0) var angle = (second - first).truncatingRemainder(dividingBy: twoPi) if angle >= .pi { angle = angle - twoPi } if angle <= -.pi { angle = angle + twoPi } return angle } }
mit
443cc7bbfd26768dc65be4f954698af0
31.012048
111
0.630787
4.355738
false
false
false
false
mozilla-mobile/firefox-ios
Sync/SyncStateMachine.swift
2
43706
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Account private let log = Logger.syncLogger private let StorageVersionCurrent = 5 // Names of collections that can be enabled/disabled locally. public let TogglableEngines: [String] = [ "bookmarks", "history", "tabs", "passwords" ] // Names of collections for which a synchronizer is implemented locally. private let LocalEngines: [String] = TogglableEngines + ["clients"] // Names of collections which will appear in a default meta/global produced locally. // Map collection name to engine version. See http://docs.services.mozilla.com/sync/objectformats.html. private let DefaultEngines: [String: Int] = [ "bookmarks": 2, "clients": ClientsStorageVersion, "history": HistoryStorageVersion, "tabs": 1, // We opt-in to syncing collections we don't know about, since no client offers to sync non-enabled, // non-declined engines yet. See Bug 969669. "passwords": 1, "forms": 1, "addons": 1, "prefs": 2, "addresses": 1, "creditcards": 1, ] // Names of collections which will appear as declined in a default // meta/global produced locally. private let DefaultDeclined: [String] = [String]() public func computeNewEngines(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> (engines: [String: EngineMeta], declined: [String]) { var enabled: Set<String> = Set(engineConfiguration.enabled) var declined: Set<String> = Set(engineConfiguration.declined) var engines: [String: EngineMeta] = [:] if let enginesEnablements = enginesEnablements { let enabledLocally = Set(enginesEnablements.filter { $0.value }.map { $0.key }) let declinedLocally = Set(enginesEnablements.filter { !$0.value }.map { $0.key }) enabled.subtract(declinedLocally) declined.subtract(enabledLocally) enabled.formUnion(enabledLocally) declined.formUnion(declinedLocally) } for engine in enabled { // We take this device's version, or, if we don't know the correct version, 0. Another client should recognize // the engine, see an old version, wipe and start again. // TODO: this client does not yet do this wipe-and-update itself! let version = DefaultEngines[engine] ?? 0 engines[engine] = EngineMeta(version: version, syncID: Bytes.generateGUID()) } return (engines: engines, declined: Array(declined)) } // public for testing. public func createMetaGlobalWithEngineConfiguration(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> MetaGlobal { let (engines, declined) = computeNewEngines(engineConfiguration, enginesEnablements: enginesEnablements) return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: engines, declined: declined) } public func createMetaGlobal(enginesEnablements: [String: Bool]?) -> MetaGlobal { let engineConfiguration = EngineConfiguration(enabled: Array(DefaultEngines.keys), declined: DefaultDeclined) return createMetaGlobalWithEngineConfiguration(engineConfiguration, enginesEnablements: enginesEnablements) } public typealias TokenSource = () -> Deferred<Maybe<TokenServerToken>> public typealias ReadyDeferred = Deferred<Maybe<Ready>> // See docs in docs/sync.md. // You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine // does. Well, such a client is pinned to a particular server, and this state machine must // acknowledge that a Sync client occasionally must migrate between two servers, preserving // some state from the last. // The resultant 'Ready' will be able to provide a suitably initialized storage client. open class SyncStateMachine { // The keys are used as a set, to prevent cycles in the state machine. var stateLabelsSeen = [SyncStateLabel: Bool]() var stateLabelSequence = [SyncStateLabel]() let stateLabelsAllowed: Set<SyncStateLabel> let scratchpadPrefs: Prefs /// Use this set of states to constrain the state machine to attempt the barest /// minimum to get to Ready. This is suitable for extension uses. If it is not possible, /// then no destructive or expensive actions are taken (e.g. total HTTP requests, /// duration, records processed, database writes, fsyncs, blanking any local collections) public static let OptimisticStates = Set(SyncStateLabel.optimisticValues) /// The default set of states that the state machine is allowed to use. public static let AllStates = Set(SyncStateLabel.allValues) public init(prefs: Prefs, allowingStates labels: Set<SyncStateLabel> = SyncStateMachine.AllStates) { self.scratchpadPrefs = prefs.branch("scratchpad") self.stateLabelsAllowed = labels } open class func clearStateFromPrefs(_ prefs: Prefs) { log.debug("Clearing all Sync prefs.") Scratchpad.clearFromPrefs(prefs.branch("scratchpad")) // XXX this is convoluted. prefs.clearAll() } fileprivate func advanceFromState(_ state: SyncState) -> ReadyDeferred { log.info("advanceFromState: \(state.label)") // Record visibility before taking any action. let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: state.label) != nil stateLabelSequence.append(state.label) if let ready = state as? Ready { // Sweet, we made it! return deferMaybe(ready) } // Cycles are not necessarily a problem, but seeing the same (recoverable) error condition is a problem. if state is RecoverableSyncState && labelAlreadySeen { return deferMaybe(StateMachineCycleError()) } guard stateLabelsAllowed.contains(state.label) else { return deferMaybe(DisallowedStateError(state.label, allowedStates: stateLabelsAllowed)) } return state.advance() >>== self.advanceFromState } open func toReady(_ authState: SyncAuthState) -> ReadyDeferred { let readyDeferred = ReadyDeferred() RustFirefoxAccounts.shared.accountManager.uponQueue(.main) { accountManager in authState.token(Date.now(), canBeExpired: false).uponQueue(.main) { success in guard let (token, kSync) = success.successValue else { readyDeferred.fill(Maybe(failure: success.failureValue ?? FxAClientError.local(NSError()))) return } log.debug("Got token from auth state.") if Logger.logPII { log.debug("Server is \(token.api_endpoint).") } let prior = Scratchpad.restoreFromPrefs(self.scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync)) if prior == nil { log.info("No persisted Sync state. Starting over.") } var scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKSync(kSync), persistingTo: self.scratchpadPrefs) // Take the scratchpad and add the fxaDeviceId from the state, and hashedUID from the token let b = Scratchpad.Builder(p: scratchpad) if let deviceID = accountManager.deviceConstellation()?.state()?.localDevice?.id { b.fxaDeviceId = deviceID } else { // Either deviceRegistration hasn't occurred yet (our bug) or // FxA has given us an UnknownDevice error. log.warning("Device registration has not taken place before sync.") } b.hashedUID = token.hashedFxAUID if let enginesEnablements = authState.enginesEnablements, !enginesEnablements.isEmpty { b.enginesEnablements = enginesEnablements } if let clientName = authState.clientName { b.clientName = clientName } // Detect if we've changed anything in our client record from the last time we synced… let ourClientUnchanged = (b.fxaDeviceId == scratchpad.fxaDeviceId) // …and if so, trigger a reset of clients. if !ourClientUnchanged { b.localCommands.insert(LocalCommand.resetEngine(engine: "clients")) } scratchpad = b.build() log.info("Advancing to InitialWithLiveToken.") let state = InitialWithLiveToken(scratchpad: scratchpad, token: token) // Start with fresh visibility data. self.stateLabelsSeen = [:] self.stateLabelSequence = [] self.advanceFromState(state).uponQueue(.main) { success in readyDeferred.fill(success) } } } return readyDeferred } } public enum SyncStateLabel: String { case Stub = "STUB" // For 'abstract' base classes. case InitialWithExpiredToken = "initialWithExpiredToken" case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo" case InitialWithLiveToken = "initialWithLiveToken" case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo" case ResolveMetaGlobalVersion = "resolveMetaGlobalVersion" case ResolveMetaGlobalContent = "resolveMetaGlobalContent" case NeedsFreshMetaGlobal = "needsFreshMetaGlobal" case NewMetaGlobal = "newMetaGlobal" case HasMetaGlobal = "hasMetaGlobal" case NeedsFreshCryptoKeys = "needsFreshCryptoKeys" case HasFreshCryptoKeys = "hasFreshCryptoKeys" case Ready = "ready" case FreshStartRequired = "freshStartRequired" // Go around again... once only, perhaps. case ServerConfigurationRequired = "serverConfigurationRequired" case ChangedServer = "changedServer" case MissingMetaGlobal = "missingMetaGlobal" case MissingCryptoKeys = "missingCryptoKeys" case MalformedCryptoKeys = "malformedCryptoKeys" case SyncIDChanged = "syncIDChanged" case RemoteUpgradeRequired = "remoteUpgradeRequired" case ClientUpgradeRequired = "clientUpgradeRequired" static let allValues: [SyncStateLabel] = [ InitialWithExpiredToken, InitialWithExpiredTokenAndInfo, InitialWithLiveToken, InitialWithLiveTokenAndInfo, NeedsFreshMetaGlobal, ResolveMetaGlobalVersion, ResolveMetaGlobalContent, NewMetaGlobal, HasMetaGlobal, NeedsFreshCryptoKeys, HasFreshCryptoKeys, Ready, FreshStartRequired, ServerConfigurationRequired, ChangedServer, MissingMetaGlobal, MissingCryptoKeys, MalformedCryptoKeys, SyncIDChanged, RemoteUpgradeRequired, ClientUpgradeRequired, ] // This is the list of states needed to get to Ready, or failing. // This is useful in circumstances where it is important to conserve time and/or battery, and failure // to timely sync is acceptable. static let optimisticValues: [SyncStateLabel] = [ InitialWithLiveToken, InitialWithLiveTokenAndInfo, HasMetaGlobal, HasFreshCryptoKeys, Ready, ] } /** * States in this state machine all implement SyncState. * * States are either successful main-flow states, or (recoverable) error states. * Errors that aren't recoverable are simply errors. * Main-flow states flow one to one. * * (Terminal failure states might be introduced at some point.) * * Multiple error states (but typically only one) can arise from each main state transition. * For example, parsing meta/global can result in a number of different non-routine situations. * * For these reasons, and the lack of useful ADTs in Swift, we model the main flow as * the success branch of a Result, and the recovery flows as a part of the failure branch. * * We could just as easily use a ternary Either-style operator, but thanks to Swift's * optional-cast-let it's no saving to do so. * * Because of the lack of type system support, all RecoverableSyncStates must have the same * signature. That signature implies a possibly multi-state transition; individual states * will have richer type signatures. */ public protocol SyncState { var label: SyncStateLabel { get } func advance() -> Deferred<Maybe<SyncState>> } /* * Base classes to avoid repeating initializers all over the place. */ open class BaseSyncState: SyncState { open var label: SyncStateLabel { return SyncStateLabel.Stub } public let client: Sync15StorageClient! let token: TokenServerToken // Maybe expired. var scratchpad: Scratchpad // TODO: 304 for i/c. open func getInfoCollections() -> Deferred<Maybe<InfoCollections>> { return chain(self.client.getInfoCollections(), f: { return $0.value }) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } open func synchronizer<T: Synchronizer>(_ synchronizerClass: T.Type, delegate: SyncDelegate, prefs: Prefs, why: SyncReason) -> T { return T(scratchpad: self.scratchpad, delegate: delegate, basePrefs: prefs, why: why) } // This isn't a convenience initializer 'cos subclasses can't call convenience initializers. public init(scratchpad: Scratchpad, token: TokenServerToken) { let workQueue = DispatchQueue.global() let resultQueue = DispatchQueue.main let backoff = scratchpad.backoffStorage let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff) self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(StubStateError()) } } open class BaseSyncStateWithInfo: BaseSyncState { public let info: InfoCollections init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(client: client, scratchpad: scratchpad, token: token) } init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(scratchpad: scratchpad, token: token) } } /* * Error types. */ public protocol SyncError: MaybeErrorType, SyncPingFailureFormattable {} extension SyncError { public var failureReasonName: SyncPingFailureReasonName { return .unexpectedError } } open class UnknownError: SyncError { open var description: String { return "Unknown error." } } open class StateMachineCycleError: SyncError { open var description: String { return "The Sync state machine encountered a cycle. This is a coding error." } } open class CouldNotFetchMetaGlobalError: SyncError { open var description: String { return "Could not fetch meta/global." } } open class CouldNotFetchKeysError: SyncError { open var description: String { return "Could not fetch crypto/keys." } } open class StubStateError: SyncError { open var description: String { return "Unexpectedly reached a stub state. This is a coding error." } } open class ClientUpgradeRequiredError: SyncError { let targetStorageVersion: Int public init(target: Int) { self.targetStorageVersion = target } open var description: String { return "Client upgrade required to work with storage version \(self.targetStorageVersion)." } } open class InvalidKeysError: SyncError { let keys: Keys public init(_ keys: Keys) { self.keys = keys } open var description: String { return "Downloaded crypto/keys, but couldn't parse them." } } open class DisallowedStateError: SyncError { let state: SyncStateLabel let allowedStates: Set<SyncStateLabel> public init(_ state: SyncStateLabel, allowedStates: Set<SyncStateLabel>) { self.state = state self.allowedStates = allowedStates } open var description: String { return "Sync state machine reached \(String(describing: state)) state, which is disallowed. Legal states are: \(String(describing: allowedStates))" } } /** * Error states. These are errors that can be recovered from by taking actions. We use RecoverableSyncState as a * sentinel: if we see the same recoverable state twice, we bail out and complain that we've seen a cycle. (Seeing * some states -- principally initial states -- twice is fine.) */ public protocol RecoverableSyncState: SyncState { } /** * Recovery: discard our local timestamps and sync states; discard caches. * Be prepared to handle a conflict between our selected engines and the new * server's meta/global; if an engine is selected locally but not declined * remotely, then we'll need to upload a new meta/global and sync that engine. */ open class ChangedServerError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ChangedServer } let newToken: TokenServerToken let newScratchpad: Scratchpad public init(scratchpad: Scratchpad, token: TokenServerToken) { self.newToken = token self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs) } open func advance() -> Deferred<Maybe<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken) return deferMaybe(state) } } /** * Recovery: same as for changed server, but no need to upload a new meta/global. */ open class SyncIDChangedError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged } fileprivate let previousState: BaseSyncStateWithInfo fileprivate let newMetaGlobal: Fetched<MetaGlobal> public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) { self.previousState = previousState self.newMetaGlobal = newMetaGlobal } open func advance() -> Deferred<Maybe<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint() let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info) return deferMaybe(state) } } /** * Recovery: configure the server. */ open class ServerConfigurationRequiredError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ServerConfigurationRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { let client = self.previousState.client! let oldScratchpad = self.previousState.scratchpad let enginesEnablements = oldScratchpad.enginesEnablements let s = oldScratchpad.evolve() .setGlobal(nil) .addLocalCommandsFromKeys(nil) .setKeys(nil) .clearEnginesEnablements() .build().checkpoint() // Upload a new meta/global ... let metaGlobal: MetaGlobal if let oldEngineConfiguration = s.engineConfiguration { metaGlobal = createMetaGlobalWithEngineConfiguration(oldEngineConfiguration, enginesEnablements: enginesEnablements) } else { metaGlobal = createMetaGlobal(enginesEnablements: enginesEnablements) } return client.uploadMetaGlobal(metaGlobal, ifUnmodifiedSince: nil) // ... and a new crypto/keys. >>> { return client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: s.syncKeyBundle, ifUnmodifiedSince: nil) } >>> { return deferMaybe(InitialWithLiveToken(client: client, scratchpad: s, token: self.previousState.token)) } } } /** * Recovery: wipe the server (perhaps unnecessarily) and proceed to configure the server. */ open class FreshStartRequiredError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.FreshStartRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { let client = self.previousState.client! return client.wipeStorage() >>> { return deferMaybe(ServerConfigurationRequiredError(previousState: self.previousState)) } } } open class MissingMetaGlobalError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class MissingCryptoKeysError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class RemoteUpgradeRequired: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.RemoteUpgradeRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class ClientUpgradeRequired: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ClientUpgradeRequired } fileprivate let previousState: BaseSyncStateWithInfo let targetStorageVersion: Int public init(previousState: BaseSyncStateWithInfo, target: Int) { self.previousState = previousState self.targetStorageVersion = target } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(ClientUpgradeRequiredError(target: self.targetStorageVersion)) } } /* * Non-error states. */ open class InitialWithLiveToken: BaseSyncState { open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken } // This looks totally redundant, but try taking it out, I dare you. public override init(scratchpad: Scratchpad, token: TokenServerToken) { super.init(scratchpad: scratchpad, token: token) } // This looks totally redundant, but try taking it out, I dare you. public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { super.init(client: client, scratchpad: scratchpad, token: token) } func advanceWithInfo(_ info: InfoCollections) -> SyncState { return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { return chain(getInfoCollections(), f: self.advanceWithInfo) } } /** * Each time we fetch a new meta/global, we need to reconcile it with our * current state. * * It might be identical to our current meta/global, in which case we can short-circuit. * * We might have no previous meta/global at all, in which case this state * simply configures local storage to be ready to sync according to the * supplied meta/global. (Not necessarily datatype elections: those will be per-device.) * * Or it might be different. In this case the previous m/g and our local user preferences * are compared to the new, resulting in some actions and a final state. * * This states are similar in purpose to GlobalSession.processMetaGlobal in Android Sync. */ open class ResolveMetaGlobalVersion: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalVersion } class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalVersion { return ResolveMetaGlobalVersion(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // First: check storage version. let v = fetched.value.storageVersion if v > StorageVersionCurrent { // New storage version? Uh-oh. No recovery possible here. log.info("Client upgrade required for storage version \(v)") return deferMaybe(ClientUpgradeRequired(previousState: self, target: v)) } if v < StorageVersionCurrent { // Old storage version? Uh-oh. Wipe and upload both meta/global and crypto/keys. log.info("Server storage version \(v) is outdated.") return deferMaybe(RemoteUpgradeRequired(previousState: self)) } return deferMaybe(ResolveMetaGlobalContent.fromState(self, fetched: self.fetched)) } } open class ResolveMetaGlobalContent: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalContent } class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalContent { return ResolveMetaGlobalContent(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Check global syncID and contents. if let previous = self.scratchpad.global?.value { // Do checks that only apply when we're coming from a previous meta/global. if previous.syncID != fetched.value.syncID { log.info("Remote global sync ID has changed. Dropping keys and resetting all local collections.") let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } let b = self.scratchpad.evolve() .setGlobal(fetched) // We always adopt the upstream meta/global record. let previousEngines = Set(previous.engines.keys) let remoteEngines = Set(fetched.value.engines.keys) for engine in previousEngines.subtracting(remoteEngines) { log.info("Remote meta/global disabled previously enabled engine \(engine).") b.localCommands.insert(.disableEngine(engine: engine)) } for engine in remoteEngines.subtracting(previousEngines) { log.info("Remote meta/global enabled previously disabled engine \(engine).") b.localCommands.insert(.enableEngine(engine: engine)) } for engine in remoteEngines.intersection(previousEngines) { let remoteEngine = fetched.value.engines[engine]! let previousEngine = previous.engines[engine]! if previousEngine.syncID != remoteEngine.syncID { log.info("Remote sync ID for \(engine) has changed. Resetting local.") b.localCommands.insert(.resetEngine(engine: engine)) } } let s = b.build().checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } // No previous meta/global. Adopt the new meta/global. let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } } private func processFailure(_ failure: MaybeErrorType?) -> MaybeErrorType { if let failure = failure as? ServerInBackoffError { log.warning("Server in backoff. Bailing out. \(failure.description)") return failure } // TODO: backoff etc. for all of these. if let failure = failure as? ServerError<HTTPURLResponse> { // Be passive. log.error("Server error. Bailing out. \(failure.description)") return failure } if let failure = failure as? BadRequestError<HTTPURLResponse> { // Uh oh. log.error("Bad request. Bailing out. \(failure.description)") return failure } log.error("Unexpected failure. \(failure?.description ?? "nil")") return failure ?? UnknownError() } open class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo } // This method basically hops over HasMetaGlobal, because it's not a state // that we expect consumers to know about. override open func advance() -> Deferred<Maybe<SyncState>> { // Either m/g and c/k are in our local cache, and they're up-to-date with i/c, // or we need to fetch them. // Cached and not changed in i/c? Use that. // This check would be inaccurate if any other fields were stored in meta/; this // has been the case in the past, with the Sync 1.1 migration indicator. if let global = self.scratchpad.global { if let metaModified = self.info.modified("meta") { // We check the last time we fetched the record, and that can be // later than the collection timestamp. All we care about here is if the // server might have a newer record. if global.timestamp >= metaModified { log.debug("Cached meta/global fetched at \(global.timestamp), newer than server modified \(metaModified). Using cached meta/global.") // Strictly speaking we can avoid fetching if this condition is not true, // but if meta/ is modified for a different reason -- store timestamps // for the last collection fetch. This will do for now. return deferMaybe(HasMetaGlobal.fromState(self)) } log.info("Cached meta/global fetched at \(global.timestamp) older than server modified \(metaModified). Fetching fresh meta/global.") } else { // No known modified time for meta/. That means the server has no meta/global. // Drop our cached value and fall through; we'll try to fetch, fail, and // go through the usual failure flow. log.warning("Local meta/global fetched at \(global.timestamp) found, but no meta collection on server. Dropping cached meta/global.") // If we bail because we've been overly optimistic, then we nil out the current (broken) // meta/global. Next time around, we end up in the "No cached meta/global found" branch. self.scratchpad = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint() } } else { log.debug("No cached meta/global found. Fetching fresh meta/global.") } return deferMaybe(NeedsFreshMetaGlobal.fromState(self)) } } /* * We've reached NeedsFreshMetaGlobal somehow, but we haven't yet done anything about it * (e.g. fetch a new one with GET /storage/meta/global ). * * If we don't want to hit the network (e.g. from an extension), we should stop if we get to this state. */ open class NeedsFreshMetaGlobal: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshMetaGlobal } class func fromState(_ state: BaseSyncStateWithInfo) -> NeedsFreshMetaGlobal { return NeedsFreshMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Fetch. return self.client.getMetaGlobal().bind { result in if let resp = result.successValue { // We use the server's timestamp, rather than the record's modified field. // Either can be made to work, but the latter has suffered from bugs: see Bug 1210625. let fetched = Fetched(value: resp.value, timestamp: resp.metadata.timestampMilliseconds) return deferMaybe(ResolveMetaGlobalVersion.fromState(self, fetched: fetched)) } if result.failureValue as? NotFound<HTTPURLResponse> != nil { // OK, this is easy. // This state is responsible for creating the new m/g, uploading it, and // restarting with a clean scratchpad. return deferMaybe(MissingMetaGlobalError(previousState: self)) } // Otherwise, we have a failure state. Die on the sword! return deferMaybe(processFailure(result.failureValue)) } } } open class HasMetaGlobal: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal } class func fromState(_ state: BaseSyncStateWithInfo) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Check if we have enabled/disabled some engines. if let enginesEnablements = self.scratchpad.enginesEnablements, let oldMetaGlobal = self.scratchpad.global { let (engines, declined) = computeNewEngines(oldMetaGlobal.value.engineConfiguration(), enginesEnablements: enginesEnablements) let newMetaGlobal = MetaGlobal(syncID: oldMetaGlobal.value.syncID, storageVersion: oldMetaGlobal.value.storageVersion, engines: engines, declined: declined) return self.client.uploadMetaGlobal(newMetaGlobal, ifUnmodifiedSince: oldMetaGlobal.timestamp) >>> { self.scratchpad = self.scratchpad.evolve().clearEnginesEnablements().build().checkpoint() return deferMaybe(NeedsFreshMetaGlobal.fromState(self)) } } // Check if crypto/keys is fresh in the cache already. if let keys = self.scratchpad.keys, keys.value.valid { if let cryptoModified = self.info.modified("crypto") { // Both of these are server timestamps. If the record we stored was // fetched after the last time the record was modified, as represented // by the "crypto" entry in info/collections, and we're fetching from the // same server, then the record must be identical, and we can use it // directly. If are ever additional records in the crypto collection, // this will fetch keys too frequently. In that case, we should use // X-I-U-S and expect some 304 responses. if keys.timestamp >= cryptoModified { log.debug("Cached keys fetched at \(keys.timestamp), newer than server modified \(cryptoModified). Using cached keys.") return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, collectionKeys: keys.value)) } // The server timestamp is newer, so there might be new keys. // Re-fetch keys and check to see if the actual contents differ. // If the keys are the same, we can ignore this change. If they differ, // we need to re-sync any collection whose keys just changed. log.info("Cached keys fetched at \(keys.timestamp) older than server modified \(cryptoModified). Fetching fresh keys.") return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: keys.value)) } else { // No known modified time for crypto/. That likely means the server has no keys. // Drop our cached value and fall through; we'll try to fetch, fail, and // go through the usual failure flow. log.warning("Local keys fetched at \(keys.timestamp) found, but no crypto collection on server. Dropping cached keys.") self.scratchpad = self.scratchpad.evolve().setKeys(nil).build().checkpoint() } } else { log.debug("No cached keys found. Fetching fresh keys.") } return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: nil)) } } open class NeedsFreshCryptoKeys: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshCryptoKeys } let staleCollectionKeys: Keys? class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, staleCollectionKeys: Keys?) -> NeedsFreshCryptoKeys { return NeedsFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: staleCollectionKeys) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys?) { self.staleCollectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Fetch crypto/keys. return self.client.getCryptoKeys(self.scratchpad.syncKeyBundle, ifUnmodifiedSince: nil).bind { result in if let resp = result.successValue { let collectionKeys = Keys(payload: resp.value.payload) if !collectionKeys.valid { log.error("Unexpectedly invalid crypto/keys during a successful fetch.") return Deferred(value: Maybe(failure: InvalidKeysError(collectionKeys))) } let fetched = Fetched(value: collectionKeys, timestamp: resp.metadata.timestampMilliseconds) let s = self.scratchpad.evolve() .addLocalCommandsFromKeys(fetched) .setKeys(fetched) .build().checkpoint() return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: s, collectionKeys: collectionKeys)) } if result.failureValue as? NotFound<HTTPURLResponse> != nil { // No crypto/keys? We can handle this. Wipe and upload both meta/global and crypto/keys. return deferMaybe(MissingCryptoKeysError(previousState: self)) } // Otherwise, we have a failure state. return deferMaybe(processFailure(result.failureValue)) } } } open class HasFreshCryptoKeys: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.HasFreshCryptoKeys } let collectionKeys: Keys class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, collectionKeys: Keys) -> HasFreshCryptoKeys { return HasFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: collectionKeys) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(Ready(client: self.client, scratchpad: self.scratchpad, token: self.token, info: self.info, keys: self.collectionKeys)) } } public protocol EngineStateChanges { func collectionsThatNeedLocalReset() -> [String] func enginesEnabled() -> [String] func enginesDisabled() -> [String] func clearLocalCommands() } open class Ready: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.Ready } let collectionKeys: Keys public var hashedFxADeviceID: String { return (scratchpad.fxaDeviceId + token.hashedFxAUID).sha256.hexEncodedString } public var engineConfiguration: EngineConfiguration? { return scratchpad.engineConfiguration } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } } extension Ready: EngineStateChanges { public func collectionsThatNeedLocalReset() -> [String] { var needReset: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .resetAllEngines(except: except): needReset.formUnion(Set(LocalEngines).subtracting(except)) case let .resetEngine(engine): needReset.insert(engine) case .enableEngine, .disableEngine: break } } return needReset.sorted() } public func enginesEnabled() -> [String] { var engines: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .enableEngine(engine): engines.insert(engine) default: break } } return engines.sorted() } public func enginesDisabled() -> [String] { var engines: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .disableEngine(engine): engines.insert(engine) default: break } } return engines.sorted() } public func clearLocalCommands() { self.scratchpad = self.scratchpad.evolve().clearLocalCommands().build().checkpoint() } }
mpl-2.0
b87fa8be9b4a9375c502b340847ded4e
41.511673
168
0.679076
5.07278
false
false
false
false
alobanov/ALFormBuilder
Sources/FormBuilder/Vendors/extension/Dictionary+Ext.swift
1
2391
// // Dictionary+Ext.swift // Pulse // // Created by Aleksey Lobanov on 19.04.17. // Copyright © 2017 Aleksey Lobanov All rights reserved. // import Foundation import SwiftyJSON extension Dictionary { func setOrUpdate(value: Any, path: String) -> [String: Any] { let keys = path.components(separatedBy: ".") var json = JSON(self) var keyStack: [String] = [] var deep = 1 for key in keys { keyStack.append(key) if deep == keys.count { json[keyStack] = JSON(value) } else { if json[keyStack].dictionary == nil { json[keyStack] = JSON([keys[deep]: ""]) } } deep+=1 } return json.dictionaryObject! } func value(by path: String) -> Any? { let keys = path.components(separatedBy: ".") let count = keys.count var deep = 1 guard var currentNode = self as? [String: Any] else { return nil } for key in keys { if deep == count { if (currentNode[key] as? NSNull) != nil { return nil } if let array = currentNode[key] as? [[String: Any]] { return array } if let dict = currentNode[key] as? [String: Any] { return dict } if let result = currentNode[key] { let result = String(describing: result) return result } else { return nil } } else { if let nextNode = currentNode[key] as? [String: Any] { currentNode = nextNode } } deep+=1 } return nil } func find<T>(by path: [JSONSubscriptType]) throws -> T { let json = JSON(self) if let d = json[path].object as? T { return d } else { let d = [NSLocalizedDescriptionKey: "Resources.Data.\(path) is empty or is not an Object"] throw NSError(domain: "ru.alobanov", code: 1, userInfo: d) } } func nullKeyRemoval() -> [AnyHashable: Any] { var dict: [AnyHashable: Any] = self let keysToRemove = dict.keys.filter { dict[$0] is NSNull } let keysToCheck = dict.keys.filter({ dict[$0] is Dictionary }) for key in keysToRemove { dict.removeValue(forKey: key) } for key in keysToCheck { if let valueDict = dict[key] as? [AnyHashable: Any] { dict.updateValue(valueDict.nullKeyRemoval(), forKey: key) } } return dict } }
mit
b13e2b68b6146708bb1464d76c448fc8
21.761905
96
0.56318
3.905229
false
false
false
false
RevenueCat/purchases-ios
Sources/Purchasing/TrialOrIntroPriceEligibilityChecker.swift
1
10510
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // IntroTrialOrIntroductoryPriceEligibilityChecker.swift // // Created by César de la Vega on 8/31/21. import Foundation import StoreKit typealias ReceiveIntroEligibilityBlock = ([String: IntroEligibility]) -> Void /// A type that can determine `IntroEligibility` for products. protocol TrialOrIntroPriceEligibilityCheckerType { func checkEligibility(productIdentifiers: [String], completion: @escaping ReceiveIntroEligibilityBlock) } class TrialOrIntroPriceEligibilityChecker: TrialOrIntroPriceEligibilityCheckerType { private var appUserID: String { self.currentUserProvider.currentAppUserID } private let systemInfo: SystemInfo private let receiptFetcher: ReceiptFetcher private let introEligibilityCalculator: IntroEligibilityCalculator private let backend: Backend private let currentUserProvider: CurrentUserProvider private let operationDispatcher: OperationDispatcher private let productsManager: ProductsManagerType init( systemInfo: SystemInfo, receiptFetcher: ReceiptFetcher, introEligibilityCalculator: IntroEligibilityCalculator, backend: Backend, currentUserProvider: CurrentUserProvider, operationDispatcher: OperationDispatcher, productsManager: ProductsManagerType ) { self.systemInfo = systemInfo self.receiptFetcher = receiptFetcher self.introEligibilityCalculator = introEligibilityCalculator self.backend = backend self.currentUserProvider = currentUserProvider self.operationDispatcher = operationDispatcher self.productsManager = productsManager } func checkEligibility(productIdentifiers: [String], completion: @escaping ReceiveIntroEligibilityBlock) { guard !productIdentifiers.isEmpty else { Logger.warn(Strings.purchase.check_eligibility_no_identifiers) completion([:]) return } if #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *), self.systemInfo.storeKit2Setting.usesStoreKit2IfAvailable { Async.call(with: completion) { do { return try await self.sk2CheckEligibility(productIdentifiers) } catch { Logger.appleError(Strings.purchase.unable_to_get_intro_eligibility_for_user(error: error)) return productIdentifiers.reduce(into: [:]) { resultDict, productId in resultDict[productId] = IntroEligibility(eligibilityStatus: IntroEligibilityStatus.unknown) } } } } else { self.sk1CheckEligibility(productIdentifiers, completion: completion) } } func sk1CheckEligibility(_ productIdentifiers: [String], completion: @escaping ReceiveIntroEligibilityBlock) { // We don't want to refresh receipts because it will likely prompt the user for their credentials, // and intro eligibility is triggered programmatically. self.receiptFetcher.receiptData(refreshPolicy: .never) { data in if #available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.2, *), let data = data { self.sk1CheckEligibility(with: data, productIdentifiers: productIdentifiers, completion: completion) } else { self.getIntroEligibility(with: data ?? Data(), productIdentifiers: productIdentifiers, completion: completion) } } } @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) func sk2CheckEligibility(_ productIdentifiers: [String]) async throws -> [String: IntroEligibility] { let identifiers = Set(productIdentifiers) var introDictionary: [String: IntroEligibility] = identifiers.dictionaryWithValues { _ in .init(eligibilityStatus: .unknown) } let products = try await self.productsManager.sk2Products(withIdentifiers: identifiers) for sk2StoreProduct in products { let sk2Product = sk2StoreProduct.underlyingSK2Product let eligibilityStatus: IntroEligibilityStatus if let subscription = sk2Product.subscription, subscription.introductoryOffer != nil { let isEligible = await subscription.isEligibleForIntroOffer eligibilityStatus = isEligible ? .eligible : .ineligible } else { eligibilityStatus = .noIntroOfferExists } introDictionary[sk2StoreProduct.productIdentifier] = .init(eligibilityStatus: eligibilityStatus) } return introDictionary } } /// Default overload implementation that takes a single `StoreProductType`. extension TrialOrIntroPriceEligibilityCheckerType { func checkEligibility(product: StoreProductType, completion: @escaping (IntroEligibilityStatus) -> Void) { self.checkEligibility(productIdentifiers: [product.productIdentifier]) { eligibility in completion(eligibility[product.productIdentifier]?.status ?? .unknown) } } } // MARK: - Implementations private extension TrialOrIntroPriceEligibilityChecker { @available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 6.2, *) func sk1CheckEligibility(with receiptData: Data, productIdentifiers: [String], completion: @escaping ReceiveIntroEligibilityBlock) { introEligibilityCalculator .checkEligibility(with: receiptData, productIdentifiers: Set(productIdentifiers)) { receivedEligibility, error in if let error = error { Logger.error(Strings.receipt.parse_receipt_locally_error(error: error)) self.getIntroEligibility(with: receiptData, productIdentifiers: productIdentifiers, completion: completion) return } let convertedEligibility = receivedEligibility.mapValues(IntroEligibility.init) self.operationDispatcher.dispatchOnMainThread { completion(convertedEligibility) } } } func getIntroEligibility(with receiptData: Data, productIdentifiers: [String], completion: @escaping ReceiveIntroEligibilityBlock) { if #available(iOS 11.2, macOS 10.13.2, macCatalyst 13.0, tvOS 11.2, watchOS 6.2, *) { // Products that don't have an introductory discount don't need to be sent to the backend // Step 1: Filter out products without introductory discount and give .noIntroOfferExists status // Step 2: Send products without eligibility status to backend // Step 3: Merge results from step 1 and step 2 self.productsWithKnownIntroEligibilityStatus(productIdentifiers: productIdentifiers) { onDeviceResults in let nilProductIdentifiers = productIdentifiers.filter { productIdentifier in return onDeviceResults[productIdentifier] == nil } self.getIntroEligibilityFromBackend(with: receiptData, productIdentifiers: nilProductIdentifiers) { backendResults in let results = onDeviceResults + backendResults completion(results) } } } else { self.getIntroEligibilityFromBackend(with: receiptData, productIdentifiers: productIdentifiers, completion: completion) } } } extension TrialOrIntroPriceEligibilityChecker { @available(iOS 11.2, macOS 10.13.2, macCatalyst 13.0, tvOS 11.2, watchOS 6.2, *) func productsWithKnownIntroEligibilityStatus(productIdentifiers: [String], completion: @escaping ReceiveIntroEligibilityBlock) { self.productsManager.products(withIdentifiers: Set(productIdentifiers)) { products in let eligibility: [(String, IntroEligibility)] = Array(products.value ?? []) .filter { $0.introductoryDiscount == nil } .map { ($0.productIdentifier, IntroEligibility(eligibilityStatus: .noIntroOfferExists)) } let productIdsToIntroEligibleStatus = Dictionary(uniqueKeysWithValues: eligibility) completion(productIdsToIntroEligibleStatus) } } func getIntroEligibilityFromBackend(with receiptData: Data, productIdentifiers: [String], completion: @escaping ReceiveIntroEligibilityBlock) { if productIdentifiers.isEmpty { completion([:]) return } self.backend.offerings.getIntroEligibility(appUserID: self.appUserID, receiptData: receiptData, productIdentifiers: productIdentifiers) { backendResult, error in let result: [String: IntroEligibility] = { if let error = error { Logger.error(Strings.purchase.unable_to_get_intro_eligibility_for_user(error: error)) return Set(productIdentifiers) .dictionaryWithValues { _ in IntroEligibility(eligibilityStatus: .unknown) } } else { return backendResult } }() self.operationDispatcher.dispatchOnMainThread { completion(result) } } } } // @unchecked because: // - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe. extension TrialOrIntroPriceEligibilityChecker: @unchecked Sendable {}
mit
8be2c31acdbc5b7096c07812506e32f6
42.970711
117
0.623751
5.9139
false
false
false
false
0x4a616e/ArtlessEdit
ArtlessEdit/EditorSettingsObservable.swift
1
874
// // EditorSettingsObservable.swift // ArtlessEdit // // Created by Jan Gassen on 28/12/14. // Copyright (c) 2014 Jan Gassen. All rights reserved. // import Foundation class EditorSettingsObservable: ObservableSettings { var subscribers: [EditorSettingsObserver] = [] func notifySubscribers(settings: EditorSettings) { for subscriber in subscribers { subscriber.updateSettings(settings) } } func addSubscriber(subscriber: EditorSettingsObserver) { subscribers.append(subscriber) } func removeSubscriber(subscriberToRemove: EditorSettingsObserver) { var index = 0 for subscriber in subscribers { if subscriber === subscriberToRemove { subscribers.removeAtIndex(index) break } index += 1 } } }
bsd-3-clause
29e7be09ad501b9bebdedaa62aa59ed8
24
71
0.625858
5.171598
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 7 - Alien Adventure 4/Making Design Choices/Making Design Choices.playground/Pages/Reduce Working Memory Overhead.xcplaygroundpage/Contents.swift
1
1653
//: [Previous](@previous) /*: ## Reduce Working Memory Overhead */ //: ### Exercise: Code Prediction var isLoggedIn = false var isPreferredMember = false var isReturnCustomer = false var wasReferred = true var name = "Fred Skinner" // version 1 if isLoggedIn && (isPreferredMember || isReturnCustomer) { print("Very very happy to see you again \(name)") } else if isLoggedIn && !isPreferredMember { print("Hello there \(name)") } else if !isLoggedIn && wasReferred { print("Oh hi there \(name)") } else if !isLoggedIn { print("Hi") } // version 2 if isLoggedIn { let isSpecialCustomer = isPreferredMember || isReturnCustomer if isSpecialCustomer { print("Very very happy to see you again \(name)") } else { print("Hello there \(name)") } } else if wasReferred { print("Oh hi there \(name)") } else { print("Hi") } //: ### Exercise: Simplify var isAboutToRetire = false var isCriticallyAcclaimed = false var hasBestSellingRecord = true var wonAGrammyBefore = false var percentageOddsOfGrammyWin = 0 if isAboutToRetire && (isCriticallyAcclaimed || hasBestSellingRecord) && hasBestSellingRecord { percentageOddsOfGrammyWin = 80 } else if isAboutToRetire && !hasBestSellingRecord { percentageOddsOfGrammyWin = 70 } else if !isAboutToRetire && isCriticallyAcclaimed && hasBestSellingRecord { percentageOddsOfGrammyWin = 50 } else if !isAboutToRetire && !wonAGrammyBefore { percentageOddsOfGrammyWin = 40 } else if isAboutToRetire || wonAGrammyBefore || hasBestSellingRecord || isCriticallyAcclaimed { percentageOddsOfGrammyWin = 35 } else { percentageOddsOfGrammyWin = 1 }
mit
8de46a1857191409763d80a8ed3fe280
28.517857
96
0.714459
4.293506
false
false
false
false
jussiyu/bus-stop-ios-swift
BusStop/common/Common.swift
1
2518
// Copyright (c) 2015 Solipaste Oy // // 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 CoreLocation // MARK: - CLLocation extension CLLocation { /// compare horizontal location accuracy to a another location func moreAccurateThanLocation(other: CLLocation) -> Bool { return self.horizontalAccuracy < other.horizontalAccuracy } /// Is this location in same horizontal position than the anothe one func commonHorizontalLocationWith (other: CLLocation) -> Bool { return self.coordinate.longitude == other.coordinate.longitude && self.coordinate.latitude == other.coordinate.latitude } // Based on https://stackoverflow.com/questions/7278094/moving-a-cllocation-by-x-meters /// Return coordinate from 'distance' meters to 'direction' direction from this location func coordinateWithDirection(direction: CLLocationDirection, distance distanceMeters: CLLocationDistance) -> CLLocationCoordinate2D { let distRadians = distanceMeters / (6372797.6) let rDirection = direction * M_PI / 180.0 let lat1 = self.coordinate.latitude * M_PI / 180 let lon1 = self.coordinate.longitude * M_PI / 180 let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(rDirection)) let lon2 = lon1 + atan2(sin(rDirection) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2)) return CLLocationCoordinate2D(latitude: lat2 * 180 / M_PI, longitude: lon2 * 180 / M_PI) } }
mit
3ef1c32ee7c9650f6dd404fa3ebe54ca
45.62963
135
0.743447
4.333907
false
false
false
false
sishenyihuba/Weibo
Weibo/00-Main(主要)/OAuth/UserAccountViewModel.swift
1
967
// // UserAccountViewModel.swift // Weibo // // Created by daixianglong on 2017/1/16. // Copyright © 2017年 Dale. All rights reserved. // import UIKit class UserAccountViewModel { static var sharedInstance :UserAccountViewModel = UserAccountViewModel() //MARK: - 计算属性 var accountPath:String { let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! return (path as NSString).stringByAppendingPathComponent("account.plist") } var isLogin:Bool { if let account = account { if let expires_date = account.expires_date { return expires_date.compare(NSDate()) == .OrderedDescending } } return false } //MARK: - 存储属性 var account:UserAccount? init() { account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount } }
mit
fc351c0d2f51b3518986f590ba4bbf66
23.307692
104
0.627637
4.963351
false
false
false
false
modum-io/ios_client
PharmaSupplyChain/KeychainStore.swift
1
3857
// // KeychainStore.swift // PharmaSupplyChain // // Created by Yury Belevskiy on 23.03.17. // Copyright © 2017 Modum. All rights reserved. // import Foundation import Security /* Class that allows to securely store user-sensitive data in Keychain */ class KeychainStore : NSObject { // MARK: Constants fileprivate static let userAccount: String = "AuthUser" fileprivate static let passwordKey: String = "PasswordKey" fileprivate static let kSecClassGenericPasswordValue: NSString = NSString(format: kSecClassGenericPassword) fileprivate static let kSecClassValue: NSString = NSString(format: kSecClass) fileprivate static let kSecAttrServiceValue: NSString = NSString(format: kSecAttrService) fileprivate static let kSecAttrAccountValue: NSString = NSString(format: kSecAttrAccount) fileprivate static let kSecValueDataValue: NSString = NSString(format: kSecValueData) fileprivate static let kSecReturnDataValue: NSString = NSString(format: kSecReturnData) fileprivate static let kSecMatchLimitValue: NSString = NSString(format: kSecMatchLimit) fileprivate static let kSecMatchLimitOneValue: NSString = NSString(format: kSecMatchLimitOne) // MARK: Public functions /* Convinience function to store user password */ public static func storePassword(password: String) { save(service: passwordKey, data: password) } /* Convinience function to retrieve user password from Keychain */ public static func loadPassword() -> String? { return load(service: passwordKey) } /* Convinience function to delete existing password from Keychain */ public static func clear() { delete(service: passwordKey) } // MARK: Helper functions /* Generic method to store @data String under given @service key */ fileprivate static func save(service: String, data: String) { if let dataFromString = data.data(using: .utf8) { let keychainQuery = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue]) SecItemDelete(keychainQuery as CFDictionary) SecItemAdd(keychainQuery as CFDictionary, nil) } } /* Returns String if there exists an object in Keychain stored under @service key Otherwise, return nil */ fileprivate static func load(service: String) -> String? { let keychainQuery = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue]) var dataTypeRef: AnyObject? let status = SecItemCopyMatching(keychainQuery, &dataTypeRef) var contentsOfKeychain: String? = nil if status == errSecSuccess { if let retrievedData = dataTypeRef as? Data { contentsOfKeychain = String(data: retrievedData, encoding: .utf8) } } else { log("Nothing was retrieved from the keychain. Status code \(status)") } return contentsOfKeychain } /* Deletes an object in Keychain stored under @service key if it exists Otherwise, does nothing */ fileprivate static func delete(service: String) { let keychainQuery = NSMutableDictionary(objects: [kSecClassGenericPasswordValue], forKeys: [kSecClassValue]) let status = SecItemDelete(keychainQuery) if status == errSecSuccess { log("Successfully cleared Keychain!") } else { log("Failed to clear keychain! Status is \(status)") } } }
apache-2.0
20dccc5a6de1ed5625d690aa6db9c434
40.021277
264
0.695799
5.54023
false
false
false
false
gouyz/GYZBaking
baking/Pods/SKPhotoBrowser/SKPhotoBrowser/SKButtons.swift
4
2855
// // SKButtons.swift // SKPhotoBrowser // // Created by 鈴木 啓司 on 2016/08/09. // Copyright © 2016年 suzuki_keishi. All rights reserved. // import Foundation // helpers which often used private let bundle = Bundle(for: SKPhotoBrowser.self) class SKButton: UIButton { var showFrame: CGRect! var hideFrame: CGRect! var insets: UIEdgeInsets { if UI_USER_INTERFACE_IDIOM() == .phone { return UIEdgeInsets(top: 15.25, left: 15.25, bottom: 15.25, right: 15.25) } else { return UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) } } var size: CGSize = CGSize(width: 44, height: 44) var margin: CGFloat = 5 var buttonTopOffset: CGFloat { return 5 } func setup(_ imageName: String) { backgroundColor = .clear imageEdgeInsets = insets translatesAutoresizingMaskIntoConstraints = true autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] let image = UIImage(named: "SKPhotoBrowser.bundle/images/\(imageName)", in: bundle, compatibleWith: nil) ?? UIImage() setImage(image, for: UIControlState()) } func setFrameSize(_ size: CGSize) { let newRect = CGRect(x: margin, y: buttonTopOffset, width: size.width, height: size.height) frame = newRect showFrame = newRect hideFrame = CGRect(x: margin, y: -20, width: size.width, height: size.height) } } class SKCloseButton: SKButton { let imageName = "btn_common_close_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) setup(imageName) showFrame = CGRect(x: margin, y: buttonTopOffset, width: size.width, height: size.height) hideFrame = CGRect(x: margin, y: -20, width: size.width, height: size.height) } } class SKDeleteButton: SKButton { let imageName = "btn_common_delete_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) setup(imageName) showFrame = CGRect(x: SKMesurement.screenWidth - size.width, y: buttonTopOffset, width: size.width, height: size.height) hideFrame = CGRect(x: SKMesurement.screenWidth - size.width, y: -20, width: size.width, height: size.height) } override func setFrameSize(_ size: CGSize) { let newRect = CGRect(x: SKMesurement.screenWidth - size.width, y: buttonTopOffset, width: size.width, height: size.height) self.frame = newRect showFrame = newRect hideFrame = CGRect(x: SKMesurement.screenWidth - size.width, y: -20, width: size.width, height: size.height) } }
mit
267f9890751bff5e3d56f44dce36d71a
34.55
130
0.642405
4.086207
false
false
false
false
mbcltd/swift-normal-distribution
swift-normal-distribution/AppDelegate.swift
1
6199
// // AppDelegate.swift // swift-normal-distribution // // Created by David Morgan-Brown on 18/08/2015. // Copyright (c) 2015 David Morgan-Brown. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "MBC.swift_normal_distribution" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("swift_normal_distribution", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("swift_normal_distribution.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
3ea10fea615fe7b07b0eaec8ae365812
54.846847
290
0.717374
5.745134
false
false
false
false
lanjing99/RxSwiftDemo
11-time-based-operators/final/RxSwiftPlayground/RxSwift.playground/Pages/window.xcplaygroundpage/Contents.swift
1
4080
//: Please build the scheme 'RxSwiftPlayground' first import UIKit import RxSwift import RxCocoa let elementsPerSecond = 3 let windowTimeSpan: RxTimeInterval = 4 let windowMaxCount = 10 let sourceObservable = PublishSubject<String>() let sourceTimeline = TimelineView<String>.make() let stack = UIStackView.makeVertical([ UILabel.makeTitle("window"), UILabel.make("Emitted elements (\(elementsPerSecond) per sec.):"), sourceTimeline, UILabel.make("Windowed observables (at most \(windowMaxCount) every \(windowTimeSpan) sec):")]) let timer = DispatchSource.timer(interval: 1.0 / Double(elementsPerSecond), queue: .main) { sourceObservable.onNext("🐱") } _ = sourceObservable.subscribe(sourceTimeline) _ = sourceObservable .window(timeSpan: windowTimeSpan, count: windowMaxCount, scheduler: MainScheduler.instance) .flatMap { windowedObservable -> Observable<(TimelineView<Int>, String?)> in let timeline = TimelineView<Int>.make() stack.insert(timeline, at: 4) stack.keep(atMost: 8) return windowedObservable .map { value in (timeline, value) } .concat(Observable.just((timeline, nil))) } .subscribe(onNext: { tuple in let (timeline, value) = tuple if let value = value { timeline.add(.Next(value)) } else { timeline.add(.Completed(true)) } }) let hostView = setupHostView() hostView.addSubview(stack) hostView // Support code -- DO NOT REMOVE class TimelineView<E>: TimelineViewBase, ObserverType where E: CustomStringConvertible { static func make() -> TimelineView<E> { let view = TimelineView(frame: CGRect(x: 0, y: 0, width: 400, height: 100)) view.setup() return view } public func on(_ event: Event<E>) { switch event { case .next(let value): add(.Next(String(describing: value))) case .completed: add(.Completed()) case .error(_): add(.Error()) } } } /*: Copyright (c) 2014-2016 Razeware LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*: Copyright (c) 2014-2016 Razeware LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
mit
bf0916193f5ac96226f8d8817253334b
36.75
97
0.742948
4.441176
false
false
false
false
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/TakeLast.swift
6
1807
// // TakeLast.swift // Rx // // Created by Tomi Koskinen on 25/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class TakeLastSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = TakeLast<ElementType> typealias E = ElementType private let _parent: Parent private var _elements: Queue<ElementType> init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _elements = Queue<ElementType>(capacity: parent._count + 1) super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { switch event { case .next(let value): _elements.enqueue(value) if _elements.count > self._parent._count { let _ = _elements.dequeue() } case .error: forwardOn(event) dispose() case .completed: for e in _elements { forwardOn(.next(e)) } forwardOn(.completed) dispose() } } } class TakeLast<Element>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _count: Int init(source: Observable<Element>, count: Int) { if count < 0 { rxFatalError("count can't be negative") } _source = source _count = count } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TakeLastSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
mit
788cfdf3541d6d7cb94808729ce7cb0e
27.666667
145
0.584164
4.372881
false
false
false
false
xedin/swift
test/SILOptimizer/access_marker_mandatory.swift
5
3784
// RUN: %target-swift-frontend -module-name access_marker_mandatory -parse-as-library -Xllvm -sil-full-demangle -emit-sil -Onone -enforce-exclusivity=checked %s | %FileCheck %s public struct S { var i: Int var o: AnyObject } // CHECK-LABEL: sil [noinline] @$s23access_marker_mandatory5initSyAA1SVSi_yXltF : $@convention(thin) (Int, @guaranteed AnyObject) -> @owned S { // CHECK: bb0(%0 : $Int, %1 : $AnyObject): // CHECK: [[STK:%.*]] = alloc_stack $S, var, name "s" // CHECK: cond_br %{{.*}}, bb1, bb2 // CHECK: bb1: // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*S // CHECK: store %{{.*}} to [[WRITE]] : $*S // CHECK: end_access [[WRITE]] // CHECK: bb2: // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*S // CHECK: store %{{.*}} to [[WRITE]] : $*S // CHECK: end_access [[WRITE]] // CHECK: bb3: // CHECK: [[READ:%.*]] = begin_access [read] [static] [[STK]] : $*S // CHECK: [[RET:%.*]] = load [[READ]] : $*S // CHECK: end_access [[READ]] // CHECK: destroy_addr [[STK]] // CHECK: dealloc_stack [[STK]] // CHECK: return [[RET]] : $S // CHECK-LABEL: } // end sil function '$s23access_marker_mandatory5initSyAA1SVSi_yXltF' @inline(never) public func initS(_ x: Int, _ o: AnyObject) -> S { var s: S if x == 0 { s = S(i: 1, o: o) } else { s = S(i: x, o: o) } return s } @inline(never) func takeS(_ s: S) {} // CHECK-LABEL: sil @$s23access_marker_mandatory14modifyAndReadS1oyyXl_tF : $@convention(thin) (@guaranteed AnyObject) -> () { // CHECK: bb0(%0 : $AnyObject): // CHECK: [[STK:%.*]] = alloc_stack $S, var, name "s" // CHECK: [[FINIT:%.*]] = function_ref @$s23access_marker_mandatory5initSyAA1SVSi_yXltF : $@convention(thin) (Int, @guaranteed AnyObject) -> @owned S // CHECK: [[INITS:%.*]] = apply [[FINIT]](%{{.*}}, %0) : $@convention(thin) (Int, @guaranteed AnyObject) -> @owned S // CHECK: store [[INITS]] to [[STK]] : $*S // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*S // CHECK: [[ADDRI:%.*]] = struct_element_addr [[WRITE]] : $*S, #S.i // CHECK: store %{{.*}} to [[ADDRI]] : $*Int // CHECK: end_access [[WRITE]] // CHECK: [[READ:%.*]] = begin_access [read] [static] [[STK]] : $*S // CHECK: end_access [[READ]] // CHECK: [[FTAKE:%.*]] = function_ref @$s23access_marker_mandatory5takeSyyAA1SVF : $@convention(thin) (@guaranteed S) -> () // CHECK: apply [[FTAKE]](%{{.*}}) : $@convention(thin) (@guaranteed S) -> () // CHECK-LABEL: } // end sil function '$s23access_marker_mandatory14modifyAndReadS1oyyXl_tF' public func modifyAndReadS(o: AnyObject) { var s = initS(3, o) s.i = 42 takeS(s) } // Test capture promotion followed by stack promotion. // Access enforcement selection must run after capture promotion // so that we never stack promote something with dynamic access. // Otherwise, we may try to convert the access to [deinit] which // doesn't make sense dynamically. // // CHECK-LABEL: sil hidden @$s23access_marker_mandatory19captureStackPromoteSiycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> Int { // CHECK-LABEL: bb0: // CHECK: [[STK:%.*]] = alloc_stack $Int, var, name "x" // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*Int // CHECK: store %{{.*}} to [[WRITE]] : $*Int // CHECK: end_access [[WRITE]] : $*Int // CHECK: [[F:%.*]] = function_ref @$s23access_marker_mandatory19captureStackPromoteSiycyFSiycfU_Tf2i_n : $@convention(thin) (Int) -> Int // CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[F]](%{{.*}}) : $@convention(thin) (Int) -> Int // CHECK: dealloc_stack [[STK]] : $*Int // CHECK: return [[C]] : $@callee_guaranteed () -> Int // CHECK-LABEL: } // end sil function '$s23access_marker_mandatory19captureStackPromoteSiycyF' func captureStackPromote() -> () -> Int { var x = 1 x = 2 let f = { x } return f }
apache-2.0
7790dc6a60cd8f05a334148feac06735
43.517647
176
0.613636
3.179832
false
false
false
false
telip007/ChatFire
Pods/ALCameraViewController/ALCameraViewController/Views/CameraView.swift
2
8584
// // CameraView.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/17. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import AVFoundation public class CameraView: UIView { var session: AVCaptureSession! var input: AVCaptureDeviceInput! var device: AVCaptureDevice! var imageOutput: AVCaptureStillImageOutput! var preview: AVCaptureVideoPreviewLayer! let cameraQueue = dispatch_queue_create("com.zero.ALCameraViewController.Queue", DISPATCH_QUEUE_SERIAL) let focusView = CropOverlay(frame: CGRect(x: 0, y: 0, width: 80, height: 80)) public var currentPosition = AVCaptureDevicePosition.Back public func startSession() { dispatch_async(cameraQueue) { self.createSession() self.session?.startRunning() } } public func stopSession() { dispatch_async(cameraQueue) { self.session?.stopRunning() self.preview?.removeFromSuperlayer() self.session = nil self.input = nil self.imageOutput = nil self.preview = nil self.device = nil } } public override func layoutSubviews() { super.layoutSubviews() preview?.frame = bounds } public func configureFocus() { if let gestureRecognizers = gestureRecognizers { gestureRecognizers.forEach({ removeGestureRecognizer($0) }) } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(focus(_:))) addGestureRecognizer(tapGesture) userInteractionEnabled = true addSubview(focusView) focusView.hidden = true let lines = focusView.horizontalLines + focusView.verticalLines + focusView.outerLines lines.forEach { line in line.alpha = 0 } } internal func focus(gesture: UITapGestureRecognizer) { let point = gesture.locationInView(self) guard focusCamera(point) else { return } focusView.hidden = false focusView.center = point focusView.alpha = 0 focusView.transform = CGAffineTransformMakeScale(1.2, 1.2) bringSubviewToFront(focusView) UIView.animateKeyframesWithDuration(1.5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.15, animations: { () -> Void in self.focusView.alpha = 1 self.focusView.transform = CGAffineTransformIdentity }) UIView.addKeyframeWithRelativeStartTime(0.80, relativeDuration: 0.20, animations: { () -> Void in self.focusView.alpha = 0 self.focusView.transform = CGAffineTransformMakeScale(0.8, 0.8) }) }, completion: { finished in if finished { self.focusView.hidden = true } }) } private func createSession() { session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetPhoto dispatch_async(dispatch_get_main_queue()) { self.createPreview() } } private func createPreview() { device = cameraWithPosition(currentPosition) if let device = device where device.hasFlash { do { try device.lockForConfiguration() device.flashMode = .Auto device.unlockForConfiguration() } catch _ {} } let outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] do { input = try AVCaptureDeviceInput(device: device) } catch let error as NSError { input = nil print("Error: \(error.localizedDescription)") return } if session.canAddInput(input) { session.addInput(input) } imageOutput = AVCaptureStillImageOutput() imageOutput.outputSettings = outputSettings session.addOutput(imageOutput) preview = AVCaptureVideoPreviewLayer(session: session) preview.videoGravity = AVLayerVideoGravityResizeAspectFill preview.frame = bounds layer.addSublayer(preview) } private func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? { guard let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as? [AVCaptureDevice] else { return nil } return devices.filter { $0.position == position }.first } public func capturePhoto(completion: CameraShotCompletion) { userInteractionEnabled = false dispatch_async(cameraQueue) { var i = 0 if let device = self.device { while device.adjustingWhiteBalance || device.adjustingExposure || device.adjustingFocus { i += 1 // this is strange but we have to do something while we wait } } let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.currentDevice().orientation.rawValue)! takePhoto(self.imageOutput, videoOrientation: orientation, cropSize: self.frame.size) { image in dispatch_async(dispatch_get_main_queue()) { self.userInteractionEnabled = true completion(image) } } } } public func focusCamera(toPoint: CGPoint) -> Bool { guard let device = device where device.isFocusModeSupported(.ContinuousAutoFocus) else { return false } do { try device.lockForConfiguration() } catch { return false } // focus points are in the range of 0...1, not screen pixels let focusPoint = CGPoint(x: toPoint.x / frame.width, y: toPoint.y / frame.height) device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus device.exposurePointOfInterest = focusPoint device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure device.unlockForConfiguration() return true } public func cycleFlash() { guard let device = device where device.hasFlash else { return } do { try device.lockForConfiguration() if device.flashMode == .On { device.flashMode = .Off } else if device.flashMode == .Off { device.flashMode = .Auto } else { device.flashMode = .On } device.unlockForConfiguration() } catch _ { } } public func swapCameraInput() { guard let session = session, input = input else { return } session.beginConfiguration() session.removeInput(input) if input.device.position == AVCaptureDevicePosition.Back { currentPosition = AVCaptureDevicePosition.Front device = cameraWithPosition(currentPosition) } else { currentPosition = AVCaptureDevicePosition.Back device = cameraWithPosition(currentPosition) } guard let i = try? AVCaptureDeviceInput(device: device) else { return } self.input = i session.addInput(i) session.commitConfiguration() } public func rotatePreview() { guard preview != nil else { return } switch UIApplication.sharedApplication().statusBarOrientation { case .Portrait: preview?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait break case .PortraitUpsideDown: preview?.connection.videoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown break case .LandscapeRight: preview?.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight break case .LandscapeLeft: preview?.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeLeft break default: break } } }
apache-2.0
95f6c6ec8db99813c81f4e2ee6664699
31.270677
115
0.579916
6.02809
false
false
false
false
lanserxt/teamwork-ios-sdk
TeamWorkClient/TeamWorkClient/Requests/TWApiClient+Search.swift
1
3844
// // TWApiClient+Invoices.swift // TeamWorkClient // // Created by Anton Gubarenko on 02.02.17. // Copyright © 2017 Anton Gubarenko. All rights reserved. // import Foundation import Alamofire extension TWApiClient{ func search(searchFor: String, searchTerm: String, _ responseBlock: @escaping (Bool, Int, SearchResult?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.search.path, searchFor, searchTerm), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<SearchResult>.init(rootObjectName: TWApiClientConstants.APIPath.search.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func searchExtended(searchFor: String, searchTerm: String, projectId: String = "0", sortOrder: String, includArchivedProjects: Bool, includeCompletedItems: Bool, pageSize: Int = 20, _ responseBlock: @escaping (Bool, Int, SearchResult?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.searchExtended.path, searchFor, searchTerm, projectId, sortOrder, wrapBoolValue(includArchivedProjects), wrapBoolValue(includeCompletedItems), pageSize), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<SearchResult>.init(rootObjectName: TWApiClientConstants.APIPath.searchExtended.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } }
mit
9bec3209cdb889fa508994076aff9adb
51.643836
325
0.56102
5.876147
false
false
false
false
orcudy/archive
ios/apps/UCLALibrary/Code/UCLALibrary/DataManager.swift
1
6162
// // DataManager.swift // UCLALibrary // // Created by Chris Orcutt on 8/2/15. // Copyright (c) 2015 Chris Orcutt. All rights reserved. // import Foundation import AFNetworking import SwiftyJSON //wrapper which provides unique way (ID) to lookup libraries in other VCs class OperatingHoursData { var ID: String var operatingHours: [OperatingHours] init(ID: String, operatingHours: [OperatingHours]) { self.ID = ID self.operatingHours = operatingHours } } class DataManager { private let unitURL = "https://webservices.library.ucla.edu/libservices/units" private let baseDataURL = "https://webservices.library.ucla.edu/libservices/hours/unit/" private let manager = AFHTTPRequestOperationManager() //cache private var libraries: [Library]? // MARK: DataManagerAPI func dataForLibraries() { if let _ = self.libraries { postNotification("LibraryListDataReady", data: self.libraries) self.fetchAllLibraryData() } else { fetchLibraryUnitDataFromNetwork() } } func dataForLibraryWithID(ID: String) { let result = self.libraries?.filter { (element: Library) -> Bool in if element.ID == ID { if let operatingHours = element.operatingHours { let operatingHoursData = OperatingHoursData(ID: ID, operatingHours: operatingHours) self.postNotification("LibraryDataReady", data: operatingHoursData) } else { self.fetchLibraryDataFromNetwork(ID) } } return false } self.libraries = result } // MARK: Notifications private func postNotification(name: String, data: AnyObject?) { let notificationCenter = NSNotificationCenter.defaultCenter() let notification: NSNotification if let data: AnyObject = data { let userInfo = ["data" : data] notification = NSNotification(name: name, object: nil, userInfo: userInfo) } else { notification = NSNotification(name: name, object: nil, userInfo: nil) } notificationCenter.postNotification(notification) } //MARK: AFNetworking private func fetchLibraryUnitDataFromNetwork() { manager.GET(unitURL, parameters: nil, success: {(operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in let json = JSON(response) var libraryData = json["unit"] self.libraries = [Library]() for index in 0..<libraryData.count { let name = libraryData[index]["name"].string let ID = libraryData[index]["id"].string if let name = name, ID = ID { let libraries = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Libraries", ofType: "plist")!) if libraries?.objectForKey(ID) as? NSDictionary != nil { let library = Library(name: name, ID: ID) self.libraries!.append(library) } } } self.postNotification("LibraryListDataReady", data: self.libraries) self.fetchAllLibraryData() print("unit success") }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in //TODO: implement failure condition -- note response internally failed August 5, 2015 // idea: have unit data locally (check if it ever changes) print("failure: error \(error)") // let libraryData = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("LibraryUnits", ofType: "plist")!) // // // for index in 0..<libraryData!.count { // let name = libraryData[index]["name"].string // let ID = libraryData[index]["id"].string // if let name = name, ID = ID { // var library = Library(name: name, ID: ID) // self.libraries!.append(library) // } // } }) } private func fetchAllLibraryData() { if let libraries = libraries { for library in libraries { fetchLibraryDataFromNetwork(library.ID) } } } private func fetchLibraryDataFromNetwork(ID: String) { manager.GET(baseDataURL + ID, parameters: nil, success: {(operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in let json = JSON(response) let schedule = json["unitSchedule"] let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ" let timeFormatter = NSDateFormatter() timeFormatter.dateFormat = "HH:mm" let daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] let responseOpenKeys = ["monThursOpens", "monThursOpens", "monThursOpens", "monThursOpens", "friOpens", "satOpens", "sunOpens"] let responseCloseKeys = ["monThursCloses", "monThursCloses", "monThursCloses", "monThursCloses", "friCloses", "satCloses", "sunCloses"] var operatingHours = [OperatingHours]() for index in 0..<daysOfWeek.count { let openingDate = dateFormatter.dateFromString(schedule[responseOpenKeys[index]].string ?? "") let closingDate = dateFormatter.dateFromString(schedule[responseCloseKeys[index]].string ?? "") let hours = OperatingHours(day: daysOfWeek[index], opens: openingDate, closes: closingDate) operatingHours.append(hours) } self.libraries = self.libraries?.map { (element: Library) -> Library in if element.ID == ID { element.operatingHours = operatingHours } return element } let operatingHoursData = OperatingHoursData(ID: ID, operatingHours: operatingHours) self.postNotification("LibraryDataReady", data: operatingHoursData) print("success for \(ID)") }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in //TODO: implement failure condition print("failure: error \(error)") }) } }
gpl-3.0
87a45232b68be55c4b0c66eece5a396c
36.351515
145
0.622363
4.810304
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/TalkPageFetcher.swift
1
9815
import Foundation import WMF struct TalkPageAPIResponse: Codable { let threads: TalkPageThreadItems? enum CodingKeys: String, CodingKey { case threads = "discussiontoolspageinfo" } } struct TalkPageThreadItems: Codable { let threadItems: [TalkPageItem] enum CodingKeys: String, CodingKey { case threadItems = "threaditemshtml" } } struct TalkPageItem: Codable { let type: TalkPageItemType let level: Int? let id: String let html: String? let name: String? let headingLevel: Int? let replies: [TalkPageItem] let otherContent: String? let author: String? let timestamp: Date? enum CodingKeys: String, CodingKey { case type, level, id, html, name ,headingLevel, replies, author, timestamp case otherContent = "othercontent" } enum TalkPageItemType: String, Codable { case comment = "comment" case heading = "heading" } init(type: TalkPageItemType, level: Int?, id: String, html: String?, name: String?, headingLevel: Int?, replies: [TalkPageItem], otherContent: String?, author: String?, timestamp: Date?) { self.type = type self.level = level self.id = id self.html = html self.name = name self.headingLevel = headingLevel self.replies = replies self.otherContent = otherContent self.author = author self.timestamp = timestamp } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) type = try values.decode(TalkPageItemType.self, forKey: .type) level = try? values.decode(Int.self, forKey: .level) id = try values.decode(String.self, forKey: .id) html = try? values.decode(String.self, forKey: .html) name = try? values.decode(String.self, forKey: .name) headingLevel = try? values.decode(Int.self, forKey: .headingLevel) replies = (try? values.decode([TalkPageItem].self, forKey: .replies)) ?? [] otherContent = try? values.decode(String.self, forKey: .otherContent) author = try? values.decode(String.self, forKey: .author) if let timestampString = try? values.decode(String.self, forKey: .timestamp) { let timestampDate = (timestampString as NSString).wmf_iso8601Date() timestamp = timestampDate } else { timestamp = nil } } func updatingReplies(replies: [TalkPageItem]) -> TalkPageItem { return TalkPageItem(type: type, level: level, id: id, html: html, name: name, headingLevel: headingLevel, replies: replies, otherContent: otherContent, author: author, timestamp: timestamp) } } class TalkPageFetcher: Fetcher { func fetchTalkPageContent(talkPageTitle: String, siteURL: URL, completion: @escaping (Result<[TalkPageItem], Error>) -> Void) { guard let title = talkPageTitle.denormalizedPageTitle else { completion(.failure(RequestError.invalidParameters)) return } let params = ["action" : "discussiontoolspageinfo", "page" : title, "format": "json", "prop" : "threaditemshtml", "formatversion" : "2" ] performDecodableMediaWikiAPIGET(for: siteURL, with: params) { (result: Result<TalkPageAPIResponse, Error>) in switch result { case let .success(talk): completion(.success(talk.threads?.threadItems ?? [])) case let .failure(error): completion(.failure(error)) } } } /// This function takes a **topic** argument of type String. /// This argument expects a `name` value from `TalkPageItem` heading (or topic) items. func subscribeToTopic(talkPageTitle: String, siteURL: URL, topic: String, shouldSubscribe: Bool, completion: @escaping (Result<Bool, Error>) -> Void) { guard let title = talkPageTitle.denormalizedPageTitle else { completion(.failure(RequestError.invalidParameters)) return } var params = ["action": "discussiontoolssubscribe", "page": title, "format": "json", "commentname": topic, "formatversion": "2" ] if shouldSubscribe { params["subscribe"] = "1" } performTokenizedMediaWikiAPIPOST(to: siteURL, with: params, reattemptLoginOn401Response: true) { result, httpResponse, error in if let error = error { completion(.failure(error)) return } if let resultError = result?["error"] as? [String: Any], let info = resultError["info"] as? String { completion(.failure(RequestError.api(info))) return } if let resultSuccess = result?["discussiontoolssubscribe"] as? [String: Any], let didSubscribe = resultSuccess["subscribe"] as? Bool { completion(.success(didSubscribe)) return } completion(.failure(RequestError.unexpectedResponse)) } } /// Returns a list of active talk page topics subscription /// - Parameters: /// - siteURL: URL for the talk page, takes a URL object /// - topics: Expects a array of Strings containing the `name` value from `TalkPageItem` /// - completion: Returns either and array with the the `name` property of subscribed topics or an Error func getSubscribedTopics(siteURL: URL, topics: [String], completion: @escaping (Result<[String], Error>) -> Void) { let joinedString = topics.joined(separator: "|") let params = ["action": "discussiontoolsgetsubscriptions", "format": "json", "commentname": joinedString, "formatversion": "2" ] performMediaWikiAPIGET(for: siteURL, with: params, cancellationKey: nil) { result, httpResponse, error in if let error = error { completion(.failure(error)) return } if let resultError = result?["error"] as? [String: Any], let info = resultError["info"] as? String { completion(.failure(RequestError.api(info))) return } if let resultSuccess = result?["subscriptions"] as? [String: Any] { var subscribedTopics = [String]() for (topicId, subStatus) in resultSuccess { if subStatus as? Int == 1 { subscribedTopics.append(topicId) } } completion(.success(subscribedTopics)) return } completion(.failure(RequestError.unexpectedResponse)) } } func postReply(talkPageTitle: String, siteURL: URL, commentId: String, comment: String, completion: @escaping(Result<Void, Error>) -> Void) { guard let title = talkPageTitle.denormalizedPageTitle else { completion(.failure(RequestError.invalidParameters)) return } let params = ["action": "discussiontoolsedit", "paction": "addcomment", "page": title, "format": "json", "formatversion" : "2", "commentid": commentId, "wikitext": comment ] performTokenizedMediaWikiAPIPOST(to: siteURL, with: params, reattemptLoginOn401Response: false) { result, httpResponse, error in self.evaluateResponse(error, result, completion: completion) } } func postTopic(talkPageTitle: String, siteURL: URL, topicTitle: String, topicBody: String, completion: @escaping(Result<Void, Error>) -> Void) { guard let title = talkPageTitle.denormalizedPageTitle else { completion(.failure(RequestError.invalidParameters)) return } let params = ["action": "discussiontoolsedit", "paction": "addtopic", "page": title, "format": "json", "formatversion" : "2", "sectiontitle": topicTitle, "wikitext": topicBody ] performTokenizedMediaWikiAPIPOST(to: siteURL, with: params, reattemptLoginOn401Response: false) { result, httpResponse, error in self.evaluateResponse(error, result, completion: completion) } } fileprivate func evaluateResponse(_ error: Error?, _ result: [String : Any]?, completion: @escaping(Result<Void, Error>) -> Void) { if let error = error { completion(.failure(error)) return } if let resultError = result?["error"] as? [String: Any], let info = resultError["info"] as? String { completion(.failure(RequestError.api(info))) return } guard let discussionToolsEdit = result?["discussiontoolsedit"] as? [String: Any], let discussionToolsEditResult = discussionToolsEdit["result"] as? String, discussionToolsEditResult == "success" else { completion(.failure(RequestError.unexpectedResponse)) return } completion(.success(())) } }
mit
3fd5f2ab868b1502b4a82b5b4dc9107c
38.103586
197
0.567193
5.082859
false
false
false
false
BurntCaramel/Lantern
Lantern/MultipleStringPreviewViewController.swift
1
4997
// // MultipleStringPreviewViewController.swift // Hoverlytics // // Created by Patrick Smith on 3/05/2015. // Copyright (c) 2015 Burnt Caramel. All rights reserved. // import Cocoa import LanternModel class MultipleStringPreviewViewController: NSViewController { @IBOutlet var tableView: NSTableView! var measuringTableCellView: MultipleStringPreviewTableCellView! var itemMenu: NSMenu! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self measuringTableCellView = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "stringValue"), owner: self) as! MultipleStringPreviewTableCellView view.appearance = NSAppearance(named: NSAppearance.Name.aqua) } func createRowMenu() { // Row Menu itemMenu = NSMenu(title: "Values Menu") let copyValueItem = itemMenu.addItem(withTitle: "Copy Value", action: #selector(MultipleStringPreviewViewController.copyValueForSelectedRow(_:)), keyEquivalent: "") copyValueItem.target = self } var validatedStringValues: [ValidatedStringValue] = [] { didSet { reloadValues() } } func reloadValues() { // Stupid NSViewController _ = self.view tableView.reloadData() } override func keyDown(with theEvent: NSEvent) { if theEvent.burnt_isSpaceKey { // Just like QuickLook, use space to dismiss. dismiss(nil) } } } extension MultipleStringPreviewViewController { class func instantiateFromStoryboard() -> MultipleStringPreviewViewController { return NSStoryboard.lantern_contentPreviewStoryboard.instantiateController(withIdentifier: "String Value View Controller") as! MultipleStringPreviewViewController } } extension MultipleStringPreviewViewController { @IBAction func copyValueForSelectedRow(_ menuItem: NSMenuItem) { let row = tableView.clickedRow if row != -1 { performCopyValueForItemAtRow(row) } } func performCopyValueForItemAtRow(_ row: Int) { switch validatedStringValues[row] { case .validString(let stringValue): let pasteboard = NSPasteboard.general pasteboard.clearContents() pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil) pasteboard.setString(stringValue, forType: NSPasteboard.PasteboardType.string) default: break } } } extension MultipleStringPreviewViewController: NSTableViewDataSource, NSTableViewDelegate { func numberOfRows(in tableView: NSTableView) -> Int { return validatedStringValues.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { switch validatedStringValues[row] { case .validString(let stringValue): return stringValue default: break } return nil } func setUpTableCellView(_ view: MultipleStringPreviewTableCellView, tableColumn: NSTableColumn?, row: Int, visualsAndInteraction: Bool = true) { let validatedStringValue = validatedStringValues[row] let textField = view.textField! textField.stringValue = validatedStringValue.stringValueForPresentation let indexField = view.indexField! indexField.stringValue = String(row + 1) // 1-based index if visualsAndInteraction { let textColor = NSColor.textColor indexField.textColor = textColor.withAlphaComponent(0.3) textField.textColor = textColor.withAlphaComponent(validatedStringValue.alphaValueForPresentation) view.menu = itemMenu } } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { let cellView = measuringTableCellView setUpTableCellView(cellView!, tableColumn: nil, row: row, visualsAndInteraction: false) let tableColumn = tableView.tableColumns[0] let cellWidth = tableColumn.width cellView?.setFrameSize(NSSize(width: cellWidth, height: 100.0)) cellView?.layoutSubtreeIfNeeded() let textField = cellView?.textField! textField?.preferredMaxLayoutWidth = (textField?.bounds.width)! let extraPadding: CGFloat = 5.0 + 5.0 let height = (textField?.intrinsicContentSize.height)! + extraPadding return height } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if let view = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "stringValue"), owner: self) as? MultipleStringPreviewTableCellView { setUpTableCellView(view, tableColumn: tableColumn, row: row) return view } return nil } func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { return false } } extension MultipleStringPreviewViewController: NSPopoverDelegate { func popoverWillShow(_ notification: Notification) { //let popover = notification.object as! NSPopover //popover.appearance = NSAppearance(named: NSAppearanceNameVibrantDark) //popover.appearance = NSAppearance(named: NSAppearanceNameLightContent) //popover.appearance = .HUD } } class MultipleStringPreviewTableCellView: NSTableCellView { @IBOutlet var indexField: NSTextField! }
apache-2.0
8b1719de6e231b0d8f5eee6b3d48d53f
28.394118
169
0.763858
4.477599
false
false
false
false
hunj/hCrypto
hCrypto/DecryptViewController.swift
1
844
// // DecryptViewController.swift // hCrypto // // Created by Hun Jae Lee on 6/7/16. // Copyright © 2016 Hun Jae Lee. All rights reserved. // import Cocoa class DecryptViewController: NSViewController { @IBOutlet var inputTextField: NSTextField! @IBOutlet var outputTextField: NSTextField! @IBOutlet var keyField: NSTextField! @IBOutlet var submitButton: NSButton! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } @IBAction func decryptButtonPressed(sender: NSButton) { if inputTextField.stringValue == "" || keyField.stringValue == "" { showAlert("Text and Key is required!") } else { let cryptor = hCryptor() let decryptedMessage = cryptor.decrypt(inputTextField.stringValue, key: keyField.stringValue) outputTextField.stringValue = decryptedMessage } } }
mit
a41f33a29a26a140a959ed712df29f93
25.34375
96
0.714116
4.072464
false
false
false
false
MukeshKumarS/Swift
test/SILGen/objc_protocols.swift
1
10983
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: objc_interop import gizmo import objc_protocols_Bas @objc protocol NSRuncing { func runce() -> NSObject func copyRuncing() -> NSObject func foo() static func mince() -> NSObject } @objc protocol NSFunging { func funge() func foo() } protocol Ansible { func anse() } // CHECK-LABEL: sil hidden @_TF14objc_protocols12objc_generic func objc_generic<T : NSRuncing>(x: T) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) // -- Result of runce is autoreleased according to default objc conv // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[THIS1:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject // -- Result of copyRuncing is received retained according to -copy family // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[THIS2:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject // -- Arguments are not consumed by objc calls // CHECK: release [[THIS2]] } func objc_generic_partial_apply<T : NSRuncing>(x: T) { // CHECK: [[FN:%.*]] = function_ref @_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject // CHECK-NEXT: strong_retain %0 // CHECK-NEXT: [[METHOD:%.*]] = apply [[FN]]<T>(%0) // CHECK-NEXT: strong_release [[METHOD]] _ = x.runce // CHECK: [[FN:%.*]] = function_ref @_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]]<T>() // CHECK-NEXT: strong_release [[METHOD]] _ = T.runce // CHECK: [[FN:%.*]] = function_ref @_TTOZFP14objc_protocols9NSRuncing5minceFT_CSo8NSObject // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]]) // CHECK-NEXT: strong_release [[METHOD:%.*]] _ = T.mince } // CHECK-LABEL: sil shared @_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject // CHECK: [[FN:%.*]] = function_ref @_TTOFP14objc_protocols9NSRuncing5runcefT_CSo8NSObject // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]]<Self>(%0) // CHECK-NEXT: return [[METHOD]] // CHECK-LABEL: sil shared @_TTOFP14objc_protocols9NSRuncing5runcefT_CSo8NSObject // CHECK: strong_retain %0 // CHECK-NEXT: [[FN:%.*]] = witness_method $Self, #NSRuncing.runce!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0) // CHECK-NEXT: strong_release %0 // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared @_TTOZFP14objc_protocols9NSRuncing5minceFT_CSo8NSObject // CHECK: [[FN:%.*]] = function_ref @_TTOZFP14objc_protocols9NSRuncing5mincefT_CSo8NSObject // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]]<Self>(%0) // CHECK-NEXT: return [[METHOD]] // CHECK-LABEL: sil shared @_TTOZFP14objc_protocols9NSRuncing5mincefT_CSo8NSObject // CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.mince!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0) // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil hidden @_TF14objc_protocols13objc_protocol func objc_protocol(x: NSRuncing) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) // -- Result of runce is autoreleased according to default objc conv // CHECK: [[THIS1:%.*]] = open_existential_ref [[THIS1_ORIG:%.*]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]]) // -- Result of copyRuncing is received retained according to -copy family // CHECK: [[THIS2:%.*]] = open_existential_ref [[THIS2_ORIG:%.*]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]]) // -- Arguments are not consumed by objc calls // CHECK: release [[THIS2_ORIG]] } func objc_protocol_partial_apply(x: NSRuncing) { // CHECK: [[THIS1:%.*]] = open_existential_ref %0 : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[FN:%.*]] = function_ref @_TTOFP14objc_protocols9NSRuncing5runceFT_CSo8NSObject // CHECK: strong_retain [[THIS1]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[THIS1]]) // CHECK: strong_release [[RESULT]] // CHECK: strong_release %0 _ = x.runce // FIXME: rdar://21289579 // _ = NSRuncing.runce } // CHECK-LABEL: sil hidden @_TF14objc_protocols25objc_protocol_composition func objc_protocol_composition(x: protocol<NSRuncing, NSFunging>) { // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $protocol<NSFunging, NSRuncing> to $[[OPENED:@opened(.*) protocol<NSFunging, NSRuncing>]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.runce() // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $protocol<NSFunging, NSRuncing> to $[[OPENED:@opened(.*) protocol<NSFunging, NSRuncing>]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSFunging.funge!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.funge() } // -- ObjC thunks get emitted for ObjC protocol conformances class Foo : NSRuncing, NSFunging, Ansible { // -- NSRuncing @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc static func mince() -> NSObject { return NSObject() } // -- NSFunging @objc func funge() {} // -- Both NSRuncing and NSFunging @objc func foo() {} // -- Ansible func anse() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo5runce // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo5funge // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Foo3foo // CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}} class Bar { } extension Bar : NSRuncing { @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar5runce // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Bar3foo // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // runce() implementation from the original definition of Bas @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas3Bas11copyRuncing // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas3Bas3foo // -- Inherited objc protocols protocol Fungible : NSFunging { } class Zim : Fungible { @objc func funge() {} @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Zim5funge // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols3Zim3foo // class Zang from objc_protocols_Bas module extension Zang : Fungible { // funge() implementation from the original definition of Zim @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_TToFE14objc_protocolsC18objc_protocols_Bas4Zang3foo // -- objc protocols with property requirements in extensions // <rdar://problem/16284574> @objc protocol NSCounting { var count: Int {get} } class StoredPropertyCount { @objc let count = 0 } extension StoredPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC14objc_protocols19StoredPropertyCountg5countSi class ComputedPropertyCount { @objc var count: Int { return 0 } } extension ComputedPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols21ComputedPropertyCountg5countSi // -- adding @objc protocol conformances to native ObjC classes should not // emit thunks since the methods are already available to ObjC. // Gizmo declared in Inputs/usr/include/Gizmo.h extension Gizmo : NSFunging { } // CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}} @objc class InformallyFunging { @objc func funge() {} @objc func foo() {} } extension InformallyFunging: NSFunging { } @objc protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @_TF14objc_protocols28testInitializableExistential func testInitializableExistential(im: Initializable.Type, i: Int) -> Initializable { // CHECK: bb0([[META:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[I2_BOX:%[0-9]+]] = alloc_box $Initializable // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type // CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method [volatile] $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign, [[ARCHETYPE_META]]{{.*}} : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_ALLOC]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable // CHECK: store [[I2_EXIST_CONTAINER]] to [[I2_BOX]]#1 : $*Initializable // CHECK: [[I2:%[0-9]+]] = load [[I2_BOX]]#1 : $*Initializable // CHECK: strong_retain [[I2]] : $Initializable // CHECK: strong_release [[I2_BOX]]#0 : $@box Initializable // CHECK: return [[I2]] : $Initializable var i2 = im.init(int: i) return i2 } class InitializableConformer: Initializable { @objc required init(int: Int) {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols22InitializableConformerc final class InitializableConformerByExtension { init() {} } extension InitializableConformerByExtension: Initializable { @objc convenience init(int: Int) { self.init() } } // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_protocols33InitializableConformerByExtensionc
apache-2.0
0b8a1df92b32dd8c2afcabe7bfa8bbac
40.082397
263
0.668247
3.582299
false
false
false
false
carmelosui/DemoShareCoreDataBetweenWatchAndiPhone
ShareLib/CoreDataManager.swift
1
2508
// // CoreDataManager.swift // PomodoroWatch // // Created by Carmelo Sui on 4/10/15. // Copyright (c) 2015 Carmelo Sui. All rights reserved. // import CoreData public class CoreDataManager: NSObject { public static let sharedInstance = CoreDataManager() // let shareGroupName = "group.com.carmelosui.demowatchcoredata" let shareGroupName = //You need to fill your container group id here, and you must turn the "App Group" capability in main app target and watch extension target's "Capability" tab func sharedContainerDirectoryURL() -> NSURL { return NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(shareGroupName)! } func libBundle() -> NSBundle { return NSBundle(forClass: self.dynamicType) } //MARM: path configurations private lazy var sqliteFileURL: NSURL = { let containerURL = self.sharedContainerDirectoryURL() let sqliteURL = containerURL.URLByAppendingPathComponent("coredatatest.sqlite") return sqliteURL }() //MARK: Core Data Stack lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = self.libBundle().URLForResource("Model", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let containerURL = self.sharedContainerDirectoryURL() var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: self.sqliteFileURL, options: nil, error: &error) == nil { abort() } return coordinator }() public lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support public func saveContext () { let moc = self.managedObjectContext var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { abort() } } }
mit
f583efd2b928edcdae17f378808662ba
37
183
0.687799
5.560976
false
false
false
false
twlkyao/Swift
Struct/Struct/main.swift
1
2591
// // main.swift // Struct // // Created by Jack on 6/26/14. // Copyright (c) 2014 Jack. All rights reserved. // /* * an example to show the difference between value type and reference type. */ import Foundation /***************************************** value type. *****************************************/ struct Point1 { var x = 0, y = 0 mutating func moveToX(x: Int, andY y:Int) { // needs to be a mutating method in order to work self.x = x self.y = y } } var p1 = Point1(x: 1, y: 2) // in order to change the properties, you have to use var, because it is a value type. p1.x = 3 // works from outside the struct! p1.moveToX(5, andY: 5) println("p1.x = \(p1.x), p1.y = \(p1.y)") let p7 = Point1(x: 1, y: 2) //p7.moveToX(4, andY: 5) // error, since p7 is a constant, its property can't change. struct Point2 { let x = 0, y = 0 } var p2 = Point2(x: 1, y: 2) println("p2.x=\(p2.x), p2.y=\(p2.y)") //p2.x = 3 // can't change p2.x, since p2.x is a constant. /***************************************** reference type. *****************************************/ class Point3 { var x = 0 var y = 0 let plet: Point4 var pvar: Point4 init(x: Int, y: Int) { self.x = x self.y = y self.plet = Point4() // plet.x = 0, plet.y = 0 self.pvar = Point4() // pvar.x = 0, pvar.y = 0 } func moveToX(x: Int, andY y: Int) { // no need to use "mutating" keyword. self.x = x; self.y = y; } } class Point4 { var x = 0 var y = 0 } let p3 = Point3(x:1, y:2) // you can use let, even though you want to change the property, because it is a reference. p3.x = 2 p3.moveToX(5, andY: 5) // no need to use the "mutating" keyword. println("p3.x = \(p3.x), p3.y = \(p3.y)") // x = 5, y = 5 var p4 = p3 // p3 and p4 are the same, since they are reference type. p4.x = 3 println("p4.x = \(p4.x), p4.y = \(p4.y)") // p4.x = 3, p4.y = 5 println("p3.x = \(p3.x), p3.y = \(p3.y)") // p3.x = 3, p3.y = 5 /**********************/ p3.plet.x = 4 println("p4.p.x = \(p3.plet.x), p4.p.y = \(p3.plet.y)") // p3.plet.x = 4, p3.plet.y = 0 let p5 = Point4() //p3.plet = p5 // can't assign new value to p3.plet since the realtion can't change since the p property of p3 is a constant. p3.pvar = p5 // even p3 is a constant, its propery can change. struct Point { var x = 0 let y = 0 } var a = Point() let b = Point() a.x = 1 // var, right. //a.y = 2 // let, compile time error. //b.x = 3 // let, compile time error. //b.y = 4 // let, compile time error.
gpl-2.0
20afbad00c1be67bbd6e072cac9dce61
24.92
125
0.522964
2.713089
false
false
false
false
xuyunan/YNRefreshController
YNRefreshController/YNMoreController.swift
1
4613
// // YNMoreController.swift // YNRefreshController // // Created by Tommy on 15/3/13. // Copyright (c) 2015年 [email protected]. All rights reserved. // import Foundation import UIKit typealias YNRefreshHandler = () -> Void enum YNRefreshState : Printable { case Normal case Loading case Dragging; var description: String { get { switch self { case .Normal: return "Normal" case .Loading: return "Loading" case .Dragging: return "Dragging" } } } } class YNMoreController : NSObject { let refreshView: YNRefreshView! let scrollView: UIScrollView! var originalInsetBottom: CGFloat! var newInsetBottom: CGFloat { get { return originalInsetBottom + additionalInsetBottom } } var additionalInsetBottom: CGFloat { get { return self.refreshView.bounds.height } } var refreshState: YNRefreshState = .Normal { didSet { if oldValue != self.refreshState { self.refreshStateDidChanged(self.refreshState) } } } var isLoading: Bool { get { return self.refreshState == .Loading } } var refreshHandler: YNRefreshHandler? init(scrollView: UIScrollView) { super.init() self.scrollView = scrollView self.originalInsetBottom = scrollView.contentInset.bottom self.refreshView = YNRefreshView() refreshView.textLabel.text = "上拉加载更多..." scrollView.addSubview(refreshView) layoutSubviews() addObservers() } func layoutSubviews() { var frame = refreshView.frame frame.origin.y = scrollView.contentSize.height refreshView.frame = frame } func addObservers() { scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil) scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil) } func removeObservers() { scrollView.removeObserver(self, forKeyPath: "contentOffset") scrollView.removeObserver(self, forKeyPath: "contentSize") } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if keyPath == "contentOffset" { if scrollView.contentOffset.y > 0 && scrollView.contentSize.height > scrollView.bounds.size.height { if refreshView.hidden { refreshView.hidden = false } } else { if !refreshView.hidden { refreshView.hidden = true } return } if !self.isLoading { var distanceToBottom = scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentSize.height if distanceToBottom > additionalInsetBottom { if scrollView.dragging { self.refreshState = .Dragging } else { self.refreshState = .Loading; } } else { self.refreshState = .Normal; } } } else if keyPath == "contentSize" { layoutSubviews() } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } func refreshStateDidChanged(newState: YNRefreshState) { var inset = scrollView.contentInset switch newState { case .Normal: inset.bottom = originalInsetBottom scrollView.contentInset = inset refreshView.textLabel.text = "上拉加载更多..." case .Loading: inset.bottom = newInsetBottom scrollView.contentInset = inset refreshView.textLabel.text = "加载中..." if let refreshHandler = refreshHandler { refreshHandler() } case .Dragging: scrollView.contentInset = inset refreshView.textLabel.text = "松开加载更多..." } } func refreshHandler(handler: YNRefreshHandler) { refreshHandler = handler } deinit { removeObservers() } }
mit
c7d14cf3046884d1bc887f72ce37c683
28.294872
156
0.563143
5.578755
false
false
false
false
mtransitapps/mtransit-for-ios
MonTransit/Source/UI/ViewController/FavoritesViewController.swift
1
11723
// // FavoritesViewController.swift // MonTransit // // Created by Thibault on 16-01-20. // Copyright © 2016 Thibault. All rights reserved. // import UIKit import CoreLocation import MapKit import GoogleMobileAds class FavoritesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var menuButton:UIBarButtonItem! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var bannerConstraint: NSLayoutConstraint! private var mSelectedFavorite:FavoriteObject! private var mRefreshControl:UIRefreshControl! private let mOperationQueue = NSOperationQueue() private var mRefreshTimer = NSTimer() var mBusProvider:BusDataProviderHelper! var mTripProvider:TripDataProviderHelper! var mStopProvider:StationDataProviderHelper! var mFavoritesProvider:FavoritesDataProviderHelper! var mSections:[Section] = [] // custom type to represent table sections class Section { var type:SQLProvider.DatabaseType! var title:String! var favorites: [FavoriteObject] = [] func addFavorites(iTitle:String, iFav: [FavoriteObject], iType:SQLProvider.DatabaseType) { self.type = iType self.title = iTitle self.favorites = iFav } } override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.barStyle = .Black; self.tableView.delegate = self self.tableView.dataSource = self if revealViewController() != nil { revealViewController().delegate = self revealViewController().rearViewRevealWidth = 180 menuButton.target = revealViewController() menuButton.action = #selector(SWRevealViewController.revealToggle(_:)) revealViewController().draggableBorderWidth = 100 self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) } pullToRefresh() self.addIAdBanner() mBusProvider = BusDataProviderHelper() mTripProvider = TripDataProviderHelper() mStopProvider = StationDataProviderHelper() mFavoritesProvider = FavoritesDataProviderHelper() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController!.navigationBar.barTintColor = ColorUtils.hexStringToUIColor("212121") retrieveFavorites() mRefreshTimer = NSTimer.scheduledTimerWithTimeInterval(45, target:self, selector: #selector(FavoritesViewController.updateTimer), userInfo: nil, repeats: true) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) mOperationQueue.cancelAllOperations() self.clearAllNotice() mRefreshTimer.invalidate() } var adRecieved:Bool = false override func adViewDidReceiveAd(bannerView: GADBannerView!) { super.adViewDidReceiveAd(bannerView) if (!self.adRecieved) { bannerConstraint.constant = -CGRectGetHeight(bannerView.frame) self.adRecieved = true; } } func retrieveFavorites() { mSections.removeAll() self.pleaseWait() let wFavoritesOperation = NSBlockOperation { for wAgency in AgencyManager.getAgencies(){ // get favorites let iId = wAgency.mAgencyId var wListOfFav = self.mFavoritesProvider.retrieveFavorites(iId, iType: wAgency.mAgencyType) wListOfFav = self.processFavorites(wListOfFav, iId: iId) let wSection = Section() wSection.addFavorites(wAgency.mAgencyName, iFav: wListOfFav, iType: wAgency.mAgencyType) self.mSections.append(wSection) } dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.clearAllNotice() } } wFavoritesOperation.qualityOfService = .Background mOperationQueue.addOperation(wFavoritesOperation) } func processFavorites(iListOfFav:[FavoriteObject], iId:Int) -> [FavoriteObject] { for wFav in iListOfFav { wFav.setRelatedBus(mBusProvider.retrieveRouteById(wFav.getRouteId(), iId:iId)) wFav.setRelatedTrip(mTripProvider.retrieveTripById(wFav.getTripId(), iId:iId)) wFav.setRelatedStation(mStopProvider.retrieveStationById(wFav.getStopId(), iTripId:wFav.getTripId(), iId:iId)) } return iListOfFav } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. if !mSections.isEmpty{ return mSections.count } return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. if !mSections.isEmpty{ return mSections[section].favorites.count } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("favoriteCell", forIndexPath: indexPath) as! FavoriteTableViewCell if mSections.count > 0 { if nil != mSections[indexPath.section].favorites[indexPath.row].getRelatedBus() { let wFav = mSections[indexPath.section].favorites[indexPath.row] cell.addFavoriteParameter(wFav.getRelatedStation().getStationTitle(), iBusNumber: wFav.getRelatedBus().getBusNumber(), iDirection: wFav.getRelatedTrip().getTripDirection(), iColor: wFav.getRelatedBus().getBusColor(), iDistance: wFav.getRelatedStation().distanceToUser(AppDelegate().sharedInstance().getUserLocation())) cell.setAlert(AppDelegate().sharedInstance().getJson().retrieveAlertByContainStationId(wFav.getRelatedBus().getBusId(), iDirection: wFav.getRelatedTrip().getTripDirection(), iStationId: wFav.getRelatedStation().getStationCode())) if wFav.getRelatedGtfs() == nil { cell.setUpNearestComputations(wFav,iId: wFav.getAgencyId(), iType: mSections[indexPath.section].type) } else{ let wMin = (wFav.getRelatedGtfs().count > 0 ? wFav.getRelatedGtfs()[0].getNSDate().getMinutesDiference(NSDate()) : -1) let wSecondMin = (wFav.getRelatedGtfs().count > 1 ? wFav.getRelatedGtfs()[1].getNSDate().getMinutesDiference(NSDate()) : -1) cell.addTime(wMin, iSecondHour: wSecondMin) } } } return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if !mSections.isEmpty && mSections[section].favorites.count != 0 { return mSections[section].title } return "" } // Override to support conditional editing of the table view. 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. func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source let wSelectedFavorite = mSections[indexPath.section].favorites[indexPath.row] mFavoritesProvider.removeFavorites(wSelectedFavorite, iId: wSelectedFavorite.getAgencyId()) mSections[indexPath.section].favorites.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) self.tableView.reloadData() } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Get Cell Label let indexPath = tableView.indexPathForSelectedRow; mSelectedFavorite = mSections[indexPath!.section].favorites[indexPath!.row] performSegueWithIdentifier("StopIdentifier", sender: self) } func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if mSections.isEmpty || mSections.count == 0 || (indexPath.section <= mSections.count && indexPath.row <= mSections[indexPath.section].favorites.count && mSections[indexPath.section].favorites[indexPath.row].getRelatedGtfs() == nil) { return nil } return indexPath } // 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. if (segue.identifier == "StopIdentifier") { // initialize new view controller and cast it as your view controller let viewController = segue.destinationViewController as! StopViewController if nil != mSelectedFavorite { viewController.mSelectedStation = mSelectedFavorite.getRelatedStation() viewController.mSelectedBus = mSelectedFavorite.getRelatedBus() viewController.mSelectedTrip = mSelectedFavorite.getRelatedTrip() AgencyManager.setCurrentAgency(mSelectedFavorite.getAgencyId()) } } } @IBAction func doEdit(sender: AnyObject) { if (self.tableView.editing) { self.tableView.setEditing(false, animated: true) } else { self.tableView.setEditing(true, animated: true) } } /* TIMER */ func updateTimer() { if revealViewController() != nil && revealViewController().frontViewPosition == FrontViewPosition.Left { self.retrieveFavorites() } } /* PULL TO REFRESH */ func pullToRefresh(){ self.mRefreshControl = UIRefreshControl() self.mRefreshControl.attributedTitle = NSAttributedString(string: "") self.mRefreshControl.addTarget(self, action: #selector(FavoritesViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged) self.tableView.addSubview(mRefreshControl) } func refresh(sender:AnyObject) { self.retrieveFavorites() self.mRefreshControl.endRefreshing() } }
apache-2.0
ff3dcdbf46e6d9aaeb3957b88e35047d
35.746082
334
0.628391
5.757367
false
false
false
false
Constructor-io/constructorio-client-swift
UserApplication/Screens/Cart/UI/CartItemTableViewCell.swift
1
915
// // CartItemTableViewCell.swift // UserApplication // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import UIKit class CartItemTableViewCell: UITableViewCell { @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var labelQuantity: UILabel! @IBOutlet weak var labelTotalPrice: UILabel! @IBOutlet weak var imageViewProduct: UIImageView! func setup(_ model: CartItemViewModel){ self.labelTitle.text = model.title self.labelQuantity.text = model.quantity.string self.labelTotalPrice.text = model.singleItemPrice self.imageViewProduct.kf.setImage(with: URL(string: model.imageURL)) self.labelTitle.font = UIFont.appFontSemiBold(18) self.labelTotalPrice.font = UIFont.appFont(17) self.labelTotalPrice.adjustsFontSizeToFitWidth = true self.labelQuantity.font = UIFont.appFont(11) } }
mit
c78ce218232671d1f3abdcc45b72cf1f
30.517241
76
0.717724
4.29108
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
Sources/CoreAPI/CoreAPI_AuthVault.swift
1
20277
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import Foundation extension CoreAPI { final class AuthVault { // MARK: - Types enum AuthRegenerationType: Equatable { case create // destroy and recreate a new token case renewOrCreate // just renew the current token's expiry (performs `create` if no token) case reauthorize(LoginCredentials) // renew the current token the specified credentials (fails if no token) } typealias SignedRequestCompletion = ((Result<URLRequest, Error>) -> Void) // MARK: Funcs init(baseURL: URL, key: String, secret: String, tokenLife: Int = 7_776_000, urlSession: URLSession, dataStore: ShopGunSDKDataStore?) { self.baseURL = baseURL self.key = key self.secret = secret self.tokenLife = tokenLife self.dataStore = dataStore self.urlSession = urlSession self.activeRegenerateTask = nil // load clientId/authState from the store (if provided) let storedAuth = AuthVault.loadFromDataStore(dataStore) if let auth = storedAuth.auth { // Apply stored auth if it exists self.authState = .authorized(token: auth.token, user: auth.user, clientId: storedAuth.clientId) } else if let legacyAuthState = AuthVault.loadLegacyAuthState() { // load, apply & clear any legacy auth from the previous version of the SDK self.authState = legacyAuthState self.updateStore() AuthVault.clearLegacyAuthState() Logger.log("Loaded AuthState from Legacy cache", level: .debug, source: .CoreAPI) } else { // If no stored auth, or legacy auth to migrate, mark as unauthorized. self.authState = .unauthorized(error: nil, clientId: storedAuth.clientId) } } func regenerate(_ type: AuthRegenerationType, completion: ((Error?) -> Void)? = nil) { self.queue.async { [weak self] in self?.regenerateOnQueue(type, completion: completion) } } // Returns a new urlRequest that has been signed with the authToken // If we are not authorized, or in the process of authorizing, then this can take some time to complete. func signURLRequest(_ urlRequest: URLRequest, completion: @escaping SignedRequestCompletion) { self.queue.async { [weak self] in self?.signURLRequestOnQueue(urlRequest, completion: completion) } } var authorizedUserDidChangeCallback: ((_ prev: AuthorizedUser?, _ new: AuthorizedUser?) -> Void)? var additionalRequestParams: [String: String] = [:] /// If we are authorized, and have an authorized user, then this is non-nil var currentAuthorizedUser: AuthorizedUser? { if case .authorized(_, let user, _) = self.authState, user != nil { return user } else { return nil } } func resetStoredAuthState() { self.queue.async { [weak self] in guard let s = self else { return } AuthVault.clearLegacyAuthState() AuthVault.updateDataStore(s.dataStore, data: nil) s.authState = .unauthorized(error: nil, clientId: nil) } } // MARK: - Private Types enum AuthState { case unauthorized(error: Error?, clientId: ClientIdentifier?) // we currently have no auth (TODO: `reason` enum insted of error?) case authorized(token: String, user: AuthorizedUser?, clientId: ClientIdentifier?) // we have signed headers to return } // MARK: Private Vars private let baseURL: URL private let key: String private let secret: String private let tokenLife: Int private weak var dataStore: ShopGunSDKDataStore? private let urlSession: URLSession private let queue = DispatchQueue(label: "ShopGunSDK.CoreAPI.AuthVault.Queue") // if we are in the process of regenerating the token, this is set private var activeRegenerateTask: (type: AuthRegenerationType, task: URLSessionTask)? private var pendingSignedRequests: [(URLRequest, SignedRequestCompletion)] = [] private var authState: AuthState { didSet { // save the current authState to the store updateStore() // TODO: change to 'authStateDidChange', and trigger for _any_ change to the authState guard let authDidChangeCallback = self.authorizedUserDidChangeCallback else { return } var prevAuthUser: AuthorizedUser? = nil if case .authorized(_, let user?, _) = oldValue { prevAuthUser = user } if prevAuthUser?.person != currentAuthorizedUser?.person || prevAuthUser?.provider != currentAuthorizedUser?.provider { authDidChangeCallback(prevAuthUser, currentAuthorizedUser) } } } var clientId: ClientIdentifier? { switch self.authState { case .authorized(_, _, let clientId), .unauthorized(_, let clientId): return clientId } } var sessionToken: String? { guard case let .authorized(token, _, _) = self.authState else { return nil } return token } // MARK: Funcs private func regenerateOnQueue(_ type: AuthRegenerationType, completion: ((Error?) -> Void)? = nil) { // If we are in the process of doing a different kind of regen, cancel it cancelActiveRegenerateTask() var mutableCompletion = completion // generate a request based on the regenerate type let request: CoreAPI.Request<AuthSessionResponse> switch (type, self.authState) { case (.create, _), (.renewOrCreate, .unauthorized): request = AuthSessionResponse.createRequest(clientId: self.clientId, apiKey: self.key, tokenLife: self.tokenLife) case (.renewOrCreate, .authorized): request = AuthSessionResponse.renewRequest(clientId: self.clientId) case (.reauthorize(let credentials), .authorized): request = AuthSessionResponse.renewRequest(clientId: self.clientId, additionalParams: credentials.requestParams) case (.reauthorize, .unauthorized): // if we have no valid token at all when trying to reauthorize then just create request = AuthSessionResponse.createRequest(clientId: self.clientId, apiKey: self.key, tokenLife: self.tokenLife) // once completed, if we are authorized, then reauthorize with the credentials mutableCompletion = { [weak self] (createError) in self?.queue.async { [weak self] in guard case .authorized? = self?.authState else { DispatchQueue.main.async { completion?(createError) } return } self?.regenerate(type, completion: completion) } } } var urlRequest = request.urlRequest(for: self.baseURL, additionalParameters: self.additionalRequestParams) if case .authorized(let token, _, _) = self.authState, request.requiresAuth == true { urlRequest = urlRequest.signedForCoreAPI(withToken: token, secret: self.secret) } let task = self.urlSession.coreAPIDataTask(with: urlRequest) { [weak self] (authSessionResult: Result<AuthSessionResponse, Error>) -> Void in self?.queue.async { [weak self] in self?.activeRegenerateTaskCompleted(authSessionResult) DispatchQueue.main.async { mutableCompletion?(authSessionResult.getFailure()) } } } self.activeRegenerateTask = (type: type, task: task) task.resume() } private func signURLRequestOnQueue(_ urlRequest: URLRequest, completion: @escaping SignedRequestCompletion) { // check if we are in the process of regenerating the token // if so just save the completion handler to be run once regeneration finishes guard self.activeRegenerateTask == nil else { self.pendingSignedRequests.append((urlRequest, completion)) return } switch self.authState { case .unauthorized(let authError, _): if let authError = authError { // unauthorized, with an error, so perform completion and forward the error DispatchQueue.main.async { completion(.failure(authError)) } } else { // unauthorized, without an error, so cache completion & start regenerating token self.pendingSignedRequests.append((urlRequest, completion)) self.regenerate(.renewOrCreate) } case let .authorized(token, _, _): // we are authorized, so sign the request and perform the completion handler let signedRequest = urlRequest.signedForCoreAPI(withToken: token, secret: self.secret) DispatchQueue.main.async { completion(.success(signedRequest)) } } } /// Save the current AuthState to the store private func updateStore() { guard let store = self.dataStore else { return } switch self.authState { case .unauthorized(_, nil): AuthVault.updateDataStore(store, data: nil) case let .unauthorized(_, clientId): AuthVault.updateDataStore(store, data: StoreData(auth: nil, clientId: clientId)) case let .authorized(token, user, clientId): AuthVault.updateDataStore(store, data: StoreData(auth: (token: token, user: user), clientId: clientId)) } } // If we are in the process of doing a different kind of regen, cancel it private func cancelActiveRegenerateTask() { self.activeRegenerateTask?.task.cancel() self.activeRegenerateTask = nil } private func activeRegenerateTaskCompleted(_ result: Result<AuthSessionResponse, Error>) { switch result { case .success(let authSession): Logger.log("Successfully updated authSession \(authSession)", level: .debug, source: .CoreAPI) self.authState = .authorized(token: authSession.token, user: authSession.authorizedUser, clientId: authSession.clientId) self.activeRegenerateTask = nil // we are authorized, so sign the requests and perform the completion handlers for (urlRequest, completion) in self.pendingSignedRequests { let signedRequest = urlRequest.signedForCoreAPI(withToken: authSession.token, secret: self.secret) DispatchQueue.main.async { completion(.success(signedRequest)) } } case .failure(let cancelError as NSError) where cancelError.domain == NSURLErrorDomain && cancelError.code == URLError.Code.cancelled.rawValue: // if cancelled then ignore break case .failure(let regenError): Logger.log("Failed to update authSession \(regenError)", level: .error, source: .CoreAPI) let type = activeRegenerateTask?.type self.activeRegenerateTask = nil // we weren't creating, and the error isnt a network error, so try to just create the token. if type != .create && (regenError as NSError).isNetworkError == false { self.regenerateOnQueue(.create) } else { for (_, completion) in self.pendingSignedRequests { DispatchQueue.main.async { completion(.failure(regenError)) } } } } } } } // MARK: - extension CoreAPI.AuthVault { /// The response from requests to the API's session endpoint fileprivate struct AuthSessionResponse: Decodable { var clientId: CoreAPI.ClientIdentifier var token: String var expiry: Date var authorizedUser: CoreAPI.AuthorizedUser? enum CodingKeys: String, CodingKey { case clientId = "client_id" case token = "token" case expiry = "expires" case provider = "provider" case person = "user" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.clientId = try values.decode(CoreAPI.ClientIdentifier.self, forKey: .clientId) self.token = try values.decode(String.self, forKey: .token) if let provider = try? values.decode(CoreAPI.AuthorizedUserProvider.self, forKey: .provider), let person = try? values.decode(CoreAPI.Person.self, forKey: .person) { self.authorizedUser = (person, provider) } let expiryString = try values.decode(String.self, forKey: .expiry) if let expiryDate = CoreAPI.dateFormatter.date(from: expiryString) { self.expiry = expiryDate } else { throw DecodingError.dataCorruptedError(forKey: .expiry, in: values, debugDescription: "Date string does not match format expected by formatter (\(String(describing: CoreAPI.dateFormatter.dateFormat))).") } } // MARK: Response-generating requests static func createRequest(clientId: CoreAPI.ClientIdentifier?, apiKey: String, tokenLife: Int) -> CoreAPI.Request<AuthSessionResponse> { var params: [String: String] = [:] params["api_key"] = apiKey params["token_ttl"] = String(tokenLife) params["clientId"] = clientId?.rawValue return .init(path: "v2/sessions", method: .POST, requiresAuth: false, httpBody: params, timeoutInterval: 10) } static func renewRequest(clientId: CoreAPI.ClientIdentifier?, additionalParams: [String: String] = [:]) -> CoreAPI.Request<AuthSessionResponse> { var params: [String: String] = additionalParams params["clientId"] = clientId?.rawValue return .init(path: "v2/sessions", method: .PUT, requiresAuth: true, httpBody: params, timeoutInterval: 10) } } } // MARK: - DataStore extension CoreAPI.AuthVault { fileprivate static let dataStoreKey = "ShopGunSDK.CoreAPI.AuthVault" fileprivate static func updateDataStore(_ dataStore: ShopGunSDKDataStore?, data: CoreAPI.AuthVault.StoreData?) { var authJSON: String? = nil if let data = data, let authJSONData: Data = try? JSONEncoder().encode(data) { authJSON = String(data: authJSONData, encoding: .utf8) } dataStore?.set(value: authJSON, for: CoreAPI.AuthVault.dataStoreKey) } fileprivate static func loadFromDataStore(_ dataStore: ShopGunSDKDataStore?) -> CoreAPI.AuthVault.StoreData { guard let authJSONData = dataStore?.get(for: CoreAPI.AuthVault.dataStoreKey)?.data(using: .utf8), let auth = try? JSONDecoder().decode(CoreAPI.AuthVault.StoreData.self, from: authJSONData) else { return .init(auth: nil, clientId: nil) } return auth } // The data to be saved/read from disk fileprivate struct StoreData: Codable { var auth: (token: String, user: CoreAPI.AuthorizedUser?)? var clientId: CoreAPI.ClientIdentifier? init(auth: (token: String, user: CoreAPI.AuthorizedUser?)?, clientId: CoreAPI.ClientIdentifier?) { self.auth = auth self.clientId = clientId } enum CodingKeys: String, CodingKey { case authToken = "auth.token" case authUserPerson = "auth.user.person" case authUserProvider = "auth.user.provider" case clientId = "clientId" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if let token = try? values.decode(String.self, forKey: .authToken) { let authorizedUser: CoreAPI.AuthorizedUser? if let provider = try? values.decode(CoreAPI.AuthorizedUserProvider.self, forKey: .authUserProvider), let person = try? values.decode(CoreAPI.Person.self, forKey: .authUserPerson) { authorizedUser = (person, provider) } else { authorizedUser = nil } self.auth = (token: token, user: authorizedUser) } else { self.auth = nil } self.clientId = try? values.decode(CoreAPI.ClientIdentifier.self, forKey: .clientId) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try? container.encode(self.auth?.token, forKey: .authToken) try? container.encode(self.auth?.user?.person, forKey: .authUserPerson) try? container.encode(self.auth?.user?.provider, forKey: .authUserProvider) try? container.encode(self.clientId, forKey: .clientId) } } } // MARK: - extension URLRequest { /// Generates a new URLRequest that includes the signed HTTPHeaders, given a token & secret fileprivate func signedForCoreAPI(withToken token: String, secret: String) -> URLRequest { // make an SHA256 Hex string let hashString = (secret + token).sha256() var signedRequest = self signedRequest.setValue(token, forHTTPHeaderField: "X-Token") signedRequest.setValue(hashString, forHTTPHeaderField: "X-Signature") return signedRequest } } // MARK: - extension CoreAPI.LoginCredentials { /// What are the request params that a specific loginCredential needs to send when reauthorizing fileprivate var requestParams: [String: String] { switch self { case .logout: return ["email": ""] case let .shopgun(email, password): return ["email": email, "password": password] case let .facebook(token): return ["facebook_token": token] } } }
mit
fbed6178097b40f300049954c96d3e00
43.067982
219
0.567952
5.404788
false
false
false
false
slashlos/Helium
Helium/Helium/HeliumPanel.swift
1
9222
// // Panel.swift // Helium // // Created by shdwprince on 8/10/16. // Copyright © 2016 Jaden Geller. All rights reserved. // Copyright © 2017 Carlos D. Santiago. All rights reserved. // import Foundation import Cocoa // Sugar extension NSPoint { static func - (left: NSPoint, right: NSPoint) -> NSPoint { return NSPoint(x: left.x - right.x, y: left.y - right.y) } } class HeliumDocPromise : NSFilePromiseProvider { func pasteboardWriter(forPanel panel: HeliumPanel) -> NSPasteboardWriting { let provider = NSFilePromiseProvider(fileType: kUTTypeJPEG as String, delegate: panel.heliumPanelController) provider.userInfo = (provider.delegate as! HeliumPanelController).promiseContents return provider } // MARK: - NSFilePromiseProviderDelegate /// - Tag: ProvideFileName func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String { return (delegate as! HeliumPanelController).filePromiseProvider(filePromiseProvider, fileNameForType: fileType) } /// - Tag: ProvideOperationQueue func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue { return (delegate as! HeliumPanelController).workQueue } /// - Tag: PerformFileWriting func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) { (delegate as! HeliumPanelController).filePromiseProvider(filePromiseProvider, writePromiseTo: url, completionHandler: completionHandler) } } class HeliumPanel: NSPanel, NSPasteboardWriting, NSDraggingSource { var heliumPanelController : HeliumPanelController { get { return delegate as! HeliumPanelController } } var promiseFilename : String { get { return heliumPanelController.promiseFilename } } var promiseURL : URL { get { return heliumPanelController.promiseURL } } // nil when not dragging var previousMouseLocation: NSPoint? override func sendEvent(_ event: NSEvent) { switch event.type { case .flagsChanged: // If modifier key was released, dragging should be disabled if !event.modifierFlags.contains(NSEvent.ModifierFlags.command) { previousMouseLocation = nil } case .leftMouseDown: if event.modifierFlags.contains(NSEvent.ModifierFlags.command) { previousMouseLocation = event.locationInWindow } case .leftMouseUp: previousMouseLocation = nil case .leftMouseDragged: if let previousMouseLocation = previousMouseLocation { let delta = previousMouseLocation - event.locationInWindow let newOrigin = self.frame.origin - delta self.setFrameOrigin(newOrigin) return // don't pass event to super } default: break } super.sendEvent(event) } func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { return (context == .outsideApplication) ? [.copy] : [] } func performDragOperation(_ sender: NSDraggingInfo) -> Bool { return heliumPanelController.performDragOperation(sender) } required convenience init(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { Swift.print("ppl type: \(type.rawValue)") self.init() } func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { Swift.print("ppl type: \(type.rawValue)") switch type { case .promise: return promiseURL.absoluteString as NSString case .fileURL, .URL: return NSKeyedArchiver.archivedData(withRootObject: promiseURL) case .string: return promiseURL.absoluteString default: Swift.print("unknown \(type)") return nil } } func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { var types : [NSPasteboard.PasteboardType] = [.fileURL, .URL, .string] types.append((promiseURL.isFileURL ? .files : .promise)) Swift.print("wtp \(types)") return types } func writingOptions(forType type: NSPasteboard.PasteboardType, pasteboard: NSPasteboard) -> NSPasteboard.WritingOptions { Swift.print("wtp type: \(type.rawValue)") switch type { default: return .promised } } override var canBecomeKey: Bool { return true } override var canBecomeMain: Bool { return true } func selectTabItem(_ sender: Any?) { if let item = (sender as? NSMenuItem), let window : NSWindow = item.representedObject as? NSWindow, let group = window.tabGroup { Swift.print("set selected window within group: \(String(describing: window.identifier))") group.selectedWindow = window windowController?.synchronizeWindowTitleWithDocumentName() } } override func addTabbedWindow(_ window: NSWindow, ordered: NSWindow.OrderingMode) { super.addTabbedWindow(window, ordered: ordered) window.invalidateRestorableState() } override func moveTabToNewWindow(_ sender: Any?) { super.moveTabToNewWindow(sender) self.invalidateRestorableState() } override func selectPreviousTab(_ sender: Any?) { super.selectPreviousTab(sender) windowController?.synchronizeWindowTitleWithDocumentName() } override func selectNextTab(_ sender: Any?) { super.selectNextTab(sender) windowController?.synchronizeWindowTitleWithDocumentName() } } class PlaylistsPanel : NSPanel { } class ReleasePanel : HeliumPanel { } // Offset a window from the current app key window extension NSWindow { var titlebarHeight : CGFloat { if self.styleMask.contains(.fullSizeContentView), let svHeight = self.standardWindowButton(.closeButton)?.superview?.frame.height { return svHeight } let contentHeight = contentRect(forFrameRect: frame).height let titlebarHeight = frame.height - contentHeight return titlebarHeight > k.TitleNormal ? k.TitleUtility : titlebarHeight } func offsetFromKeyWindow() { if let keyWindow = NSApp.keyWindow { self.offsetFromWindow(keyWindow) } else if let mainWindow = NSApp.mainWindow { self.offsetFromWindow(mainWindow) } } func offsetFromWindow(_ theWindow: NSWindow) { let titleHeight = theWindow.titlebarHeight let oldRect = theWindow.frame let newRect = self.frame // Offset this window from the window by title height pixels to right, just below // either the title bar or the toolbar accounting for incons and/or text. let x = oldRect.origin.x + k.TitleNormal var y = oldRect.origin.y + (oldRect.size.height - newRect.size.height) - titleHeight if let toolbar = theWindow.toolbar { if toolbar.isVisible { let item = theWindow.toolbar?.visibleItems?.first let size = item?.maxSize if ((size?.height)! > CGFloat(0)) { y -= (k.ToolbarItemSpacer + (size?.height)!); } else { y -= k.ToolbarItemHeight; } if theWindow.toolbar?.displayMode == .iconAndLabel { y -= (k.ToolbarItemSpacer + k.ToolbarTextHeight); } y -= k.ToolbarItemSpacer; } } self.setFrameOrigin(NSMakePoint(x,y)) } func overlayWindow(_ theWindow: NSWindow) { let oldRect = theWindow.frame let newRect = self.frame // let titleHeight = theWindow.isFloatingPanel ? k.TitleUtility : k.TitleNormal // Overlay this window over the chosen window let x = oldRect.origin.x var y = oldRect.origin.y + (oldRect.size.height - newRect.size.height) if let toolbar = theWindow.toolbar { if toolbar.isVisible { let item = theWindow.toolbar?.visibleItems?.first let size = item?.maxSize if ((size?.height)! > CGFloat(0)) { y -= (k.ToolbarItemSpacer + (size?.height)!); } else { y -= k.ToolbarItemHeight; } if theWindow.toolbar?.displayMode == .iconAndLabel { y -= (k.ToolbarItemSpacer + k.ToolbarTextHeight); } y -= k.ToolbarItemSpacer; } } self.setFrameOrigin(NSMakePoint(x,y)) } }
mit
3c1a0ed622241eac0718506d12adff48
33.531835
148
0.613666
5.217883
false
false
false
false
contactlab/CLABPush-Swift
CLABPush/CLABPushManager.swift
1
11277
/** * Copyright 2012-2017 ContactLab, Italy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation let kCLABDomain = "ContactLabPush" let kCLABRemoteAddressNeededMessage = "You need to specify a valid remote address on takeOff." let kCLABAppKeyNeededMessage = "You need to provide the appKey on takeOff." /** Singleton responsible to register, unregister and send red callbacks to the remote service. Inside your `AppDelegate` on `aplication:didFinishLaunchingWithOptions:` method perform the setup calling `takeOffWithBaseURL:appKey:` and inside the `application:didRegisterForRemoteNotificationsWithDeviceToken:` you should call let tokenString = CLABPushManager.convertDataToken(deviceToken) CLABPushManager.sharedInstance().registerDeviceToken(tokenString, userInfo: nil, completionHandler: { (data, response, error) -> Void in if let e = error { println("\(e.localizedDescription)") } }) */ open class CLABPushManager { /** A shared instance of `CLABPushManager`. */ static open let sharedInstance = CLABPushManager() var baseURL: URL? var session: URLSession? /** Configures `CLABPushManager` with the specified base URL and app key used to authenticate with the remote service. - parameter baseURL: The base URL to be used to construct requests; - parameter appKey: The Authorization token that will be used authenticate the application with the remote serive. */ open func takeOffWithBaseURL(_ baseURL: URL, appKey: String) { self.baseURL = baseURL let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.httpAdditionalHeaders = ["Authorization": "Token \(appKey)"] self.session = URLSession(configuration: sessionConfiguration) } /** Register a given device token to the remote service. - parameter deviceToken: The device token; - parameter userInfo: A `[String: NSObject]` dictionary with informations regarding the device and the user (if applicable); - parameter completionHandler: A block containing the response from the remote server, that will be executed after the connection finished. */ open func registerDeviceToken(_ deviceToken: String, userInfo: [String: NSObject]?, completionHandler: ((Data?, URLResponse?, Error?) -> Void)?) { assert(self.baseURL != nil, kCLABRemoteAddressNeededMessage) assert(self.session != nil, kCLABAppKeyNeededMessage) if let registerURL = endpoint(deviceToken: deviceToken) { var registerRequest = request(url: registerURL, contentTypes: ["application/json"]) registerRequest.httpMethod = "PUT" var postData = [String : Any]() let preferredLanguage = Locale.preferredLanguages.first! let endIndex = preferredLanguage.characters.index(preferredLanguage.startIndex, offsetBy: 2) let language = preferredLanguage.substring(to: endIndex) let appId = Bundle.main.bundleIdentifier var clabDictionary = [String : Any]() clabDictionary["appId"] = appId clabDictionary["language"] = language postData["clab"] = clabDictionary if let info = userInfo { postData["userInfo"] = info } var error: NSError? let data: Data? do { data = try JSONSerialization.data(withJSONObject: postData, options: JSONSerialization.WritingOptions.prettyPrinted) } catch let error1 as NSError { error = error1 data = nil } if let e = error { if let handler = completionHandler { handler(nil, nil, e) } } else if let d = data { registerRequest.httpBody = d } if let handler = completionHandler { let registerTask = self.session!.dataTask(with: registerRequest, completionHandler: handler) registerTask.resume() } else { let registerTask = self.session!.dataTask(with: registerRequest, completionHandler: { (data, response, error) -> Void in // We are not providing feedback as if the developer is interested can provide a completion handler }) registerTask.resume() } } else { if let handler = completionHandler { let errorDetail = [NSLocalizedDescriptionKey: "Invalid url provided"] let error = NSError(domain: kCLABDomain, code: 500, userInfo: errorDetail) handler(nil, nil, error); } } } /** Unregister a given device token from the remote service. - parameter deviceToken: The device token; - parameter completionHandler: A block containing the response from the remote server that will be executed after the connection finished. */ open func unregisterDeviceToken(_ deviceToken: String, completionHandler: ((Data?, URLResponse?, Error?) -> Void)?) { assert(self.baseURL != nil, kCLABRemoteAddressNeededMessage) assert(self.session != nil, kCLABAppKeyNeededMessage) if let unregisterURL = endpoint(deviceToken: deviceToken) { var unregisterRequest = request(url: unregisterURL, contentTypes: ["application/json"]) unregisterRequest.httpMethod = "DELETE" if let handler = completionHandler { let unregisterTask = self.session!.dataTask(with: unregisterRequest, completionHandler: handler) unregisterTask.resume() } else { let unregisterTask = self.session!.dataTask(with: unregisterRequest, completionHandler: { (data, response, error) -> Void in // We are not providing feedback as if the developer is interested can provide a completion handler }) unregisterTask.resume() } } else { if let handler = completionHandler { let errorDetail = [NSLocalizedDescriptionKey: "Invalid url provided"] let error = NSError(domain: kCLABDomain, code: 500, userInfo: errorDetail) handler(nil, nil, error); } } } /** Register that a push notification has been read. ContactLab generates it as a JSON dictionary that iOS automatically converts to a `[NSObject : AnyObject]` object; the dictionary may contain only property-list objects plus `NSNull`. Push dictionary sample (example): { aps = { alert = "Some Interesting Text"; badge = 4; sound = "alert.caf"; }; sampleTrackingKey = "http://yourdomain.com/campaign/1234/users/56/track"; } In the sample payload above the `sampleTrackingKey` value shoud be used as `trackingKey` param. - parameter pushNotification: A dictionary that contains information referring to the remote notification, potentially including a badge number for the application icon, an alert sound, an alert message to display to the user and custom data; - parameter trackingKey: Name of the key containing the remote url to be called to mark the notification as red; - parameter completionHandler: A block containing the response from the remote server that will be executed after the connection finished. */ open func onPushReadWithDictionary(_ dictionary: [AnyHashable: Any], trackingKey: String, completionHandler: ((Data?, URLResponse?, Error?) -> Void)?) { if let stringForTrackingPushOpenining = dictionary[trackingKey] as? String { if let trackingURL = URL(string: stringForTrackingPushOpenining) { var trackingRequest = request(url: trackingURL, contentTypes: ["image/gif", "application/json"]) trackingRequest.httpMethod = "GET" if let handler = completionHandler { let trackingTask = self.session!.dataTask(with: trackingRequest, completionHandler: handler) trackingTask.resume() } else { let trackingTask = self.session!.dataTask(with: trackingRequest, completionHandler: { (data, response, error) -> Void in // We are not providing feedback as if the developer is interested can provide a completion handler }) trackingTask.resume() } } else { if let handler = completionHandler { let errorDetail = [NSLocalizedDescriptionKey: "Tracking key \(trackingKey) doesn't contain a valid URL"] let error = NSError(domain: kCLABDomain, code: 500, userInfo: errorDetail) handler(nil, nil, error); } } } else { if let handler = completionHandler { let errorDetail = [NSLocalizedDescriptionKey: "Missing tracking key"] let error = NSError(domain: kCLABDomain, code: 500, userInfo: errorDetail) handler(nil, nil, error); } } } /** Convenience class method to convert a token from `NSData` to the `String` format accepted by the other `CLABPushManager` methods. - parameter dataToken: Token as returned by iOS. - returns: The converted value. */ open class func convertDataToken(_ dataToken: Data) -> String { let tokenString = dataToken.description.replacingOccurrences(of: "<", with: "", options: NSString.CompareOptions.literal, range: nil).replacingOccurrences(of: ">", with: "", options: NSString.CompareOptions.literal, range: nil).replacingOccurrences(of: " ", with: "", options: NSString.CompareOptions.literal, range: nil) return tokenString } func request(url: URL, contentTypes: [String]) -> URLRequest { var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) for type in contentTypes { request.addValue(type, forHTTPHeaderField: "Content-Type") request.addValue(type, forHTTPHeaderField: "Accept") } return request } func endpoint(deviceToken: String) -> URL? { return URL(string: "/apn/devices/\(deviceToken)", relativeTo: baseURL) } }
apache-2.0
7f7b2f8f62689e95945dbe340f09b38b
47.818182
329
0.632438
5.468962
false
false
false
false
Resoulte/DYZB
DYZB/DYZB/Classes/Main/Controller/DYAllBaseViewController.swift
1
1591
// // DYAllBaseViewController.swift // DYZB // // Created by 师飞 on 2017/3/4. // Copyright © 2017年 shifei. All rights reserved. // import UIKit class DYAllBaseViewController: UIViewController { // 定义属性 var contentionView : UIView? // MARK: 懒加载属性 fileprivate lazy var animationImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: UIImage(named: "img_loading_1")) // imageView.center = (self?.view.center)! imageView.center = self.view.center imageView.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!] imageView.animationDuration = 0.25 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return imageView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension DYAllBaseViewController { func setupUI() { // 1.隐藏内容view contentionView?.isHidden = true // 2.添加执行动画的UI self.view.addSubview(animationImageView) // 3.执行动画 animationImageView.startAnimating() view.backgroundColor = UIColor(r: 250, g: 250, b: 250) } func loadFinishedData() { animationImageView.stopAnimating() contentionView?.isHidden = false animationImageView.isHidden = true } }
mit
6abb6bcdaa663bab6178e85042270fd9
23.253968
104
0.602749
4.73065
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PXCardSlider/FSPager/FSPageViewLayout.swift
1
12970
import UIKit class FSPagerViewLayout: UICollectionViewLayout { var contentSize: CGSize = .zero var leadingSpacing: CGFloat = 0 var itemSpacing: CGFloat = 0 var needsReprepare = true var scrollDirection: FSPagerView.ScrollDirection = .horizontal override open class var layoutAttributesClass: AnyClass { return FSPagerViewLayoutAttributes.self } fileprivate var pagerView: FSPagerView? { return self.collectionView?.superview?.superview as? FSPagerView } fileprivate var isInfinite: Bool = true fileprivate var collectionViewSize: CGSize = .zero fileprivate var numberOfSections = 1 fileprivate var numberOfItems = 0 fileprivate var actualInteritemSpacing: CGFloat = 0 fileprivate var actualItemSize: CGSize = .zero override init() { super.init() self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } deinit { #if !os(tvOS) NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil) #endif } override open func prepare() { guard let collectionView = self.collectionView, let pagerView = self.pagerView else { return } guard self.needsReprepare || self.collectionViewSize != collectionView.frame.size else { return } self.needsReprepare = false self.collectionViewSize = collectionView.frame.size // Calculate basic parameters/variables self.numberOfSections = pagerView.numberOfSections(in: collectionView) self.numberOfItems = pagerView.collectionView(collectionView, numberOfItemsInSection: 0) self.actualItemSize = { var size = pagerView.itemSize if size == .zero { size = collectionView.frame.size } return size }() self.actualInteritemSpacing = { if let transformer = pagerView.transformer { return transformer.proposedInteritemSpacing() } return pagerView.interitemSpacing }() self.scrollDirection = pagerView.scrollDirection self.leadingSpacing = self.scrollDirection == .horizontal ? (collectionView.frame.width - self.actualItemSize.width) * 0.5 : (collectionView.frame.height - self.actualItemSize.height) * 0.5 self.itemSpacing = (self.scrollDirection == .horizontal ? self.actualItemSize.width : self.actualItemSize.height) + self.actualInteritemSpacing // Calculate and cache contentSize, rather than calculating each time self.contentSize = { let numberOfItems = self.numberOfItems * self.numberOfSections switch self.scrollDirection { case .horizontal: var contentSizeWidth: CGFloat = self.leadingSpacing * 2 // Leading & trailing spacing contentSizeWidth += CGFloat(numberOfItems - 1) * self.actualInteritemSpacing // Interitem spacing contentSizeWidth += CGFloat(numberOfItems) * self.actualItemSize.width // Item sizes let contentSize = CGSize(width: contentSizeWidth, height: collectionView.frame.height) return contentSize case .vertical: var contentSizeHeight: CGFloat = self.leadingSpacing * 2 // Leading & trailing spacing contentSizeHeight += CGFloat(numberOfItems - 1) * self.actualInteritemSpacing // Interitem spacing contentSizeHeight += CGFloat(numberOfItems) * self.actualItemSize.height // Item sizes let contentSize = CGSize(width: collectionView.frame.width, height: contentSizeHeight) return contentSize } }() self.adjustCollectionViewBounds() } override open var collectionViewContentSize: CGSize { return self.contentSize } override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() guard self.itemSpacing > 0, !rect.isEmpty else { return layoutAttributes } let rect = rect.intersection(CGRect(origin: .zero, size: self.contentSize)) guard !rect.isEmpty else { return layoutAttributes } // Calculate start position and index of certain rects let numberOfItemsBefore = self.scrollDirection == .horizontal ? max(Int((rect.minX - self.leadingSpacing) / self.itemSpacing), 0) : max(Int((rect.minY - self.leadingSpacing) / self.itemSpacing), 0) let startPosition = self.leadingSpacing + CGFloat(numberOfItemsBefore) * self.itemSpacing let startIndex = numberOfItemsBefore // Create layout attributes var itemIndex = startIndex var origin = startPosition let maxPosition = self.scrollDirection == .horizontal ? min(rect.maxX, self.contentSize.width - self.actualItemSize.width - self.leadingSpacing) : min(rect.maxY, self.contentSize.height - self.actualItemSize.height - self.leadingSpacing) // https://stackoverflow.com/a/10335601/2398107 while origin - maxPosition <= max(CGFloat(100.0) * .ulpOfOne * abs(origin + maxPosition), .leastNonzeroMagnitude) { let indexPath = IndexPath(item: itemIndex % self.numberOfItems, section: itemIndex / self.numberOfItems) let attributes = self.layoutAttributesForItem(at: indexPath) as! FSPagerViewLayoutAttributes self.applyTransform(to: attributes, with: self.pagerView?.transformer) layoutAttributes.append(attributes) itemIndex += 1 origin += self.itemSpacing } return layoutAttributes } override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = FSPagerViewLayoutAttributes(forCellWith: indexPath) attributes.indexPath = indexPath let frame = self.frame(for: indexPath) let center = CGPoint(x: frame.midX, y: frame.midY) attributes.center = center attributes.size = self.actualItemSize return attributes } override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = self.collectionView, let pagerView = self.pagerView else { return proposedContentOffset } var proposedContentOffset = proposedContentOffset func calculateTargetOffset(by proposedOffset: CGFloat, boundedOffset: CGFloat) -> CGFloat { var targetOffset: CGFloat if pagerView.decelerationDistance == FSPagerView.automaticDistance { if abs(velocity.x) >= 0.3 { let vector: CGFloat = velocity.x >= 0 ? 1.0 : -1.0 targetOffset = round(proposedOffset / self.itemSpacing + 0.35 * vector) * self.itemSpacing // Ceil by 0.15, rather than 0.5 } else { targetOffset = round(proposedOffset / self.itemSpacing) * self.itemSpacing } } else { let extraDistance = max(pagerView.decelerationDistance - 1, 0) switch velocity.x { case 0.3 ... CGFloat.greatestFiniteMagnitude: targetOffset = ceil(collectionView.contentOffset.x / self.itemSpacing + CGFloat(extraDistance)) * self.itemSpacing case -CGFloat.greatestFiniteMagnitude ... -0.3: targetOffset = floor(collectionView.contentOffset.x / self.itemSpacing - CGFloat(extraDistance)) * self.itemSpacing default: targetOffset = round(proposedOffset / self.itemSpacing) * self.itemSpacing } } targetOffset = max(0, targetOffset) targetOffset = min(boundedOffset, targetOffset) return targetOffset } let proposedContentOffsetX: CGFloat = { if self.scrollDirection == .vertical { return proposedContentOffset.x } let boundedOffset = collectionView.contentSize.width - self.itemSpacing return calculateTargetOffset(by: proposedContentOffset.x, boundedOffset: boundedOffset) }() let proposedContentOffsetY: CGFloat = { if self.scrollDirection == .horizontal { return proposedContentOffset.y } let boundedOffset = collectionView.contentSize.height - self.itemSpacing return calculateTargetOffset(by: proposedContentOffset.y, boundedOffset: boundedOffset) }() proposedContentOffset = CGPoint(x: proposedContentOffsetX, y: proposedContentOffsetY) return proposedContentOffset } // MARK: - Internal functions func forceInvalidate() { self.needsReprepare = true self.invalidateLayout() } func contentOffset(for indexPath: IndexPath) -> CGPoint { let origin = self.frame(for: indexPath).origin guard let collectionView = self.collectionView else { return origin } let contentOffsetX: CGFloat = { if self.scrollDirection == .vertical { return 0 } let contentOffsetX = origin.x - (collectionView.frame.width * 0.5 - self.actualItemSize.width * 0.5) return contentOffsetX }() let contentOffsetY: CGFloat = { if self.scrollDirection == .horizontal { return 0 } let contentOffsetY = origin.y - (collectionView.frame.height * 0.5 - self.actualItemSize.height * 0.5) return contentOffsetY }() let contentOffset = CGPoint(x: contentOffsetX, y: contentOffsetY) return contentOffset } func frame(for indexPath: IndexPath) -> CGRect { let numberOfItems = self.numberOfItems * indexPath.section + indexPath.item let originX: CGFloat = { if self.scrollDirection == .vertical { return (self.collectionView!.frame.width - self.actualItemSize.width) * 0.5 } return self.leadingSpacing + CGFloat(numberOfItems) * self.itemSpacing }() let originY: CGFloat = { if self.scrollDirection == .horizontal { return (self.collectionView!.frame.height - self.actualItemSize.height) * 0.5 } return self.leadingSpacing + CGFloat(numberOfItems) * self.itemSpacing }() let origin = CGPoint(x: originX, y: originY) let frame = CGRect(origin: origin, size: self.actualItemSize) return frame } // MARK: - Notification @objc fileprivate func didReceiveNotification(notification: Notification) { if self.pagerView?.itemSize == .zero { self.adjustCollectionViewBounds() } } // MARK: - Private functions fileprivate func commonInit() { #if !os(tvOS) NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotification(notification:)), name: UIDevice.orientationDidChangeNotification, object: nil) #endif } fileprivate func adjustCollectionViewBounds() { guard let collectionView = self.collectionView, let pagerView = self.pagerView else { return } let currentIndex = max(0, min(pagerView.currentIndex, pagerView.numberOfItems - 1)) let newIndexPath = IndexPath(item: currentIndex, section: self.isInfinite ? self.numberOfSections / 2 : 0) let contentOffset = self.contentOffset(for: newIndexPath) let newBounds = CGRect(origin: contentOffset, size: collectionView.frame.size) collectionView.bounds = newBounds pagerView.currentIndex = currentIndex } fileprivate func applyTransform(to attributes: FSPagerViewLayoutAttributes, with transformer: FSPagerViewTransformer?) { guard let collectionView = self.collectionView else { return } guard let transformer = transformer else { return } switch self.scrollDirection { case .horizontal: let ruler = collectionView.bounds.midX attributes.position = (attributes.center.x - ruler) / self.itemSpacing case .vertical: let ruler = collectionView.bounds.midY attributes.position = (attributes.center.y - ruler) / self.itemSpacing } attributes.zIndex = Int(self.numberOfItems) - Int(attributes.position) transformer.applyTransform(to: attributes) } }
mit
a942f936101e40240e0fb23db1c07aaf
44.508772
245
0.648111
5.585702
false
false
false
false
grantmagdanz/SnapBoard
Keyboard/SpellChecker.swift
1
6062
// // SpellChecker.swift // SnapBoard -- Multi-line Text for Snapchat // // Created by Grant Magdanz on 12/29/15. // Copyright © 2015 Apple. All rights reserved. // /// Translation of [Peter Norvig's spell checker](http://norvig.com/spell-correct.html) into Swift. /// Sample input corpus [here](http://norvig.com/big.txt) import Foundation struct SpellChecker { // the point at when the concurrent edits2 finds solutions iteratively let ITERATIVE_THRESHOLD = 10 var wordFrequencies: NSDictionary var words: NSArray // the spell checker will be passing in strings in all lowercase, so these keys need to be lowercase as well! var directCorrections = NSDictionary(dictionary: [ "i": "I", "lets": "let's", "snapboard": "SnapBoard" ]) init?(frequenciesFile: String, wordListFile: String) { if let frequencies = NSDictionary(contentsOfFile: frequenciesFile) { if let dictionary = NSArray(contentsOfFile: wordListFile) { wordFrequencies = frequencies words = dictionary } else { return nil } } else { return nil } } /// Given a word, produce a set of possible alternatives with /// letters transposed, deleted, replaced or rogue characters inserted func edits(word: String) -> Set<String> { if word.isEmpty { return [] } let splits = word.characters.indices.map { (word[word.startIndex..<$0], word[$0..<word.endIndex]) } let deletes = splits.map { $0.0 + String($0.1.characters.dropFirst()) } let transposes: [String] = splits.map{ left, right in if let fst = right.characters.first { let drop1 = right.characters.dropFirst() if let snd = drop1.first { let drop2 = drop1.dropFirst() return "\(left)" + String(snd) + String(fst) + String(drop2) } } return "" }.filter { !$0.isEmpty } let alphabet = "abcdefghijklmnopqrstuvwxyz" let replaces = splits.flatMap { left, right in alphabet.characters.map { "\(left)" + String($0) + String(right.characters.dropFirst())} } let inserts = splits.flatMap { left, right in alphabet.characters.map{"\(left)\($0)\(right)" } } let toReturn = Set(deletes + transposes + replaces + inserts) return toReturn } func knownEdits2(word: String) -> Set<String>? { let possibleEdits = Array(edits(word)) // setup concurrency let group = dispatch_group_create() let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) let numberOfThreads = Int(ceil(Double(possibleEdits.count) / Double(ITERATIVE_THRESHOLD))) // we need an array of Sets to make sure that we don't have a race condition var knownEditsOfEachThread: [Set<String>?] = [Set<String>?](count: numberOfThreads, repeatedValue: nil) // dispatch threads for i in 0..<numberOfThreads { dispatch_group_async(group, queue) { let base = i * self.ITERATIVE_THRESHOLD var knownEditsOfThisThread = Set<String>() // this takes care of the last iteration where we may not want to go ITERATIVE_THRESHOLD times let end = min(base + self.ITERATIVE_THRESHOLD, possibleEdits.count) for curr in base ..< end { if let k = self.known(self.edits(possibleEdits[curr])) { knownEditsOfThisThread.unionInPlace(k) } } knownEditsOfEachThread[i] = knownEditsOfThisThread } } var knownEdits: Set<String> = [] dispatch_group_wait(group, DISPATCH_TIME_FOREVER) for edits in knownEditsOfEachThread { if edits != nil { knownEdits.unionInPlace(edits!) } } print(knownEdits.count) return knownEdits.isEmpty ? nil : knownEdits } func known<S: SequenceType where S.Generator.Element == String>(words: S) -> Set<String>? { let s = Set(words.filter{ self.wordFrequencies.valueForKey($0) != nil }) return s.isEmpty ? nil : s } // literal being whether the string should be taken literally (i.e. do not try to auto capitalize it) or not func correct(word: String) -> (correctWord: String, literal: Bool) { // Probably shouldn't try to autocorrect a number huh? if let _ = Double(word) { return (word, true) } // Check if there is a direct edit if let directCorrection = directCorrections.valueForKey(word.lowercaseString) as? String { if directCorrection.capitalizedString == directCorrection { return (directCorrection, true) } else { return (directCorrection, false) } } // Is this a word already? Let's find out... if let index = binarySearch(words, target: word, caseSensitive: false) { let foundWord = words[index] as! String if foundWord.capitalizedString == foundWord || foundWord.uppercaseString == foundWord { return (foundWord, true) } else { return (foundWord, false) } } // We're just going to have to guess then... let candidates = known([word]) ?? known(edits(word)) //?? knownEdits2(word) let result = (candidates ?? []).reduce(word) { let val1 = (wordFrequencies.valueForKey($0) ?? Int.max) as! Int let val2 = (wordFrequencies.valueForKey($1) ?? Int.max) as! Int return val1 <= val2 ? $0 : $1 } return (result, false) } }
bsd-3-clause
f3d7c3fa9a45f523b59e672e62b3a3de
37.367089
113
0.567728
4.605623
false
false
false
false
Drusy/auvergne-webcams-ios
AuvergneWebcams/ApiRequest.swift
1
3541
// // ApiRequest.swift // AuvergneWebcams // // Created by AuvergneWebcams on 20/07/16. // Copyright © 2016 AuvergneWebcams. All rights reserved. // import Foundation import AlamofireObjectMapper import ObjectMapper import Alamofire import SwiftyUserDefaults import SwiftiumKit class ApiRequest { @discardableResult static func startStringQuery<T: Queryable>(forType type: T.Type, parameters: [String: Any]? = nil, handler: ((DataResponse<String>) -> Void)? = nil) -> Request { let request = startRequest(forType: type, parameters: parameters) request.responseString { response in if let request = response.request { print("Request: \(request)") } if let statusCode = response.response?.statusCode { print("Status code: \(statusCode)") } if let value = response.result.value { print("Value: \(value)") } if let error = response.result.error { print("Error: \(error)") } handler?(response) } return request } @discardableResult static func startDataQuery<T: Queryable>(forType type: T.Type, parameters: [String: Any]? = nil, handler: ((DataResponse<Data>) -> Void)? = nil) -> Request { let request = startRequest(forType: type, parameters: parameters) request.responseData { (response: DataResponse<Data>) in handler?(response) } return request } @discardableResult static func startQuery<T: Queryable>(forType type: T.Type, parameters: [String: Any]? = nil, handler: ((DataResponse<T>) -> Void)? = nil) -> Request { let request = startRequest(forType: type, parameters: parameters) request.responseObject { (response: DataResponse<T>) in handler?(response) } return request } // MARK: - Private static let headers: [String: String] = [ // "Accept": "application/json", "Cache-Control": "no-cache", "Accept-Encoding": "gzip" ] fileprivate static func url(forType queryableType: Queryable.Type) -> String { var urlComponents: URLComponents = URLComponents() urlComponents.scheme = queryableType.webServiceScheme urlComponents.host = queryableType.webServiceHost urlComponents.path = "\(queryableType.webServicePath)\(queryableType.webServiceLastSegmentPath)" let webServiceURL: String = try! urlComponents.asURL().absoluteString return webServiceURL } fileprivate static func startRequest(forType queryableType: Queryable.Type, parameters: [String: Any]? = nil) -> DataRequest { let allHeaders = headers + queryableType.complementaryHeaders let urlConvertible = url(forType: queryableType) let queryableParameters = queryableType.parameters() ?? [:] let requestParameters = parameters ?? [:] let computedParameters = queryableParameters + requestParameters return Alamofire.request(urlConvertible, method: queryableType.webServiceMethod, parameters: computedParameters, encoding: queryableType.encoding, headers: allHeaders) .validate() .debugLog() } }
apache-2.0
2cc0ca3a77c57e37af8377554b840c58
34.049505
165
0.597175
5.40458
false
false
false
false
ryanipete/AmericanChronicle
AmericanChronicle/Code/AppWide/ServicesAndManagers/SearchDataManager.swift
1
2956
// MARK: - // MARK: SearchDataManagerInterface protocol SearchDataManagerInterface { func fetchMoreResults(_ parameters: SearchParameters, completion: @escaping (Result<SearchResults, SearchError>) -> Void) func cancelFetch(_ parameters: SearchParameters) func isFetchInProgress(_ parameters: SearchParameters) -> Bool } // MARK: - // MARK: SearchDataManager final class SearchDataManager: SearchDataManagerInterface { // MARK: Properties private let webService: SearchPagesWebServiceInterface private let cacheService: SearchPagesCacheServiceInterface // MARK: Init methods init(webService: SearchPagesWebServiceInterface = SearchPagesWebService(), cacheService: SearchPagesCacheServiceInterface = SearchPagesCacheService()) { self.webService = webService self.cacheService = cacheService } // MARK: SearchDataManagerInterface methods func fetchMoreResults(_ parameters: SearchParameters, completion: @escaping (Result<SearchResults, SearchError>) -> Void) { let page: Int if let cachedResults = cacheService.resultsForParameters(parameters) { guard !cachedResults.allItemsLoaded else { completion(.failure(.allItemsLoaded(cachedResults))) return } page = cachedResults.numLoadedPages + 1 } else { page = 1 } webService.startSearch(with: parameters, page: page) { result in switch result { case .success(let freshResults): let allResults: SearchResults let resultsToCache: SearchResults if let cachedResults = self.cacheService.resultsForParameters(parameters) { cachedResults.addItems(freshResults.items) resultsToCache = cachedResults } else { resultsToCache = freshResults } allResults = resultsToCache self.cacheService.cacheResults(resultsToCache, forParameters: parameters) completion(.success(allResults)) case .failure(let error): completion(.failure(error)) } } } func cancelFetch(_ parameters: SearchParameters) { let page: Int if let cachedResults = cacheService.resultsForParameters(parameters) { page = cachedResults.numLoadedPages + 1 } else { page = 1 } webService.cancelSearch(parameters, page: page) } func isFetchInProgress(_ parameters: SearchParameters) -> Bool { let page: Int if let cachedResults = cacheService.resultsForParameters(parameters) { page = cachedResults.numLoadedPages + 1 } else { page = 1 } return webService.isSearchInProgress(parameters, page: page) } }
mit
1c9144a41f6473c4a5c45ca4c494fa9c
34.614458
95
0.626522
5.762183
false
false
false
false
StorageKit/StorageKit
Example/Source/SubExamples/API response/APIResponseRealmViewController.swift
1
1913
// // APIResponseViewController.swift // Example // // Created by Ennio Masi on 16/07/2017. // Copyright © 2017 MarcoSantaDev. All rights reserved. // import UIKit import StorageKit class APIResponseRealmViewController: UIViewController { private static let storageType = StorageKit.StorageType.Realm private let storage = StorageKit.addStorage(type: storageType) private var users: [APIUserCoreData]? private var tableViewController: APIResponseTableViewController? override func viewDidLoad() { super.viewDidLoad() saveNewUsers { [unowned self] in self.tableViewController?.reloadTable() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "tableViewSegue", let tableViewController = segue.destination as? APIResponseTableViewController { tableViewController.storageType = APIResponseRealmViewController.storageType tableViewController.storage = storage self.tableViewController = tableViewController } } private func saveNewUsers(completion: @escaping () -> Void) { let usersFetcher = UsersFetcher() usersFetcher.fetchUser { [unowned self] usersJSON in guard let usersJSON = usersJSON else { return } self.storage.performBackgroundTask { context in guard let context = context else { return } let users: [APIUserRealm] = usersJSON.flatMap { userJSON in do { guard let apiUser: APIUserRealm = try context.create() else { return nil } apiUser.username = userJSON["username"] as? String apiUser.fullname = userJSON["fullname"] as? String return apiUser } catch { return nil } } do { try context.deleteAll(APIUserRealm.self) try context.addOrUpdate(users) } catch { print(error) } DispatchQueue.main.async { completion() } } } } }
mit
66155e17377e83068f82084d98768e6d
28.415385
129
0.6909
4.530806
false
false
false
false
roadfire/Feeder
Feeder/FeedParser.swift
1
1656
// // FeedParser.swift // Feeder // // Created by Josh Brown on 5/20/17. // Copyright © 2017 Roadfire Software. All rights reserved. // import Foundation class FeedParser { func items(with data: Data) -> [Item] { var items = [Item]() do { guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { print("error parsing JSON") return items } guard let itemsJSON = json["items"] as? [[String: Any]] else { print("error getting items") return items } for itemJSON in itemsJSON { guard let id = itemJSON["id"] as? String else { print("error on id") continue } let urlString = itemJSON["url"] as? String let title = itemJSON["title"] as? String let contentHTML = itemJSON["content_html"] as? String let datePublishedString = itemJSON["date_published"] as? String let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let datePublished = formatter.date(from: datePublishedString!) let item = Item(id: id, url: urlString, title: title, contentHTML: contentHTML, datePublished: datePublished) items.append(item) } } catch { print("Error parsing feed JSON: \(error)") } return items } }
mit
5ce32a59ddaa97005f8d60c9147c1bc6
30.826923
125
0.494864
5.092308
false
false
false
false
emilstahl/swift
stdlib/public/SDK/Darwin/POSIXError.swift
14
8190
// FIXME: Only defining _POSIXError for Darwin at the moment. #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) /// Enumeration describing POSIX error codes. @objc public enum POSIXError : CInt { // FIXME: These are the values for Darwin. We need to get the Linux // values as well. case EPERM = 1 /* Operation not permitted */ case ENOENT = 2 /* No such file or directory */ case ESRCH = 3 /* No such process */ case EINTR = 4 /* Interrupted system call */ case EIO = 5 /* Input/output error */ case ENXIO = 6 /* Device not configured */ case E2BIG = 7 /* Argument list too long */ case ENOEXEC = 8 /* Exec format error */ case EBADF = 9 /* Bad file descriptor */ case ECHILD = 10 /* No child processes */ case EDEADLK = 11 /* Resource deadlock avoided */ /* 11 was EAGAIN */ case ENOMEM = 12 /* Cannot allocate memory */ case EACCES = 13 /* Permission denied */ case EFAULT = 14 /* Bad address */ case ENOTBLK = 15 /* Block device required */ case EBUSY = 16 /* Device / Resource busy */ case EEXIST = 17 /* File exists */ case EXDEV = 18 /* Cross-device link */ case ENODEV = 19 /* Operation not supported by device */ case ENOTDIR = 20 /* Not a directory */ case EISDIR = 21 /* Is a directory */ case EINVAL = 22 /* Invalid argument */ case ENFILE = 23 /* Too many open files in system */ case EMFILE = 24 /* Too many open files */ case ENOTTY = 25 /* Inappropriate ioctl for device */ case ETXTBSY = 26 /* Text file busy */ case EFBIG = 27 /* File too large */ case ENOSPC = 28 /* No space left on device */ case ESPIPE = 29 /* Illegal seek */ case EROFS = 30 /* Read-only file system */ case EMLINK = 31 /* Too many links */ case EPIPE = 32 /* Broken pipe */ /* math software */ case EDOM = 33 /* Numerical argument out of domain */ case ERANGE = 34 /* Result too large */ /* non-blocking and interrupt i/o */ case EAGAIN = 35 /* Resource temporarily unavailable */ public static var EWOULDBLOCK: POSIXError { return EAGAIN } /* Operation would block */ case EINPROGRESS = 36 /* Operation now in progress */ case EALREADY = 37 /* Operation already in progress */ /* ipc/network software -- argument errors */ case ENOTSOCK = 38 /* Socket operation on non-socket */ case EDESTADDRREQ = 39 /* Destination address required */ case EMSGSIZE = 40 /* Message too long */ case EPROTOTYPE = 41 /* Protocol wrong type for socket */ case ENOPROTOOPT = 42 /* Protocol not available */ case EPROTONOSUPPORT = 43 /* Protocol not supported */ case ESOCKTNOSUPPORT = 44 /* Socket type not supported */ case ENOTSUP = 45 /* Operation not supported */ case EPFNOSUPPORT = 46 /* Protocol family not supported */ case EAFNOSUPPORT = 47 /* Address family not supported by protocol family */ case EADDRINUSE = 48 /* Address already in use */ case EADDRNOTAVAIL = 49 /* Can't assign requested address */ /* ipc/network software -- operational errors */ case ENETDOWN = 50 /* Network is down */ case ENETUNREACH = 51 /* Network is unreachable */ case ENETRESET = 52 /* Network dropped connection on reset */ case ECONNABORTED = 53 /* Software caused connection abort */ case ECONNRESET = 54 /* Connection reset by peer */ case ENOBUFS = 55 /* No buffer space available */ case EISCONN = 56 /* Socket is already connected */ case ENOTCONN = 57 /* Socket is not connected */ case ESHUTDOWN = 58 /* Can't send after socket shutdown */ case ETOOMANYREFS = 59 /* Too many references: can't splice */ case ETIMEDOUT = 60 /* Operation timed out */ case ECONNREFUSED = 61 /* Connection refused */ case ELOOP = 62 /* Too many levels of symbolic links */ case ENAMETOOLONG = 63 /* File name too long */ case EHOSTDOWN = 64 /* Host is down */ case EHOSTUNREACH = 65 /* No route to host */ case ENOTEMPTY = 66 /* Directory not empty */ /* quotas & mush */ case EPROCLIM = 67 /* Too many processes */ case EUSERS = 68 /* Too many users */ case EDQUOT = 69 /* Disc quota exceeded */ /* Network File System */ case ESTALE = 70 /* Stale NFS file handle */ case EREMOTE = 71 /* Too many levels of remote in path */ case EBADRPC = 72 /* RPC struct is bad */ case ERPCMISMATCH = 73 /* RPC version wrong */ case EPROGUNAVAIL = 74 /* RPC prog. not avail */ case EPROGMISMATCH = 75 /* Program version wrong */ case EPROCUNAVAIL = 76 /* Bad procedure for program */ case ENOLCK = 77 /* No locks available */ case ENOSYS = 78 /* Function not implemented */ case EFTYPE = 79 /* Inappropriate file type or format */ case EAUTH = 80 /* Authentication error */ case ENEEDAUTH = 81 /* Need authenticator */ /* Intelligent device errors */ case EPWROFF = 82 /* Device power is off */ case EDEVERR = 83 /* Device error, e.g. paper out */ case EOVERFLOW = 84 /* Value too large to be stored in data type */ /* Program loading errors */ case EBADEXEC = 85 /* Bad executable */ case EBADARCH = 86 /* Bad CPU type in executable */ case ESHLIBVERS = 87 /* Shared library version mismatch */ case EBADMACHO = 88 /* Malformed Macho file */ case ECANCELED = 89 /* Operation canceled */ case EIDRM = 90 /* Identifier removed */ case ENOMSG = 91 /* No message of desired type */ case EILSEQ = 92 /* Illegal byte sequence */ case ENOATTR = 93 /* Attribute not found */ case EBADMSG = 94 /* Bad message */ case EMULTIHOP = 95 /* Reserved */ case ENODATA = 96 /* No message available on STREAM */ case ENOLINK = 97 /* Reserved */ case ENOSR = 98 /* No STREAM resources */ case ENOSTR = 99 /* Not a STREAM */ case EPROTO = 100 /* Protocol error */ case ETIME = 101 /* STREAM ioctl timeout */ case ENOPOLICY = 103 /* No such policy registered */ case ENOTRECOVERABLE = 104 /* State not recoverable */ case EOWNERDEAD = 105 /* Previous owner died */ case EQFULL = 106 /* Interface output queue is full */ public static var ELAST: POSIXError { return EQFULL } /* Must be equal largest errno */ // FIXME: EOPNOTSUPP has different values depending on __DARWIN_UNIX03 and // KERNEL. } #endif
apache-2.0
f73d277ae33281f03496309bb584b11d
55.09589
94
0.493529
5.233227
false
false
false
false
ben-ng/swift
stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
1
7240
//===--- StdlibCoreExtras.swift -------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftPrivate import SwiftPrivateLibcExtras #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif #if _runtime(_ObjC) import Foundation #endif // // These APIs don't really belong in a unit testing library, but they are // useful in tests, and stdlib does not have such facilities yet. // func findSubstring(_ string: String, _ substring: String) -> String.Index? { if substring.isEmpty { return string.startIndex } #if _runtime(_ObjC) return string.range(of: substring)?.lowerBound #else // FIXME(performance): This is a very non-optimal algorithm, with a worst // case of O((n-m)*m). When non-objc String has a match function that's better, // this should be removed in favor of using that. // Operate on unicode scalars rather than codeunits. let haystack = string.unicodeScalars let needle = substring.unicodeScalars for matchStartIndex in haystack.indices { var matchIndex = matchStartIndex var needleIndex = needle.startIndex while true { if needleIndex == needle.endIndex { // if we hit the end of the search string, we found the needle return matchStartIndex.samePosition(in: string) } if matchIndex == haystack.endIndex { // if we hit the end of the string before finding the end of the needle, // we aren't going to find the needle after that. return nil } if needle[needleIndex] == haystack[matchIndex] { // keep advancing through both the string and search string on match matchIndex = haystack.index(after: matchIndex) needleIndex = haystack.index(after: needleIndex) } else { // no match, go back to finding a starting match in the string. break } } } return nil #endif } public func createTemporaryFile( _ fileNamePrefix: String, _ fileNameSuffix: String, _ contents: String ) -> String { #if _runtime(_ObjC) let tempDir: NSString = NSTemporaryDirectory() as NSString var fileName = tempDir.appendingPathComponent( fileNamePrefix + "XXXXXX" + fileNameSuffix) #else var fileName = fileNamePrefix + "XXXXXX" + fileNameSuffix #endif let fd = _stdlib_mkstemps( &fileName, CInt(fileNameSuffix.utf8.count)) if fd < 0 { fatalError("mkstemps() returned an error") } var stream = _FDOutputStream(fd: fd) stream.write(contents) if close(fd) != 0 { fatalError("close() return an error") } return fileName } public final class Box<T> { public init(_ value: T) { self.value = value } public var value: T } infix operator <=> public func <=> <T: Comparable>(lhs: T, rhs: T) -> ExpectedComparisonResult { return lhs < rhs ? .lt : lhs > rhs ? .gt : .eq } public struct TypeIdentifier : Hashable, Comparable { public init(_ value: Any.Type) { self.value = value } public var hashValue: Int { return objectID.hashValue } public var value: Any.Type internal var objectID : ObjectIdentifier { return ObjectIdentifier(value) } } public func < (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID < rhs.objectID } public func == (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID == rhs.objectID } extension TypeIdentifier : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return String(describing: value) } public var debugDescription: String { return "TypeIdentifier(\(description))" } } enum FormNextPermutationResult { case success case formedFirstPermutation } extension MutableCollection where Self : BidirectionalCollection, Iterator.Element : Comparable { mutating func _reverseSubrange(_ subrange: Range<Index>) { if subrange.isEmpty { return } var f = subrange.lowerBound var l = index(before: subrange.upperBound) while f < l { swap(&self[f], &self[l]) formIndex(after: &f) formIndex(before: &l) } } mutating func formNextPermutation() -> FormNextPermutationResult { if isEmpty { // There are 0 elements, only one permutation is possible. return .formedFirstPermutation } do { var i = startIndex formIndex(after: &i) if i == endIndex { // There is only element, only one permutation is possible. return .formedFirstPermutation } } var i = endIndex formIndex(before: &i) var beforeI = i formIndex(before: &beforeI) var elementAtI = self[i] var elementAtBeforeI = self[beforeI] while true { if elementAtBeforeI < elementAtI { // Elements at `i..<endIndex` are in non-increasing order. To form the // next permutation in lexicographical order we need to replace // `self[i-1]` with the next larger element found in the tail, and // reverse the tail. For example: // // i-1 i endIndex // V V V // 6 2 8 7 4 1 [ ] // Input. // 6 (4) 8 7 (2) 1 [ ] // Exchanged self[i-1] with the // ^--------^ // next larger element // // from the tail. // 6 4 (1)(2)(7)(8)[ ] // Reversed the tail. // <--------> var j = endIndex repeat { formIndex(before: &j) } while !(elementAtBeforeI < self[j]) swap(&self[beforeI], &self[j]) _reverseSubrange(i..<endIndex) return .success } if beforeI == startIndex { // All elements are in non-increasing order. Reverse to form the first // permutation, where all elements are sorted (in non-increasing order). reverse() return .formedFirstPermutation } i = beforeI formIndex(before: &beforeI) elementAtI = elementAtBeforeI elementAtBeforeI = self[beforeI] } } } /// Generate all permutations. public func forAllPermutations(_ size: Int, _ body: ([Int]) -> Void) { var data = Array(0..<size) repeat { body(data) } while data.formNextPermutation() != .formedFirstPermutation } /// Generate all permutations. public func forAllPermutations<S : Sequence>( _ sequence: S, _ body: ([S.Iterator.Element]) -> Void ) { let data = Array(sequence) forAllPermutations(data.count) { (indices: [Int]) in body(indices.map { data[$0] }) return () } } public func cartesianProduct<C1 : Collection, C2 : Collection>( _ c1: C1, _ c2: C2 ) -> [(C1.Iterator.Element, C2.Iterator.Element)] { var result: [(C1.Iterator.Element, C2.Iterator.Element)] = [] for e1 in c1 { for e2 in c2 { result.append((e1, e2)) } } return result }
apache-2.0
d2262abaad4effa156b4dea4e96d7842
28.311741
81
0.632459
4.092708
false
false
false
false
fellipecaetano/Redux.swift
Tests/CounterStore.swift
1
1751
import Foundation import Redux class CounterStore: StoreProtocol { typealias E = CounterState private(set) var actionHistory: [Action] = [] fileprivate let store: Store<CounterState> init (middleware: Middleware<CounterState>...) { store = Store<CounterState>( initialState: CounterState(), reducer: { state, action in switch action { case let action as IncrementAction: return CounterState(counter: state.counter + action.amount) case let action as DecrementAction: return CounterState(counter: state.counter - action.amount) default: return state } }, middleware: middleware ) } func subscribe(_ subscription: @escaping (CounterState) -> Void) -> (() -> Void) { return store.subscribe(subscription) } func dispatch(_ action: Action) { actionHistory.append(action) return store.dispatch(action) } var state: CounterState { return store.state } } struct CounterState { let counter: Int init (counter: Int = 0) { self.counter = counter } } struct IncrementAction: Action, Equatable { let amount: Int } struct DecrementAction: Action, Equatable { let amount: Int } struct MultipleIncrementsCommand: CompleteableCommand { typealias State = CounterState let amount: Int let times: Int func run(state: () -> CounterState, dispatch: @escaping (Action) -> Void, completion: (() -> Void)?) { for _ in (0..<times) { dispatch(IncrementAction(amount: amount)) } completion?() } }
mit
7b9ca2b18fa67dea3f73e3523749ae54
22.662162
106
0.588806
4.918539
false
false
false
false
tavultesoft/keymanweb
ios/keyman/Keyman/Keyman/Classes/LogoBackgroundView/KMUnderscoreView.swift
1
923
// // KMUnderscoreView.swift // Keyman // // Created by Jacob Bullock on 4/26/18. // Copyright © 2018 SIL International. All rights reserved. // import Foundation import UIKit class KMUnderscoreView: KMView { override func draw(_ rect: CGRect) { // percentage based widths for the color bar portion of the logo let widths: [CGFloat] = [0.6, 0.25, 0.15] let colors: [UIColor] = [ UIColor.keymanOrange, UIColor.keymanRed, UIColor.keymanBlue] var x: CGFloat = 0 for i in 0..<(widths.count) { let w: CGFloat = rect.width * widths[i] let drect = CGRect(x: x, y: 0, width: w, height: rect.height) let bpath: UIBezierPath = UIBezierPath(rect: drect) let color = colors[i] color.set() bpath.fill() x += w } } }
apache-2.0
98ef86cb19d5d5200c81266710845df6
26.117647
73
0.537961
3.87395
false
false
false
false
googlecast/CastVideos-ios
CastVideos-swift/Classes/MediaTableViewController.swift
1
17189
// Copyright 2022 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import GoogleCast import UIKit let kPrefMediaListURL: String = "media_list_url" @objc(MediaTableViewController) class MediaTableViewController: UITableViewController, GCKSessionManagerListener, MediaListModelDelegate, GCKRequestDelegate { private var sessionManager: GCKSessionManager! private var rootTitleView: UIImageView! private var titleView: UIView! private var mediaListURL: URL! private var queueButton: UIBarButtonItem! private var actionSheet: ActionSheet! private var selectedItem: MediaItem! private var queueAdded: Bool = false private var castButton: GCKUICastButton! private var credentials: String? = nil /** The media to be displayed. */ var mediaList: MediaListModel? var rootItem: MediaItem? { didSet { title = rootItem?.title tableView.reloadData() } } required init?(coder: NSCoder) { super.init(coder: coder) sessionManager = GCKCastContext.sharedInstance().sessionManager } override func viewDidLoad() { print("MediaTableViewController - viewDidLoad") super.viewDidLoad() sessionManager.add(self) titleView = navigationItem.titleView rootTitleView = UIImageView(image: UIImage(named: "logo_castvideos.png")) NotificationCenter.default.addObserver(self, selector: #selector(loadMediaList), name: UserDefaults.didChangeNotification, object: nil) if rootItem == nil { loadMediaList() } castButton = GCKUICastButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(24), height: CGFloat(24))) // Overwrite the UIAppearance theme in the AppDelegate. castButton.tintColor = UIColor.white navigationItem.rightBarButtonItem = UIBarButtonItem(customView: castButton) queueButton = UIBarButtonItem(image: UIImage(named: "playlist_white.png"), style: .plain, target: self, action: #selector(didTapQueueButton)) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Creds", style: .plain, target: self, action: #selector(toggleLaunchCreds)) tableView.separatorColor = UIColor.clear NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil) UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(castDeviceDidChange), name: NSNotification.Name.gckCastStateDidChange, object: GCKCastContext.sharedInstance()) setLaunchCreds() } @objc func toggleLaunchCreds(_: Any){ if (credentials == nil) { credentials = "{\"userId\":\"id123\"}" } else { credentials = nil } Toast.displayMessage("Launch Credentials: "+(credentials ?? "Null"), for: 3, in: appDelegate?.window) print("Credentials set: "+(credentials ?? "Null")) setLaunchCreds() } @objc func castDeviceDidChange(_: Notification) { if GCKCastContext.sharedInstance().castState != .noDevicesAvailable { // You can present the instructions on how to use Google Cast on // the first time the user uses you app GCKCastContext.sharedInstance().presentCastInstructionsViewControllerOnce(with: castButton) } } @objc func deviceOrientationDidChange(_: Notification) { tableView.reloadData() } func setQueueButtonVisible(_ visible: Bool) { if visible, !queueAdded { var barItems = navigationItem.rightBarButtonItems barItems?.append(queueButton) navigationItem.rightBarButtonItems = barItems queueAdded = true } else if !visible, queueAdded { var barItems = navigationItem.rightBarButtonItems let index = barItems?.firstIndex(of: queueButton) ?? -1 barItems?.remove(at: index) navigationItem.rightBarButtonItems = barItems queueAdded = false } } @objc func didTapQueueButton(_: Any) { performSegue(withIdentifier: "MediaQueueSegue", sender: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("viewWillAppear - Table view") navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.setBackgroundImage(nil, for: .default) navigationController?.navigationBar.shadowImage = nil navigationController?.interactivePopGestureRecognizer?.isEnabled = true // Fix navigationBar color for iOS 15+ if #available(iOS 15.0, *) { let navigationBarAppearance = UINavigationBarAppearance() navigationBarAppearance.backgroundColor = navigationController?.navigationBar.barTintColor navigationController?.navigationBar.standardAppearance = navigationBarAppearance navigationController?.navigationBar.scrollEdgeAppearance = navigationBarAppearance } if rootItem?.parent == nil { // If this is the root group, show stylized application title in the title view. navigationItem.titleView = rootTitleView } else { // Otherwise show the title of the group in the title view. navigationItem.titleView = titleView title = rootItem?.title } appDelegate?.isCastControlBarsEnabled = true } // MARK: - Table View override func numberOfSections(in _: UITableView) -> Int { return 1 } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { if let rootItem = rootItem { return rootItem.children.count } else { return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MediaCell", for: indexPath) guard let item = rootItem?.children[indexPath.row] as? MediaItem else { return cell } var detail: String? if let mediaInfo = item.mediaInfo { detail = mediaInfo.metadata?.string(forKey: kGCKMetadataKeyStudio) if detail == nil { detail = mediaInfo.metadata?.string(forKey: kGCKMetadataKeyArtist) } } if let mediaTitle = (cell.viewWithTag(1) as? UILabel) { let titleText = item.title let ownerText = detail let text = "\(titleText ?? "")\n\(ownerText ?? "")" let attribs = [NSAttributedString.Key.foregroundColor: mediaTitle.textColor as Any, NSAttributedString.Key.font: mediaTitle.font as Any] as [NSAttributedString.Key: Any] let attributedText = NSMutableAttributedString(string: text, attributes: attribs) let titleColor: UIColor! let subtitleColor: UIColor! if #available(iOS 13.0, *) { titleColor = UIColor.label subtitleColor = UIColor.secondaryLabel } else { titleColor = UIColor.black subtitleColor = UIColor.lightGray } let titleTextRange = NSRange(location: 0, length: (titleText?.count ?? 0)) attributedText.setAttributes([NSAttributedString.Key.foregroundColor: titleColor as Any], range: titleTextRange) let ownerTextRange = NSRange(location: (titleText?.count ?? 0) + 1, length: (ownerText?.count ?? 0)) attributedText.setAttributes([NSAttributedString.Key.foregroundColor: subtitleColor as Any, NSAttributedString.Key.font: UIFont.systemFont(ofSize: CGFloat(12))], range: ownerTextRange) mediaTitle.attributedText = attributedText } let mediaOwner = (cell.viewWithTag(2) as? UILabel) mediaOwner?.isHidden = true if item.mediaInfo != nil { cell.accessoryType = .none } else { cell.accessoryType = .disclosureIndicator } if let imageView = (cell.contentView.viewWithTag(3) as? UIImageView), let imageURL = item.imageURL { GCKCastContext.sharedInstance().imageCache?.fetchImage(for: imageURL, completion: { (_ image: UIImage?) -> Void in imageView.image = image cell.setNeedsLayout() }) } let addButton: UIButton? = (cell.viewWithTag(4) as? UIButton) let hasConnectedCastSession: Bool = sessionManager.hasConnectedCastSession() if hasConnectedCastSession { addButton?.isHidden = false addButton?.addTarget(self, action: #selector(playButtonClicked), for: .touchDown) } else { addButton?.isHidden = true } return cell } @IBAction func playButtonClicked(_ sender: Any) { guard let tableViewCell = (sender as AnyObject).superview??.superview as? UITableViewCell else { return } guard let indexPathForCell = tableView.indexPath(for: tableViewCell) else { return } selectedItem = (rootItem?.children[indexPathForCell.row] as? MediaItem) let hasConnectedCastSession: Bool = sessionManager.hasConnectedCastSession() if selectedItem.mediaInfo != nil, hasConnectedCastSession { // Display an popover to allow the user to add to queue or play // immediately. if actionSheet == nil { actionSheet = ActionSheet(title: "Play Item", message: "Select an action", cancelButtonText: "Cancel") actionSheet.addAction(withTitle: "Play Now", target: self, selector: #selector(playSelectedItemRemotely)) actionSheet.addAction(withTitle: "Add to Queue", target: self, selector: #selector(enqueueSelectedItemRemotely)) } actionSheet.present(in: self, sourceView: tableViewCell) } } override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) { if let item = rootItem?.children[indexPath.row] as? MediaItem, item.mediaInfo != nil { performSegue(withIdentifier: "mediaDetails", sender: self) } } override func prepare(for segue: UIStoryboardSegue, sender _: Any?) { print("prepareForSegue") if segue.identifier == "mediaDetails" { let viewController: MediaViewController? = (segue.destination as? MediaViewController) if let mediaInfo = getSelectedItem()?.mediaInfo { viewController?.mediaInfo = mediaInfo } } } @objc func playSelectedItemRemotely() { loadSelectedItem(byAppending: false) appDelegate?.isCastControlBarsEnabled = false GCKCastContext.sharedInstance().presentDefaultExpandedMediaControls() } @objc func enqueueSelectedItemRemotely() { loadSelectedItem(byAppending: true) // selectedItem = [self getSelectedItem]; let message = "Added \"\(selectedItem.mediaInfo?.metadata?.string(forKey: kGCKMetadataKeyTitle) ?? "")\" to queue." Toast.displayMessage(message, for: 3, in: appDelegate?.window) setQueueButtonVisible(true) } /** * Loads the currently selected item in the current cast media session. * @param appending If YES, the item is appended to the current queue if there * is one. If NO, or if * there is no queue, a new queue containing only the selected item is created. */ func loadSelectedItem(byAppending appending: Bool) { print("enqueue item \(String(describing: selectedItem.mediaInfo))") if let remoteMediaClient = sessionManager.currentCastSession?.remoteMediaClient { let mediaQueueItemBuilder = GCKMediaQueueItemBuilder() mediaQueueItemBuilder.mediaInformation = selectedItem.mediaInfo mediaQueueItemBuilder.autoplay = true mediaQueueItemBuilder.preloadTime = TimeInterval(UserDefaults.standard.integer(forKey: kPrefPreloadTime)) let mediaQueueItem = mediaQueueItemBuilder.build() if appending { let request = remoteMediaClient.queueInsert(mediaQueueItem, beforeItemWithID: kGCKMediaQueueInvalidItemID) request.delegate = self } else { let queueDataBuilder = GCKMediaQueueDataBuilder(queueType: .generic) queueDataBuilder.items = [mediaQueueItem] queueDataBuilder.repeatMode = remoteMediaClient.mediaStatus?.queueRepeatMode ?? .off let mediaLoadRequestDataBuilder = GCKMediaLoadRequestDataBuilder() mediaLoadRequestDataBuilder.queueData = queueDataBuilder.build() mediaLoadRequestDataBuilder.credentials = credentials let request = remoteMediaClient.loadMedia(with: mediaLoadRequestDataBuilder.build()) request.delegate = self } } } func getSelectedItem() -> MediaItem? { guard let indexPath = tableView.indexPathForSelectedRow else { return nil } print("selected row is \(indexPath)") return (rootItem?.children[(indexPath.row)] as? MediaItem) } // MARK: - MediaListModelDelegate func mediaListModelDidLoad(_: MediaListModel) { rootItem = mediaList?.rootItem title = mediaList?.title tableView.reloadData() } func mediaListModel(_: MediaListModel, didFailToLoadWithError _: Error?) { let errorMessage: String = "Unable to load the media list from\n\(mediaListURL.absoluteString)." let alertController = UIAlertController(title: "Cast Error", message: errorMessage, preferredStyle: UIAlertController.Style.alert) let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) alertController.addAction(action) present(alertController, animated: true, completion: nil) } @objc func loadMediaList() { // Look up the media list URL. let userDefaults = UserDefaults.standard guard let urlKey = userDefaults.string(forKey: kPrefMediaListURL) else { return } guard let urlText = userDefaults.string(forKey: urlKey) else { return } let _mediaListURL = URL(string: urlText) if mediaListURL == _mediaListURL { // The URL hasn't changed; do nothing. return } mediaListURL = _mediaListURL print("Media list URL: \(String(describing: mediaListURL))") // Asynchronously load the media json. mediaList = MediaListModel() mediaList?.delegate = self mediaList?.load(from: mediaListURL) } // MARK: - GCKSessionManagerListener func sessionManager(_: GCKSessionManager, didStart session: GCKSession) { print("MediaViewController: sessionManager didStartSession \(session)") setQueueButtonVisible(true) tableView.reloadData() } func sessionManager(_: GCKSessionManager, didResumeSession session: GCKSession) { print("MediaViewController: sessionManager didResumeSession \(session)") setQueueButtonVisible(true) tableView.reloadData() } func sessionManager(_: GCKSessionManager, didEnd _: GCKSession, withError error: Error?) { print("session ended with error: \(String(describing: error))") let message = "The Casting session has ended.\n\(String(describing: error))" if let window = appDelegate?.window { Toast.displayMessage(message, for: 3, in: window) } setQueueButtonVisible(false) tableView.reloadData() } func sessionManager(_: GCKSessionManager, didFailToStartSessionWithError error: Error?) { if let error = error { showAlert(withTitle: "Failed to start a session", message: error.localizedDescription) } setQueueButtonVisible(false) tableView.reloadData() } func sessionManager(_: GCKSessionManager, didFailToResumeSession _: GCKSession, withError _: Error?) { if let window = UIApplication.shared.delegate?.window { Toast.displayMessage("The Casting session could not be resumed.", for: 3, in: window) } setQueueButtonVisible(false) tableView.reloadData() } func showAlert(withTitle title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) alertController.addAction(action) present(alertController, animated: true, completion: nil) } // MARK: - GCKRequestDelegate func requestDidComplete(_ request: GCKRequest) { print("request \(Int(request.requestID)) completed") } func request(_ request: GCKRequest, didFailWithError error: GCKError) { print("request \(Int(request.requestID)) failed with error \(error)") } func setLaunchCreds() { GCKCastContext.sharedInstance() .setLaunch(GCKCredentialsData(credentials: credentials)) } }
apache-2.0
d848dbeac6ff0eb03705b1169468042a
40.519324
128
0.692187
5.175851
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/ToolKit/JSToolKit/JSUIKit/UIImage+Extension.swift
1
5486
// // UIImage+Extension.swift // BeeFun // // Created by WengHengcong on 2017/3/29. // Copyright © 2017年 JungleSong. All rights reserved. // import UIKit public enum JSImageFormat { case unknown, png, jpeg, gif } extension UIImage { /// EZSE: Returns base64 string var base64: String { return UIImageJPEGRepresentation(self, 1.0)!.base64EncodedString() } /// EZSE: Returns compressed image to rate from 0 to 1 /// 以JPEG压缩图片 /// /// - Parameter rate: 压缩比 /// - Returns: 返回图片时的Data public func compressImage(rate: CGFloat) -> Data? { return UIImageJPEGRepresentation(self, rate) } /// EZSE: Returns Image size in Bytes /// 返回图片的大小 /// /// - Returns: byte public func getSizeAsBytes() -> Int { return UIImageJPEGRepresentation(self, 1)?.count ?? 0 } /// 返回图片的大小 /// /// - Returns: kb public func getSizeAsKilobytes() -> Int { let sizeAsBytes = getSizeAsBytes() return sizeAsBytes != 0 ? sizeAsBytes / 1024 : 0 } /// EZSE: scales image /// 缩放图片 /// /// - Parameters: /// - image: 需要缩放的图片 /// - w: 宽度 /// - h: 高度 /// - Returns: 压缩后图片 public class func scaleTo(image: UIImage, w: CGFloat, h: CGFloat) -> UIImage { let newSize = CGSize(width: w, height: h) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } /// EZSE Returns resized image with width. Might return low quality /// 重置图片大小 /// /// - Parameter width: 宽度 /// - Returns: <#return value description#> public func resizeWithWidth(_ width: CGFloat) -> UIImage { let aspectSize = CGSize (width: width, height: aspectHeightForWidth(width)) UIGraphicsBeginImageContext(aspectSize) self.draw(in: CGRect(origin: CGPoint.zero, size: aspectSize)) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } /// 重置图片大小 /// /// - Parameter height: 高度 /// - Returns: <#return value description#> public func resizeWithHeight(_ height: CGFloat) -> UIImage { let aspectSize = CGSize (width: aspectWidthForHeight(height), height: height) UIGraphicsBeginImageContext(aspectSize) self.draw(in: CGRect(origin: CGPoint.zero, size: aspectSize)) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } /// 自适应高度 /// /// - Parameter width: 宽度 /// - Returns: <#return value description#> public func aspectHeightForWidth(_ width: CGFloat) -> CGFloat { return (width * self.size.height) / self.size.width } /// 自适应宽度 /// /// - Parameter height: 高度 /// - Returns: <#return value description#> public func aspectWidthForHeight(_ height: CGFloat) -> CGFloat { return (height * self.size.width) / self.size.height } /// 截图 /// /// - Parameter bound: 截图区域 /// - Returns: <#return value description#> public func croppedImage(_ bound: CGRect) -> UIImage? { guard self.size.width > bound.origin.x else { print("JSUI: Your cropping X coordinate is larger than the image width") return nil } guard self.size.height > bound.origin.y else { print("JSUI: Your cropping Y coordinate is larger than the image height") return nil } let scaledBounds: CGRect = CGRect(x: bound.x * self.scale, y: bound.y * self.scale, width: bound.w * self.scale, height: bound.h * self.scale) let imageRef = self.cgImage?.cropping(to: scaledBounds) let croppedImage: UIImage = UIImage(cgImage: imageRef!, scale: self.scale, orientation: UIImageOrientation.up) return croppedImage } ///根据颜色创建图片 public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } ///根据URL加载新图片 public convenience init?(urlString: String) { guard let url = URL(string: urlString) else { self.init(data: Data()) return } guard let data = try? Data(contentsOf: url) else { print("EZSE: No image in URL \(urlString)") self.init(data: Data()) return } self.init(data: data) } /// 空图片 /// /// - Returns: <#return value description#> public class func blankImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0.0) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
f350667dcbbb1b5440592109eacd0f15
30.052941
150
0.615268
4.539123
false
false
false
false