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
bluesnap/bluesnap-ios
BluesnapSDKExample/BluesnapSDKExampleUITests/BSUITestsUtils.swift
1
18312
// // BSUITestsUtils.swift // BluesnapSDKExampleUITests // // Created by Sivani on 06/02/2019. // Copyright © 2019 Bluesnap. All rights reserved. // import Foundation import XCTest import BluesnapSDK class BSUITestUtils { static func checkRetrieveVaultedShopperResponse(responseBody: Data, sdkRequest: BSSdkRequest, cardStored: Bool = false, expectedCreditCardInfo: [(String,String,String,String)], shippingSameAsBilling: Bool = false, chosenPaymentMethod: String? = nil, cardIndex: Int? = nil, isSubscription: Bool = false) -> BSErrors? { var resultError: BSErrors? = nil do { // Parse the result JSOn object if let jsonData = try JSONSerialization.jsonObject(with: responseBody, options: .allowFragments) as? [String: AnyObject] { if sdkRequest.shopperConfiguration.withEmail && !isSubscription { // second part is temporary till server bug is fixed checkFieldContent(expectedValue: (sdkRequest.shopperConfiguration.billingDetails?.email!)!, actualValue: jsonData["email"] as! String, fieldName: "email") } if let paymentSources = jsonData["paymentSources"] as? [String: AnyObject] { if let creditCardInfo = paymentSources["creditCardInfo"] as? [[String: Any]] { if (!cardStored){ NSLog("Error on Retrieve vaulted shopper- 'creditCardInfo' exists when shopper selected DO NOT store") resultError = .unknown } var i = 0 for item in creditCardInfo { if let creditCard = item["creditCard"] as? [String: AnyObject], let billingContactInfo = item["billingContactInfo"] as? [String: AnyObject] { //TODO: integrate this for multiple cc // let cardLastFourDigits = creditCard["cardLastFourDigits"] as? String let j = creditCard["cardType"] as! String == "VISA" ? 0 : 1 if (chosenPaymentMethod == nil || (chosenPaymentMethod != nil && j == cardIndex)) { //check info only in chosen card in shopper config checkShopperInfo(sdkRequest: sdkRequest, resultData: billingContactInfo, isBilling: true) } checkCreditCardInfo(expectedCreditCardInfo: expectedCreditCardInfo[j], resultData: creditCard) } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'creditCard' or 'billingContactInfo'") resultError = .unknown } i += 1 } XCTAssertEqual(i, Mirror(reflecting: expectedCreditCardInfo).children.count, "Error: worng number of credit cards in server") } else if (cardStored) { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'creditCardInfo'") resultError = .unknown } } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'paymentSources'") resultError = .unknown } if sdkRequest.shopperConfiguration.withShipping && !isSubscription { // second part is temporary till server bug is fixed if let shippingContactInfo = jsonData["shippingContactInfo"] as? [String: AnyObject] { checkShopperInfo(sdkRequest: sdkRequest, resultData: shippingContactInfo, isBilling: shippingSameAsBilling) } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'shippingContactInfo'") resultError = .unknown } } // choose payment flow if let chosenPaymentMethod_ = chosenPaymentMethod { if let chosenPaymentMethodInfo = jsonData["chosenPaymentMethod"] as? [String: AnyObject] { checkFieldContent(expectedValue: chosenPaymentMethod_, actualValue: chosenPaymentMethodInfo["chosenPaymentMethodType"] as! String, fieldName: "chosenPaymentMethodType") if let cardIndex_ = cardIndex { if let creditCard = chosenPaymentMethodInfo["creditCard"] as? [String: AnyObject] { //TODO: integrate this for multiple cc checkCreditCardInfo(expectedCreditCardInfo: expectedCreditCardInfo[cardIndex_], resultData: creditCard) } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'creditCard' or 'billingContactInfo'") resultError = .unknown } } } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'chosenPaymentMethod'") resultError = .unknown } } // all other flows that includes payment- regular checkout and create payment else{ //TODO: change this to support other payment method if let lastPaymentInfo = jsonData["lastPaymentInfo"] as? [String: AnyObject] { checkFieldContent(expectedValue: "CC", actualValue: lastPaymentInfo["paymentMethod"] as! String, fieldName: "paymentMethod") } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'lastPaymentInfo'") resultError = .unknown } } } else { NSLog("Error parsing BS result on Retrieve vaulted shopper") resultError = .unknown } } catch let error as NSError { NSLog("Error parsing BS result on Retrieve vaulted shopper: \(error.localizedDescription)") resultError = .unknown } return resultError } static func checkCreateSubscriptionResponse(responseBody: Data, sdkRequest: BSSdkRequest, expectedCreditCardInfo: (String,String,String,String), shippingSameAsBilling: Bool = false) -> BSErrors? { var resultError: BSErrors? = nil do { // Parse the result JSOn object if let jsonData = try JSONSerialization.jsonObject(with: responseBody, options: .allowFragments) as? [String: AnyObject] { checkFieldContent(expectedValue: "ACTIVE", actualValue: jsonData["status"] as! String, fieldName: "status") if let paymentSources = jsonData["paymentSource"] as? [String: AnyObject] { if let creditCardInfo = paymentSources["creditCardInfo"] as? [String: Any] { if let creditCard = creditCardInfo["creditCard"] as? [String: AnyObject], let billingContactInfo = creditCardInfo["billingContactInfo"] as? [String: AnyObject] { checkShopperInfo(sdkRequest: sdkRequest, resultData: billingContactInfo, isBilling: true) checkCreditCardInfo(expectedCreditCardInfo: expectedCreditCardInfo, resultData: creditCard) } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'creditCard' or 'billingContactInfo'") resultError = .unknown } } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'creditCardInfo'") resultError = .unknown } } else { NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'paymentSource'") resultError = .unknown } // add this when the server bug is fixed // if sdkRequest.shopperConfiguration.withShipping { // if let shippingContactInfo = jsonData["shippingContactInfo"] as? [String: AnyObject] { // checkShopperInfo(sdkRequest: sdkRequest, resultData: shippingContactInfo, isBilling: shippingSameAsBilling) // } else { // NSLog("Error parsing BS result on Retrieve vaulted shopper- Missing 'shippingContactInfo'") // resultError = .unknown // } // } } else { NSLog("Error parsing BS result on Retrieve vaulted shopper") resultError = .unknown } } catch let error as NSError { NSLog("Error parsing BS result on Retrieve vaulted shopper: \(error.localizedDescription)") resultError = .unknown } return resultError } static func checkCreditCardInfo(expectedCreditCardInfo: (String,String,String,String), resultData: [String: AnyObject]) { checkFieldContent(expectedValue: expectedCreditCardInfo.0 , actualValue: resultData["cardLastFourDigits"] as! String, fieldName: "cardLastFourDigits") checkFieldContent(expectedValue: expectedCreditCardInfo.1, actualValue: resultData["cardType"] as! String, fieldName: "cardType") checkFieldContent(expectedValue: expectedCreditCardInfo.2, actualValue: resultData["expirationMonth"] as! String, fieldName: "expirationMonth") checkFieldContent(expectedValue: expectedCreditCardInfo.3, actualValue: resultData["expirationYear"] as! String, fieldName: "expirationYear") } static func checkShopperInfo(sdkRequest: BSSdkRequest, resultData: [String: AnyObject], isBilling: Bool) { // let address = "address1" let fullInfo = (isBilling && sdkRequest.shopperConfiguration.fullBilling) || !isBilling let shopperInfo = isBilling ? sdkRequest.shopperConfiguration.billingDetails! : sdkRequest.shopperConfiguration.shippingDetails! let country = shopperInfo.country! let (firstName, lastName) = shopperInfo.getSplitName()! checkFieldContent(expectedValue: firstName, actualValue: resultData["firstName"] as! String, fieldName: "firstName") checkFieldContent(expectedValue: lastName, actualValue: resultData["lastName"] as! String, fieldName: "lastName") checkFieldContent(expectedValue: country.lowercased(), actualValue: resultData["country"] as! String, fieldName: "country") if (checkCountryHasZip(country: country)){ checkFieldContent(expectedValue: shopperInfo.zip!, actualValue: resultData["zip"] as! String, fieldName: "zip") } if (fullInfo){ //full billing or shipping if (checkCountryHasState(country: country)){ checkFieldContent(expectedValue: shopperInfo.state!, actualValue: resultData["state"] as! String, fieldName: "state") } checkFieldContent(expectedValue: shopperInfo.city!, actualValue: resultData["city"] as! String, fieldName: "city") checkFieldContent(expectedValue: shopperInfo.address!, actualValue: resultData["address1"] as! String, fieldName: "address") } } static func checkFieldContent(expectedValue: String, actualValue: String, fieldName: String) { XCTAssertEqual(expectedValue, actualValue, "Field \(fieldName) was not saved correctly in DataBase") } static func checkCountryHasState(country: String) -> Bool { var countryHasState = false if country == "US" || country == "CA" || country == "BR" { countryHasState = true } return countryHasState } static func checkCountryHasZip(country: String) -> Bool { let countryHasZip = !BSCountryManager.getInstance().countryHasNoZip(countryCode: country) return countryHasZip } static func getPayButtonText(sdkRequest: BSSdkRequest, country: String?, state: String?, subscriptionHasPriceDetails: Bool? = nil) -> String{ var amount: Double = sdkRequest.priceDetails.amount.doubleValue var payString: String if let subscriptionHasPriceDetails = subscriptionHasPriceDetails{ // Subscription flow payString = "Subscribe" if (!subscriptionHasPriceDetails){ // Subscription flow doesn't have amount return payString } } else { // regular flow payString = "Pay" } if let countryCode = country, let stateCode = state{ amount = calcTaxFromCuntryAndState(countryCode: countryCode, stateCode: stateCode, purchaseAmount: sdkRequest.priceDetails.amount.doubleValue) } let result = "\(payString) \(sdkRequest.priceDetails.currency == "USD" ? "$" : sdkRequest.priceDetails.currency ?? "USD") \(amount)" return result } static func calcTaxFromCuntryAndState(countryCode: String, stateCode: String, purchaseAmount: Double) -> Double { var taxPrecent = 0.0 if (countryCode == "US"){ taxPrecent = 0.05 if (stateCode == "NY"){ taxPrecent = 0.08 } } else if (countryCode == "CA"){ taxPrecent = 0.01 } let includeTaxAmount = purchaseAmount * (1+taxPrecent) return includeTaxAmount } static func checkAPayButton(app: XCUIApplication, buttonId: String, expectedPayText: String) { let payButton = app.buttons[buttonId] XCTAssertTrue(payButton.exists, "\(buttonId) is not displayed") let payButtonText = payButton.label // XCTAssert(expectedPayText == payButtonText) XCTAssert(payButtonText.contains(expectedPayText), "Pay Button doesn't display the correct text. expected text: \(expectedPayText), actual text: \(payButtonText)") } static func pressBackButton(app: XCUIApplication) { app.navigationBars.buttons.element(boundBy: 0).tap() } static func getVisaCard() -> [String: String] { return ["ccn": "4111111111111111", "exp": "10/2020", "cvv": "111", "ccType": "VISA", "last4Digits": "1111", "issuingCountry": "US"] } static func getMasterCard() -> [String: String] { return ["ccn": "5555555555555557", "exp": "11/2021", "cvv": "123", "ccType": "MASTERCARD", "last4Digits": "5557", "issuingCountry": "BR"] } static func getDummyBillingDetails(countryCode: String? = "CA", stateCode: String? = "ON") -> BSBillingAddressDetails { let billingDetails = BSBillingAddressDetails(email: "[email protected]", name: "Shevie Chen", address: "58 somestreet", city : "somecity", zip : "4282300", country : countryCode, state : stateCode) return billingDetails } static func getDummyShippingDetails(countryCode: String? = "CA", stateCode: String? = "ON") -> BSShippingAddressDetails { let shippingDetails = BSShippingAddressDetails(name: "Funny Brice", address: "77 Rambla street", city : "Barcelona", zip : "4815", country : countryCode, state : stateCode) return shippingDetails } static func getDummyEditBillingDetails(countryCode: String? = "US", stateCode: String? = "NY") -> BSBillingAddressDetails { let billingDetails = BSBillingAddressDetails(email: "[email protected]", name: "La Fleur", address: "555 Broadway street", city : "New York", zip : "3abc 324a", country : countryCode, state : stateCode) return billingDetails } static func getDummyEditShippingDetails(countryCode: String? = "CA", stateCode: String? = "ON") -> BSShippingAddressDetails { let shippingDetails = BSShippingAddressDetails(name: "Janet Weiss", address: "75 some street", city : "Denton", zip : "162342", country : countryCode, state : stateCode) return shippingDetails } static func getValidVisaCreditCardNumber()->String { return "4111 1111 1111 1111" } static func getValidVisaCreditCardNumberWithoutSpaces()->String { return "4111111111111111" } static func getValidVisaLast4Digits()->String { return "1111" } static func getValidExpDate()->String { return "1126" } static func getValidExpYear()->String { return "2026" } static func getValidExpMonth()->String { return "11" } static func getValidCvvNumber()->String { return "333" } static func getValidMCCreditCardNumber()->String { return "5572 7588 8601 5288" } static func getValidMCLast4Digits()->String { return "5288" } static func getInvalidCreditCardNumber()->String { return "5572 7588 8112 2333" } static func closeKeyboard(app: XCUIApplication, inputToTap: XCUIElement) { // if (!keyboardIsHidden) { inputToTap.tap() // if (app.keyboards.count > 0) { // let doneBtn = app.keyboards.buttons["Done"] // if doneBtn.exists && doneBtn.isHittable { // doneBtn.tap() // } // } } } extension XCUIElement { func clearText() { tap() guard let stringValue = self.value as? String else { return } var deleteString = String() for _ in stringValue { deleteString += XCUIKeyboardKey.delete.rawValue } self.typeText(deleteString) } }
mit
f18337d6a190ff6469d9907f2b84a1a5
48.223118
321
0.590028
5.662028
false
false
false
false
braintree/braintree_ios
UnitTests/BraintreeTestShared/FakeApplication.swift
1
785
import UIKit public class FakeApplication { public var lastOpenURL: URL? = nil public var openURLWasCalled: Bool = false var cannedOpenURLSuccess: Bool = true public var cannedCanOpenURL: Bool = true public var canOpenURLWhitelist: [URL] = [] public init() { } @objc func openURL(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any], completionHandler completion: ((Bool) -> Void)?) { lastOpenURL = url openURLWasCalled = true completion?(cannedOpenURLSuccess) } @objc func canOpenURL(_ url: URL) -> Bool { for whitelistURL in canOpenURLWhitelist { if whitelistURL.scheme == url.scheme { return true } } return cannedCanOpenURL } }
mit
17c4f9d59947a1153e841b5fb32464f3
27.035714
143
0.630573
4.845679
false
false
false
false
lorentey/swift
benchmark/single-source/ObserverForwarderStruct.swift
22
1383
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import TestsUtils public let ObserverForwarderStruct = BenchmarkInfo( name: "ObserverForwarderStruct", runFunction: run_ObserverForwarderStruct, tags: [.validation], legacyFactor: 5) class Observer { @inline(never) func receive(_ value: Int) { } } protocol Sink { func receive(_ value: Int) } struct Forwarder: Sink { let object: Observer func receive(_ value: Int) { object.receive(value) } } class Signal { var observers: [Sink] = [] func subscribe(_ sink: Sink) { observers.append(sink) } func send(_ value: Int) { for observer in observers { observer.receive(value) } } } public func run_ObserverForwarderStruct(_ iterations: Int) { let signal = Signal() let observer = Observer() for _ in 0 ..< 2_000 * iterations { signal.subscribe(Forwarder(object: observer)) } signal.send(1) }
apache-2.0
07295810daccbe9dd755074ee7ae5906
22.05
80
0.608821
4.308411
false
false
false
false
BaiduCloudTeam/PaperInSwift
PaperInSwift/CHSectionHeader.swift
1
3097
// // CHSectionHeader.swift // PaperInSwift // // Created by HX_Wang on 15/10/12. // Copyright © 2015年 Team_ChineseHamburger. All rights reserved. // import UIKit class CHSectionHeader : UICollectionViewCell, UIScrollViewDelegate { @IBOutlet weak var reflectedImage: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet var imageViews: [UIImageView]! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subTitleLabel: UILabel! @IBOutlet weak var logoLabel: UILabel! var didPageControllerChanged:(NSInteger) -> Void = {(arg : NSInteger) -> Void in } override internal func awakeFromNib() { self.reflectedImage.image = self.imageViews[0].image self.reflectedImage.transform = CGAffineTransformMakeScale(1.0, -1.0) self.clipsToBounds = true self.layer.cornerRadius = 4 // Gradient to top image for view in imageViews { if let imageView = view as? UIImageView { let gradientLayer = CAGradientLayer() gradientLayer.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).CGColor,UIColor(white: 0, alpha: 0).CGColor] gradientLayer.frame = imageView.bounds imageView.layer.insertSublayer(gradientLayer, atIndex: 0) } } // Gradient to reflected image let gradientReflected = CAGradientLayer() gradientReflected.frame = self.reflectedImage.bounds gradientReflected.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 1).CGColor,UIColor(white: 0, alpha: 0).CGColor] reflectedImage.layer.insertSublayer(gradientReflected, atIndex: 0) // Label Shadow logoLabel.clipsToBounds = false logoLabel.layer.shadowOffset = CGSizeMake(0, 0) logoLabel.layer.shadowColor = UIColor.blackColor().CGColor logoLabel.layer.shadowRadius = 1 logoLabel.layer.shadowOpacity = 0.6 // TitleLabel Shadow titleLabel.clipsToBounds = false titleLabel.layer.shadowOffset = CGSizeMake(0, 0) titleLabel.layer.shadowColor = UIColor.blackColor().CGColor titleLabel.layer.shadowRadius = 1.0 titleLabel.layer.shadowOpacity = 0.6 // SubTitleLabel Shadow subTitleLabel.clipsToBounds = false subTitleLabel.layer.shadowOffset = CGSizeMake(0, 0) subTitleLabel.layer.shadowColor = UIColor.blackColor().CGColor subTitleLabel.layer.shadowRadius = 1 subTitleLabel.layer.shadowOpacity = 0.6 } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let pageWidth = scrollView.frame.size.width let fractionPage = scrollView.contentOffset.x / pageWidth let newPage = lround(Double(fractionPage)) if pageControl.currentPage != newPage { reflectedImage.image = imageViews[newPage].image pageControl.currentPage = newPage didPageControllerChanged(newPage) } } }
mit
0f974460fad730901fd89186c3ea4a8c
38.679487
131
0.662896
4.974277
false
false
false
false
ygorshenin/omim
iphone/Maps/Classes/Components/Modal/AlertPresentationAnimator.swift
1
1002
final class AlertPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return kDefaultAnimationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toVC = transitionContext.viewController(forKey: .to) else { return } let containerView = transitionContext.containerView let finalFrame = transitionContext.finalFrame(for: toVC) containerView.addSubview(toVC.view) toVC.view.alpha = 0 toVC.view.center = containerView.center toVC.view.frame = finalFrame toVC.view.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleRightMargin, .flexibleBottomMargin] UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { toVC.view.alpha = 1 }) { transitionContext.completeTransition($0) } } }
apache-2.0
8248a6d8c08660a3b80bc6a483b2616d
44.545455
119
0.758483
5.964286
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Sources/Actor.swift
2
16622
// // Actor.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import SceneKit public class Actor: Item, NodeConstructible { public static var commandSpeed: Float = 1.0 // MARK: Item public static let identifier: WorldNodeIdentifier = .actor public weak var world: GridWorld? { didSet { // Create a new `WorldActionComponent` when setting the world. removeComponent(WorldActionComponent.self) addComponent(WorldActionComponent.self) let worldComponent = componentForType(WorldActionComponent.self) worldComponent?.world = world commandDelegate = world?.commandQueue } } public let node: NodeWrapper public var worldIndex = -1 public var isLevelMoveable: Bool { return true } var type: ActorType { didSet { guard type != oldValue else { return } for (index, component) in components.enumerated() { components[index] = component.dynamicType.self.init(actor: self) } } } /// The action that is currently running, if any. var currentAction: Action? var components = [ActorComponent]() var runningComponents = [ActorComponent]() /// Reports when all components have completed for the actor. weak var commandDelegate: PerformerDelegate? = nil lazy var actorCamera: SCNNode = { // Programmatically add an actor camera. let actorCamera = SCNNode() actorCamera.position = SCNVector3Make(0, 0.785, 3.25) actorCamera.eulerAngles.x = -0.1530727 actorCamera.camera = SCNCamera() actorCamera.name = "actorCamera" self.scnNode.addChildNode(actorCamera) return actorCamera }() /// If the a `CharacterName` is not provided, the saved character will be used. public init(name: CharacterName? = nil) { self.type = name?.type ?? ActorType.loadDefault() node = NodeWrapper(identifier: .actor) commonInit() } public required init?(node: SCNNode) { guard node.identifier == .actor && node.identifierComponents.count >= 2 else { return nil } guard let type = ActorType(rawValue: node.identifierComponents[1]) else { return nil } self.type = type self.node = NodeWrapper(node) commonInit() } func commonInit() { addComponent(AnimationComponent.self) addComponent(AudioComponent.self) scnNode.categoryBitMask = WorldConfiguration.characterLightBitMask } // MARK: ActorComponent /// There may only be one component instance for each component type. func addComponent<T : ActorComponent>(_ component: T.Type) { // Remove any component of the same type. removeComponent(component) components.append(component.init(actor: self)) } func componentForType<T : ActorComponent>(_ componentType: T.Type) -> T? { for component in components where component is T { return component as? T } return nil } func removeComponent<T : ActorComponent>(_ componentType: T.Type) { guard let index = components.index(where: { $0 is T }) else { return } components.remove(at: index) } public func loadGeometry() { guard scnNode.childNodes.isEmpty else { return } scnNode.addChildNode(type.createNode()) // Begin running the base breathing animation. componentForType(AnimationComponent.self)?.runsDefaultAnimationIndefinitely = true } // MARK: Jump /** Instructs the character to jump forward and either up or down one block. If the block the character is facing is one block higher than the block the character is standing on, the character will jump on top of it. If the block the character is facing is one block lower than the block the character is standing on, the character will jump down to that block. */ @discardableResult public func jump() -> Coordinate { guard let world = world else { return coordinate } let movementResult = world.movementResult(heading: heading, from: position) let nextCoordinate = nextCoordinateInCurrentDirection let deltaY = heightDisplacementMoving(to: nextCoordinate) // Determine if the y displacement is small enough such that the character can // cover it with a jump. let toleranceY = abs(deltaY) - WorldConfiguration.heightTolerance let isJumpableDisplacement = toleranceY < WorldConfiguration.levelHeight switch movementResult { case .valid, .raisedTile where isJumpableDisplacement, .edge where isJumpableDisplacement: let point = nextCoordinate.position let destination = SCNVector3Make(point.x, position.y + deltaY, point.z) add(action: .jump(from: position, to: destination)) // Check for portals. addCommandForPortal(at: nextCoordinate) return nextCoordinate default: // Error cases evaluate to the same result as `moveForward()`. return moveForward() } } /// Creates a new command if a portal exists at the specified coordinate. private func addCommandForPortal(at coordinate: Coordinate) { let portal = world?.existingNode(ofType: Portal.self, at: coordinate) if let destinationPortal = portal?.linkedPortal, portal!.isActive { add(action: .teleport(from: position, to: destinationPortal.position)) } } } // MARK: Movement Commands extension Actor { /** Moves the character forward one tile. */ @discardableResult public func moveForward() -> Coordinate { guard let world = world else { return coordinate } let movementResult = world.movementResult(heading: heading, from: position) switch movementResult { case .valid: let nextCoordinate = nextCoordinateInCurrentDirection // Check for stairs. let yDisplacement = position.y + heightDisplacementMoving(to: nextCoordinate) let point = nextCoordinate.position let destination = SCNVector3Make(point.x, yDisplacement, point.z) add(action: .move(from: position, to: destination)) // Check for portals. addCommandForPortal(at: nextCoordinate) case .edge, .obstacle: add(action: .incorrect(.offEdge)) case .wall, .raisedTile, .occupied: add(action: .incorrect(.intoWall)) } return Coordinate(position) } /** Turns the character left. */ public func turnLeft() { turnBy(90) } /** Turns the character right. */ public func turnRight() { turnBy(-90) } /** Moves the character forward by a certain number of tiles, as determined by the `distance` parameter value. */ public func move(distance: Int) { for _ in 1 ... distance { moveForward() } } // MARK: Action Helpers /** Rotates the actor by `degrees` around the y-axis. - turnLeft() = 90 - turnRight() = -90/ 270 */ @discardableResult func turnBy(_ degrees: Int) -> SCNFloat { // Convert degrees to radians. let nextDirection = (rotation + degrees.toRadians).truncatingRemainder(dividingBy: 2 * π) let currentDir = Direction(radians: rotation) let nextDir = Direction(radians: nextDirection) let clockwise = currentDir.angle(to: nextDir) < 0 add(action: .turn(from: rotation, to: nextDirection, clockwise: clockwise)) return nextDirection } /// Returns the next coordinate moving forward 1 tile in the actors `currentDirection`. var nextCoordinateInCurrentDirection: Coordinate { return coordinateInCurrentDirection(displacement: 1) } func coordinateInCurrentDirection(displacement: Int) -> Coordinate { let heading = Direction(radians: rotation) let coordinate = Coordinate(position) return coordinate.advanced(by: displacement, inDirection: heading) } func heightDisplacementMoving(to coordinate: Coordinate) -> SCNFloat { guard let world = world else { return 0 } let startHeight = position.y let endHeight = world.height(at: coordinate) return endHeight - startHeight } } // MARK: Item Commands extension Actor { /** Instructs the character to collect a gem on the current tile. */ @discardableResult public func collectGem() -> Bool { guard let item = world?.existingGems(at: [coordinate]).first else { add(action: .incorrect(.missingGem)) return false } add(action: .remove([item.worldIndex])) return true } /** Instructs the character to toggle a switch on the current tile. */ @discardableResult public func toggleSwitch() -> Bool { guard let switchNode = world?.existingNode(ofType: Switch.self, at: coordinate) else { add(action: .incorrect(.missingSwitch)) return false } // Toggle switch to the opposite of it's original value. let oldValue = switchNode.isOn add(action: .toggle(toggleable: switchNode.worldIndex, active: !oldValue)) return true } } extension Actor: Equatable{} public func ==(lhs: Actor, rhs: Actor) -> Bool { return lhs.type == rhs.type && lhs.node === rhs.node } // MARK: Boolean Commands extension Actor { /** Condition that checks if the character is on a tile with a gem on it. */ public var isBlocked: Bool { guard let world = world else { return false } return !world.isValidActorTranslation(heading: heading, from: position) } /** Condition that checks if the character is blocked on the left. */ public var isBlockedLeft: Bool { return isBlocked(heading: .west) } /** Condition that checks if the character is blocked on the right. */ public var isBlockedRight: Bool { return isBlocked(heading: .east) } func isBlocked(heading: Direction) -> Bool { guard let world = world else { return false } let blockedCheckDir = Direction(radians: rotation - heading.radians) return !world.isValidActorTranslation(heading: blockedCheckDir, from: position) } // MARK: isOn /** Condition that checks if the character is currently on a tile with that contains a WorldNode of a specific type. */ public func isOnNode<Node: Item>(ofType type: Node.Type) -> Bool { return nodeAtCurrentPosition(ofType: type) != nil } /** Condition that checks if the character is on a tile with a gem on it. */ public var isOnGem: Bool { return isOnNode(ofType: Gem.self) } /** Condition that checks if the character is on a tile with an open switch on it. */ public var isOnOpenSwitch: Bool { if let switchNode = nodeAtCurrentPosition(ofType: Switch.self) { return switchNode.isOn } return false } /** Condition that checks if the character is on a tile with a closed switch on it. */ public var isOnClosedSwitch: Bool { if let switchNode = nodeAtCurrentPosition(ofType: Switch.self) { return !switchNode.isOn } return false } func nodeAtCurrentPosition<Node: Item>(ofType type: Node.Type) -> Node? { guard let world = world else { return nil } return world.existingNode(ofType: type, at: coordinate) } } // MARK: Performer extension Actor: Performer { var id: Int { return worldIndex } var isRunning: Bool { return !runningComponents.isEmpty } func applyStateChange(for action: Action) { for performer in components { performer.applyStateChange(for: action) } } /// Cycles through the actors components allowing each component to respond to the action. func perform(_ action: Action) { // Clear the `currentAction` in case a valid animation does not exist. currentAction = nil if !runningComponents.isEmpty { for performer in runningComponents { performer.cancel(action) } } runningComponents = self.components // Not all commands apply to the actor, return immediately if there is no action. guard let animation = action.animation else { return } currentAction = action let possibleVariations = AnimationType.allIdentifiersByType[animation] let variationIndex = possibleVariations?.randomIndex ?? 0 for component in runningComponents { component.play(animation: animation, variation: variationIndex) } } func cancel(_ action: Action) { // Cancel all components. // A lot of components don't hold as running, but need to be reset with cancel. for performer in components { performer.cancel(action) } } /// Convenience to create an `Command` by bundling in `self` with the provided action. func add(action: Action) { guard let world = world else { return } let command = Command(performer: self, action: action) world.commandQueue.append(command, applyingState: true) } } // MARK: PerformerDelegate extension Actor: PerformerDelegate { func performerFinished(_ performer: Performer) { precondition(Thread.isMainThread) // Match the finished performer with the remaining `runningComponents`. guard let index = runningComponents.index(where: { $0 === performer }) else { return } runningComponents.remove(at: index) if runningComponents.isEmpty { commandDelegate?.performerFinished(self) } } } import PlaygroundSupport extension Actor: MessageConstructor { // MARK: MessageConstructor var message: PlaygroundValue { return .array(baseMessage + stateInfo) } var stateInfo: [PlaygroundValue] { return [.string(type.rawValue)] } } // MARK: Swap extension Actor { private var fadeDuration: CGFloat { return WorldConfiguration.Actor.animationFadeDuration } func swap(with actor: Actor) { actor.scnNode.removeAllAnimations() actor.scnNode.removeAllActions() for child in scnNode.childNodes { child.removeFromParentNode() } for child in actor.scnNode.childNodes { scnNode.addChildNode(child) } type = actor.type } func showContinuousIdle() { let idleAnimations = ActorAnimation(type: type)[.idle] guard !idleAnimations.isEmpty else { return } let index = idleAnimations.randomIndex let idleAnimation = idleAnimations[index] idleAnimation.fadeInDuration = fadeDuration idleAnimation.fadeOutDuration = fadeDuration var actions = [SCNAction]() let actorIdle = SCNAction.animate(with: idleAnimation, forKey: "Idle") actions.append(actorIdle) let identifier = "Idle" + "0\(index + 1)" if let audioAction = ActorAnimation.createAudioAction(for: type, identifier: identifier) { actions.append(audioAction) } let wait = SCNAction.wait(forDuration: 5, withRange: 3) let repeatAction = SCNAction.run { [weak self] _ in // Start the entire sequence over with a new random animation. self?.showContinuousIdle() } scnNode.run(.sequence([.group(actions), wait, repeatAction]), forKey: WorldConfiguration.sceneCompletionActionKey) } func removeCompletionActions() { scnNode.removeAction(forKey: WorldConfiguration.sceneCompletionActionKey) } }
mit
335923a0841ce16b99a7a47673d666d3
30.41966
149
0.619277
5.000301
false
false
false
false
mozilla-mobile/firefox-ios
Tests/ClientTests/Utils/ThrottlerTests.swift
2
1482
// 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 XCTest @testable import Client class ThrottlerTests: XCTestCase { func testThrottle_1000SecondsThrottle_doesntCall() { let subject = Throttler(seconds: 100000, on: DispatchQueue.global()) var throttleCalled = 0 subject.throttle { throttleCalled += 1 } subject.throttle { throttleCalled += 1 } XCTAssertEqual(throttleCalled, 0, "Throttle isn't called since delay is high") } func testThrottle_zeroSecondThrottle_callsTwice() { let subject = Throttler(seconds: 0, on: MockDispatchQueue()) var throttleCalled = 0 subject.throttle { throttleCalled += 1 } subject.throttle { throttleCalled += 1 } XCTAssertEqual(throttleCalled, 2, "Throttle twice is called since delay is zero") } func testThrottle_oneSecondThrottle_callsOnce() { let subject = Throttler(seconds: 0.2, on: DispatchQueue.global()) var throttleCalled = 0 subject.throttle { throttleCalled += 1 } subject.throttle { throttleCalled += 1 } wait(0.5) XCTAssertEqual(throttleCalled, 1, "Throttle is called once, one got canceled") } }
mpl-2.0
e4e69f5692d1b0a68ccb4c08201cf7e4
26.962264
89
0.618758
4.734824
false
true
false
false
ktustanowski/WeakItemContainer
WeakItemContainerTests/WeakItemContainerTests.swift
1
2669
// // WeakItemContainerTests.swift // PlayPlex // // Created by Kamil Tustanowski on 07.10.2015. // Copyright © 2015 Kamil Tustanowski. All rights reserved. // import XCTest @testable import WeakItemContainer class WeakItemContainerTests: XCTestCase { var container: WeakItemContainer<NSObject>! override func setUp() { super.setUp() container = WeakItemContainer<NSObject>() } override func tearDown() { container.removeAll() container = nil super.tearDown() } func testIfCanAppendItem() { let object = NSObject() container.append(object) XCTAssert(self.container.count == 1) } func testIfCantHaveDuplicatedObjects() { let object = NSObject() container.append(object) container.append(object) XCTAssert(self.container.count == 1) } func testIfCanRemoveItem() { let object = NSObject() container.append(object) container.remove(object) XCTAssert(self.container.count == 0) } func testIfWhenTryingToRemoveUncontainedItemDoesNothing() { XCTAssertNoThrow({ [weak self] in self?.container.remove(NSObject()) }) } func testIfCanRemoveAllObjectsAtOnce() { let objects = testObjectsArray() for object in objects { container.append(object) } container.removeAll() XCTAssert(self.container.count == 0) } func testIfCanRetrieveObjects() { let objectOne = NSObject() let objectTwo = NSObject() container.append(objectOne) container.append(objectTwo) let items = container.items XCTAssert(items.count == 2) XCTAssert(items.contains(objectOne) == true) XCTAssert(items.contains(objectTwo) == true) } func testIfObjectsAddedToContainerCanBeDeallocated() { var object:NSObject? = NSObject() container.append(object!) object = nil XCTAssert(self.container.count == 0) } func testIfCanSeeObjectCount() { let objects = testObjectsArray() for object in objects { container.append(object) } XCTAssert(self.container.count == objects.count) } } // MARK: Helper methods extension WeakItemContainerTests { func testObjectsArray() -> [NSObject] { return [NSObject(), NSObject(), NSObject(), NSObject(), NSObject(), NSObject(), NSObject(), NSObject(), NSObject(), NSObject()] } }
mit
3704b4efc188554a8c918c92fef97a64
23.934579
135
0.593703
4.949907
false
true
false
false
klundberg/swift-corelibs-foundation
Foundation/NSStream.swift
1
10504
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) internal extension UInt { init(_ status: CFStreamStatus) { self.init(status.rawValue) } } #endif extension Stream { public struct PropertyKey : RawRepresentable, Equatable, Hashable, Comparable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return rawValue.hashValue } } public enum Status : UInt { case notOpen case opening case open case reading case writing case atEnd case closed case error } public struct Event : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let openCompleted = Event(rawValue: 1 << 0) public static let hasBytesAvailable = Event(rawValue: 1 << 1) public static let hasSpaceAvailable = Event(rawValue: 1 << 2) public static let errorOccurred = Event(rawValue: 1 << 3) public static let endEncountered = Event(rawValue: 1 << 4) } } public func ==(lhs: Stream.PropertyKey, rhs: Stream.PropertyKey) -> Bool { return lhs.rawValue == rhs.rawValue } public func <(lhs: Stream.PropertyKey, rhs: Stream.PropertyKey) -> Bool { return lhs.rawValue < rhs.rawValue } // NSStream is an abstract class encapsulating the common API to NSInputStream and NSOutputStream. // Subclassers of NSInputStream and NSOutputStream must also implement these methods. public class Stream: NSObject { public override init() { } public func open() { NSRequiresConcreteImplementation() } public func close() { NSRequiresConcreteImplementation() } public weak var delegate: StreamDelegate? // By default, a stream is its own delegate, and subclassers of NSInputStream and NSOutputStream must maintain this contract. [someStream setDelegate:nil] must restore this behavior. As usual, delegates are not retained. public func propertyForKey(_ key: String) -> AnyObject? { NSUnimplemented() } public func setProperty(_ property: AnyObject?, forKey key: String) -> Bool { NSUnimplemented() } // Re-enable once run loop is compiled on all platforms public func schedule(in aRunLoop: RunLoop, forMode mode: RunLoopMode) { NSUnimplemented() } public func remove(from aRunLoop: RunLoop, forMode mode: RunLoopMode) { NSUnimplemented() } public var streamStatus: Status { NSRequiresConcreteImplementation() } /*@NSCopying */public var streamError: NSError? { NSUnimplemented() } } // NSInputStream is an abstract class representing the base functionality of a read stream. // Subclassers are required to implement these methods. public class InputStream: Stream { private var _stream: CFReadStream! // reads up to length bytes into the supplied buffer, which must be at least of size len. Returns the actual number of bytes read. public func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int { return CFReadStreamRead(_stream, buffer, CFIndex(len._bridgeToObject())) } // returns in O(1) a pointer to the buffer in 'buffer' and by reference in 'len' how many bytes are available. This buffer is only valid until the next stream operation. Subclassers may return NO for this if it is not appropriate for the stream type. This may return NO if the buffer is not available. public func getBuffer(_ buffer: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>, length len: UnsafeMutablePointer<Int>) -> Bool { NSUnimplemented() } // returns YES if the stream has bytes available or if it impossible to tell without actually doing the read. public var hasBytesAvailable: Bool { return CFReadStreamHasBytesAvailable(_stream) } public init(data: Data) { _stream = CFReadStreamCreateWithData(kCFAllocatorSystemDefault, data._cfObject) } public init?(url: URL) { _stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url._cfObject) } public convenience init?(fileAtPath path: String) { self.init(url: URL(fileURLWithPath: path)) } public override func open() { CFReadStreamOpen(_stream) } public override func close() { CFReadStreamClose(_stream) } public override var streamStatus: Status { return Stream.Status(rawValue: UInt(CFReadStreamGetStatus(_stream)))! } } // NSOutputStream is an abstract class representing the base functionality of a write stream. // Subclassers are required to implement these methods. // Currently this is left as named NSOutputStream due to conflicts with the standard library's text streaming target protocol named OutputStream (which ideally should be renamed) public class NSOutputStream : Stream { // writes the bytes from the specified buffer to the stream up to len bytes. Returns the number of bytes actually written. public func write(_ buffer: UnsafePointer<UInt8>, maxLength len: Int) -> Int { NSUnimplemented() } // returns YES if the stream can be written to or if it is impossible to tell without actually doing the write. public var hasSpaceAvailable: Bool { NSUnimplemented() } public init(toMemory: ()) { NSUnimplemented() } public init(toBuffer buffer: UnsafeMutablePointer<UInt8>, capacity: Int) { NSUnimplemented() } public init?(url: URL, append shouldAppend: Bool) { NSUnimplemented() } public convenience init?(toFileAtPath path: String, append shouldAppend: Bool) { NSUnimplemented() } public class func outputStreamToMemory() -> Self { NSUnimplemented() } } // Discussion of this API is ongoing for its usage of AutoreleasingUnsafeMutablePointer #if false extension Stream { public class func getStreamsToHost(withName hostname: String, port: Int, inputStream: AutoreleasingUnsafeMutablePointer<InputStream?>?, outputStream: AutoreleasingUnsafeMutablePointer<NSOutputStream?>?) { NSUnimplemented() } } extension Stream { public class func getBoundStreams(withBufferSize bufferSize: Int, inputStream: AutoreleasingUnsafeMutablePointer<InputStream?>?, outputStream: AutoreleasingUnsafeMutablePointer<NSOutputStream?>?) { NSUnimplemented() } } #endif extension StreamDelegate { func stream(_ aStream: Stream, handleEvent eventCode: Stream.Event) { } } public protocol StreamDelegate : class { func stream(_ aStream: Stream, handleEvent eventCode: Stream.Event) } // NSString constants for the propertyForKey/setProperty:forKey: API // String constants for the setting of the socket security level. // use this as the key for setting one of the following values for the security level of the target stream. public let NSStreamSocketSecurityLevelKey: String = "kCFStreamPropertySocketSecurityLevel" public let NSStreamSocketSecurityLevelNone: String = "kCFStreamSocketSecurityLevelNone" public let NSStreamSocketSecurityLevelSSLv2: String = "NSStreamSocketSecurityLevelSSLv2" public let NSStreamSocketSecurityLevelSSLv3: String = "NSStreamSocketSecurityLevelSSLv3" public let NSStreamSocketSecurityLevelTLSv1: String = "kCFStreamSocketSecurityLevelTLSv1" public let NSStreamSocketSecurityLevelNegotiatedSSL: String = "kCFStreamSocketSecurityLevelNegotiatedSSL" public let NSStreamSOCKSProxyConfigurationKey: String = "kCFStreamPropertySOCKSProxy" // Value is an NSDictionary containing the key/value pairs below. The dictionary returned from SystemConfiguration for SOCKS proxies will work without alteration. public let NSStreamSOCKSProxyHostKey: String = "NSStreamSOCKSProxyKey" // Value is an NSString public let NSStreamSOCKSProxyPortKey: String = "NSStreamSOCKSPortKey" // Value is an NSNumber public let NSStreamSOCKSProxyVersionKey: String = "kCFStreamPropertySOCKSVersion" // Value is one of NSStreamSOCKSProxyVersion4 or NSStreamSOCKSProxyVersion5 public let NSStreamSOCKSProxyUserKey: String = "kCFStreamPropertySOCKSUser" // Value is an NSString public let NSStreamSOCKSProxyPasswordKey: String = "kCFStreamPropertySOCKSPassword" // Value is an NSString public let NSStreamSOCKSProxyVersion4: String = "kCFStreamSocketSOCKSVersion4" // Value for NSStreamSOCKProxyVersionKey public let NSStreamSOCKSProxyVersion5: String = "kCFStreamSocketSOCKSVersion5" // Value for NSStreamSOCKProxyVersionKey public let NSStreamDataWrittenToMemoryStreamKey: String = "kCFStreamPropertyDataWritten" // Key for obtaining the data written to a memory stream. public let NSStreamFileCurrentOffsetKey: String = "kCFStreamPropertyFileCurrentOffset" // Value is an NSNumber representing the current absolute offset of the stream. // NSString constants for error domains. public let NSStreamSocketSSLErrorDomain: String = "NSStreamSocketSSLErrorDomain" // SSL errors are to be interpreted via <Security/SecureTransport.h> public let NSStreamSOCKSErrorDomain: String = "NSStreamSOCKSErrorDomain" // Property key to specify the type of service for the stream. This // allows the system to properly handle the request with respect to // routing, suspension behavior and other networking related attributes // appropriate for the given service type. The service types supported // are documented below. public let NSStreamNetworkServiceType: String = "kCFStreamNetworkServiceType" // Supported network service types: public let NSStreamNetworkServiceTypeVoIP: String = "kCFStreamNetworkServiceTypeVoIP" public let NSStreamNetworkServiceTypeVideo: String = "kCFStreamNetworkServiceTypeVideo" public let NSStreamNetworkServiceTypeBackground: String = "kCFStreamNetworkServiceTypeBackground" public let NSStreamNetworkServiceTypeVoice: String = "kCFStreamNetworkServiceTypeVoice"
apache-2.0
81f6acbc5f194e9c4b6836d0a28af51f
37.617647
305
0.734863
5.252
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Info/EventInfoCollectionViewCell.swift
1
17288
// // Copyright (c) 2017 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 Firebase import MaterialComponents class EventInfoCollectionViewCell: MDCCollectionViewCell { struct Constants { static let headerHeight: CGFloat = 200 // swiftlint:disable large_tuple static let headerInsets: (left: CGFloat, right: CGFloat) = ( left: 16, right: 16 ) // swiftlint:enable large_tuple static let titleTopPadding: CGFloat = 16 static let titleLabelFont = UIFont.preferredFont(forTextStyle: .title1) static let titleTextColor = UIColor(red: 74 / 255, green: 74 / 255, blue: 74 / 255, alpha: 1) static let titleLabelTopSpacing: CGFloat = 14 static let summaryLabelFont = { () -> UIFont in return UIFont.preferredFont(forTextStyle: .body) } static let summaryLabelTopSpacing: CGFloat = 16 static let summaryLabelBottomSpacing: CGFloat = 102 static let summaryTextColor = UIColor(red: 66 / 255, green: 66 / 255, blue: 66 / 255, alpha: 1) static let summaryParagraphStyle = { () -> NSMutableParagraphStyle in let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = 24 / 15 return paragraphStyle }() static let viewSessionsText = NSLocalizedString("View sessions", comment: "Button text to open the schedule view") static let viewMapText = NSLocalizedString("View map", comment: "Button text to open the map view") static let buttonTextColor = UIColor(red: 26 / 255, green: 115 / 255, blue: 232 / 255, alpha: 1) } private let titleImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) private let titleLabel = UILabel() private let headerBackgroundView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill return imageView }() // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(headerBackgroundView) contentView.addSubview(titleImageView) contentView.addSubview(titleLabel) contentView.addSubview(summaryLabel) contentView.addSubview(viewSessionsButton) contentView.addSubview(viewMapButton) setupHeaderBackgroundView() setupSummaryLabel() setupConstraints() setupButtons() contentView.layer.cornerRadius = 8 contentView.layer.borderColor = UIColor(hex: 0xdadce0).cgColor contentView.layer.borderWidth = 1 contentView.clipsToBounds = true } var summary: String? { get { return summaryLabel.text ?? summaryLabel.attributedText?.string } set { guard let string = newValue else { summaryLabel.text = nil return } let attributed = NSMutableAttributedString(string: string) attributed.addAttribute(NSAttributedString.Key.paragraphStyle, value: Constants.summaryParagraphStyle, range: NSRange(location: 0, length: attributed.length)) summaryLabel.attributedText = attributed } } var title: String? { get { return titleLabel.text ?? titleLabel.attributedText?.string } set { titleLabel.text = newValue } } var titleIcon: UIImage? { get { return headerBackgroundView.image } set { headerBackgroundView.image = newValue } } // MARK: - Private layout code private let summaryLabel = UILabel() fileprivate let viewSessionsButton = MDCFlatButton() fileprivate let viewMapButton = MDCFlatButton() private static func boundingRect(forText text: String, attributes: [NSAttributedString.Key: Any]? = nil, maxWidth: CGFloat) -> CGRect { let rect = text.boundingRect(with: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil) return rect } static func minimumHeight(title: String, summary: String, maxWidth: CGFloat) -> CGFloat { let effectiveMaxWidth = maxWidth - Constants.headerInsets.left - Constants.headerInsets.right let summaryHeight = boundingRect(forText: summary, attributes: [ NSAttributedString.Key.font: Constants.summaryLabelFont(), NSAttributedString.Key.paragraphStyle: Constants.summaryParagraphStyle ], maxWidth: effectiveMaxWidth).size.height let titleHeight = boundingRect(forText: title, attributes: [NSAttributedString.Key.font: Constants.titleLabelFont], maxWidth: effectiveMaxWidth).size.height return Constants.headerHeight + Constants.titleTopPadding + titleHeight + Constants.summaryLabelTopSpacing + summaryHeight + Constants.summaryLabelBottomSpacing } private func setupHeaderBackgroundView() { headerBackgroundView.translatesAutoresizingMaskIntoConstraints = false titleImageView.contentMode = .scaleAspectFit titleImageView.translatesAutoresizingMaskIntoConstraints = false titleLabel.numberOfLines = 0 titleLabel.lineBreakMode = .byWordWrapping titleLabel.font = Constants.titleLabelFont titleLabel.textColor = Constants.titleTextColor titleLabel.enableAdjustFontForContentSizeCategory() titleLabel.translatesAutoresizingMaskIntoConstraints = false } private func setupSummaryLabel() { summaryLabel.font = Constants.summaryLabelFont() summaryLabel.numberOfLines = 0 summaryLabel.lineBreakMode = .byWordWrapping summaryLabel.textColor = Constants.summaryTextColor summaryLabel.translatesAutoresizingMaskIntoConstraints = false } private func setupButtons() { viewSessionsButton.translatesAutoresizingMaskIntoConstraints = false viewMapButton.translatesAutoresizingMaskIntoConstraints = false viewSessionsButton.setTitle(Constants.viewSessionsText, for: .normal) viewMapButton.setTitle(Constants.viewMapText, for: .normal) viewSessionsButton.setTitleColor(Constants.buttonTextColor, for: .normal) viewMapButton.setTitleColor(Constants.buttonTextColor, for: .normal) viewSessionsButton.isUppercaseTitle = false viewMapButton.isUppercaseTitle = false viewSessionsButton.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) viewMapButton.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside) } // swiftlint:disable function_body_length private func setupConstraints() { var constraints: [NSLayoutConstraint] = [] // header background view top constraints.append(NSLayoutConstraint(item: headerBackgroundView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0)) // header background view left constraints.append(NSLayoutConstraint(item: headerBackgroundView, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 0)) // header background view right constraints.append(NSLayoutConstraint(item: headerBackgroundView, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: 0)) // header background view height constraints.append(NSLayoutConstraint(item: headerBackgroundView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: Constants.headerHeight)) // image view height constraints.append(NSLayoutConstraint(item: titleImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)) // image view width constraints.append(NSLayoutConstraint(item: titleImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)) // image view top constraints.append(NSLayoutConstraint(item: titleImageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 30)) // image view right constraints.append(NSLayoutConstraint(item: titleImageView, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -45)) // title label bottom constraints.append(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: headerBackgroundView, attribute: .bottom, multiplier: 1, constant: Constants.titleTopPadding)) // title label left constraints.append(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: Constants.headerInsets.left)) // title label right constraints.append(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -Constants.headerInsets.right)) // summary label top constraints.append(NSLayoutConstraint(item: summaryLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1, constant: Constants.summaryLabelTopSpacing)) // summary label left constraints.append(NSLayoutConstraint(item: summaryLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: Constants.headerInsets.left)) // summary label right constraints.append(NSLayoutConstraint(item: summaryLabel, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -Constants.headerInsets.right)) // view map button right constraints.append(NSLayoutConstraint(item: viewMapButton, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: -16)) // view map button bottom constraints.append(NSLayoutConstraint(item: viewMapButton, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -16)) // view sessions button right constraints.append(NSLayoutConstraint(item: viewSessionsButton, attribute: .right, relatedBy: .equal, toItem: viewMapButton, attribute: .left, multiplier: 1, constant: 0)) // view sessions button bottom constraints.append(NSLayoutConstraint(item: viewSessionsButton, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -16)) contentView.addConstraints(constraints) } // swiftlint:enable function_body_length override func layoutSubviews() { super.layoutSubviews() // Support dynamic type let font = Constants.summaryLabelFont() if font.pointSize != summaryLabel.font.pointSize { summaryLabel.font = font } } // Don't show ink view on this cell. override var inkView: MDCInkView? { get { return nil } set {} } @available(*, unavailable) required init(coder: NSCoder) { fatalError("NSCoding not supported for cell of type \(EventInfoCollectionViewCell.self)") } } // MARK: - Buttons extension EventInfoCollectionViewCell { @objc fileprivate func buttonPressed(_ sender: Any) { guard let button = sender as? UIButton else { return } let action: String switch button { case viewSessionsButton: Application.sharedInstance.rootNavigator.navigateToSchedule() action = "view sessions" case viewMapButton: Application.sharedInstance.rootNavigator.navigateToMap(roomId: nil) action = "view maps" case _: return } guard let title = title else { return } Application.sharedInstance.analytics.logEvent(AnalyticsEventSelectContent, parameters: [ AnalyticsParameterItemID: title, AnalyticsParameterContentType: AnalyticsParameters.uiEvent, AnalyticsParameters.uiAction: action ]) } }
apache-2.0
bcd620440481085485e57383cdd30b96
41.792079
108
0.523947
6.687814
false
false
false
false
AlexRamey/mbird-iOS
iOS Client/ArticlesController/ArticlesCoordinator.swift
1
2343
// // ArticlesCoordinator.swift // iOS Client // // Created by Alex Ramey on 9/30/17. // Copyright © 2017 Mockingbird. All rights reserved. // import UIKit import SafariServices class ArticlesCoordinator: NSObject, Coordinator, UINavigationControllerDelegate, SFSafariViewControllerDelegate, ArticlesTableViewDelegate, ArticleDetailDelegate { var childCoordinators: [Coordinator] = [] var overlay: URL? var articleDAO: ArticleDAO var authorDAO: AuthorDAO var categoryDAO: CategoryDAO var rootViewController: UIViewController { return self.navigationController } lazy var navigationController: UINavigationController = { return UINavigationController() }() init(articleDAO: ArticleDAO, authorDAO: AuthorDAO, categoryDAO: CategoryDAO) { self.articleDAO = articleDAO self.authorDAO = authorDAO self.categoryDAO = categoryDAO super.init() } // MARK: - Articles Table View Delegate func selectedArticle(_ article: Article, categoryContext: String?) { let detailVC = MBArticleDetailViewController.instantiateFromStoryboard(article: article, categoryContext: categoryContext, dao: self.articleDAO) detailVC.delegate = self self.navigationController.pushViewController(detailVC, animated: true) } // MARK: - Article Detail Delegate func selectedURL(url: URL) { if let upperScheme = url.scheme?.uppercased() { if upperScheme == "HTTP" || upperScheme == "HTTPS" { let safariVC = SFSafariViewController(url: url) safariVC.delegate = self self.navigationController.present(safariVC, animated: true, completion: nil) } } } // MARK: = SF Safari View Controller Delegate func safariViewControllerDidFinish(_ controller: SFSafariViewController) { self.navigationController.dismiss(animated: true, completion: nil) } // MARK: - Coordinator func start() { let articlesController = MBArticlesViewController.instantiateFromStoryboard(articleDAO: self.articleDAO, authorDAO: self.authorDAO, categoryDAO: self.categoryDAO) articlesController.delegate = self self.navigationController.pushViewController(articlesController, animated: true) } }
mit
f8ab8427bdc6ef7e9a1d7cc7bdefb6fc
36.174603
170
0.69684
5.216036
false
false
false
false
AllenOoo/SliderMenu-CollectionView
MyDemosInSwift/YZButton.swift
1
3972
// // YZButton.swift // MyDemosInSwift // // Created by zW on 16/8/14. // Copyright © 2016年 allen.wu. All rights reserved. // import UIKit enum YZButtonType { case scale case normal } let YZButtonTagStart: NSInteger = 1000 let YZButtonScaleMaxFloat = 1.3 let YZButtonScaleMinFloat = 1.0 let YZButtonTransAnimationInterval : NSTimeInterval = 0.25 protocol YZButtonDelegate { func didSelectedAtButton(button: YZButton?) } class YZButton: UIButton { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var scaleFloat = 0.0; var highlightColor : UIColor! var delegate: YZButtonDelegate? override init(frame: CGRect) { super.init(frame: frame) dataInit() } class func initWithType(frame: CGRect,type: YZButtonType) -> YZButton? { switch type { case .scale: return YZScaleTypeButton.init(frame: frame) case .normal: return YZButton.init(frame: frame) } } func addAction(action: UIControlActionBlock) { self.inEventDoSomething(.TouchUpInside, doSomething: action) } func dataInit() { } } class YZScaleTypeButton: YZButton { required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var isNeededAnimation : Bool = false private var defaultHightlightColor = UIColor.init(red: 147/255.0, green: 224/255.0, blue: 1, alpha: 1); override var highlightColor: UIColor! { set { if (newValue != nil) { defaultHightlightColor = highlightColor } } get { return defaultHightlightColor } } override var scaleFloat: Double { didSet { var scaleColorFloat = scaleFloat; var titleColor:UIColor! if scaleColorFloat < 1.05 { titleColor = UIColor.whiteColor() } else { if scaleColorFloat < 1.20 { scaleColorFloat = 1.2 } titleColor = highlightColor.colorWithAlphaComponent(CGFloat(scaleColorFloat/YZButtonScaleMaxFloat)) } self.setTitleColor(titleColor, forState: .Normal) if isNeededAnimation { if scaleFloat >= YZButtonScaleMaxFloat { UIView.animateWithDuration(YZButtonTransAnimationInterval, animations: { self.transform = self.transScale(YZButtonScaleMaxFloat) }) } else { if scaleFloat <= 1.05 { UIView.animateWithDuration(YZButtonTransAnimationInterval, animations: { self.transform = self.transBack() }) } } } else { if scaleFloat > YZButtonScaleMaxFloat - 0.05 { self.transform = self.transScale(YZButtonScaleMaxFloat) } else { if scaleFloat <= 1.05 { self.transform = self.transBack() } else { self.transform = self.transScale(scaleFloat) } } } isNeededAnimation = false } } override init(frame: CGRect) { super.init(frame: frame) } override func dataInit() { self.addAction { (sender) in // 选择时的缩放动画 self.isNeededAnimation = true self.scaleFloat = YZButtonScaleMaxFloat self.delegate?.didSelectedAtButton(self) } } func transScale(scaleFloat: Double) -> CGAffineTransform { return CGAffineTransformMakeScale(CGFloat(scaleFloat), CGFloat(scaleFloat)); } func transBack() -> CGAffineTransform { return CGAffineTransformIdentity } }
apache-2.0
2d560bd3aa29438626e70abee9855fcf
25.716216
111
0.568176
5.094072
false
false
false
false
morbrian/udacity-nano-onthemap
OnTheMap/ParseClient.swift
1
11056
// // ParseClient.swift // OnTheMap // // Created by Brian Moriarty on 4/24/15. // Copyright (c) 2015 Brian Moriarty. All rights reserved. // import Foundation // ParseClient // Provides simple api layer on top of WebClient designed to encapsulate // the common patterns associated with REST apis based on the Parse framework. public class ParseClient { private var applicationId: String! private var restApiKey: String! private var StandardHeaders: [String:String] { return [ "X-Parse-Application-Id":applicationId, "X-Parse-REST-API-Key":restApiKey ] } private var webClient: WebClient! // Initialize with app specific keys and id // client: insteance of a WebClient // applicationId: valid ID provided to this App for use with the Parse service. // restApiKey: a developer API Key provided by registering with the Parse service. public init(client: WebClient, applicationId: String, restApiKey: String) { self.webClient = client self.applicationId = applicationId self.restApiKey = restApiKey } // Fetch a list of objects from the Parse service for the specified class type. // className: the object model classname of the data type on Parse // limit: maximum number of objects to fetch // skip: number of objects to skip before fetching the limit. // orderedBy: name of an attribute on the object model to sort results by. // whereClause: Parse formatted query where clause to constrain query results. public func fetchResultsForClassName(className: String, limit: Int = 50, skip: Int = 0, orderedBy: String = ParseJsonKey.UpdatedAt, whereClause: String? = nil, completionHandler: (resultsArray: [[String:AnyObject]]?, error: NSError?) -> Void) { var parameterList: [String:AnyObject] = [ParseParameter.Limit:limit, ParseParameter.Skip: skip, ParseParameter.Order: orderedBy] if let whereClause = whereClause { parameterList[ParseParameter.Where] = whereClause } if let request = webClient.createHttpRequestUsingMethod(WebClient.HttpGet, forUrlString: "\(ParseClient.ObjectUrl)/\(className)", includeHeaders: StandardHeaders, includeParameters: parameterList) { webClient.executeRequest(request) { jsonData, error in if let resultsArray = jsonData?.valueForKey(ParseJsonKey.Results) as? [[String:AnyObject]] { completionHandler(resultsArray: resultsArray, error: nil) } else if let error = error { completionHandler(resultsArray: nil, error: error) } else if let errorMessage = jsonData?.valueForKey(ParseJsonKey.Error) as? String { completionHandler(resultsArray: nil, error: ParseClient.errorForCode(.ParseServerError, message: errorMessage)) } else { completionHandler(resultsArray: nil, error: ParseClient.errorForCode(.ResponseContainedNoResultObject)) } } } else { completionHandler(resultsArray: nil, error: WebClient.errorForCode(.UnableToCreateRequest)) } } // Create an object of the specified class type. // PRE: properties MUST NOT already contain an objectId, createdAt, or updatedAt properties. // className: the object model classname of the data type on Parse // withProperties: key value pair attributes of the new object. // completionHandler - objectId: the ID of the newly create object // completionHandler - createdAt: the time of creation for newly created object. public func createObjectOfClassName(className: String, withProperties properties: [String:AnyObject], completionHandler: (objectId: String?, createdAt: String?, error: NSError?) -> Void) { performHttpMethod(WebClient.HttpPost, ofClassName: className, withProperties: properties) { jsonData, error in if let objectId = jsonData?.valueForKey(ParseJsonKey.ObjectId) as? String, createdAt = jsonData?.valueForKey(ParseJsonKey.CreateAt) as? String { completionHandler(objectId: objectId, createdAt: createdAt, error: nil) } else if let error = error { completionHandler(objectId: nil, createdAt: nil, error: error) } else if let errorMessage = jsonData?.valueForKey(ParseJsonKey.Error) as? String { completionHandler(objectId: nil, createdAt: nil, error: ParseClient.errorForCode(.ParseServerError, message: errorMessage)) } else { let responseError = ParseClient.errorForCode(.ResponseForCreateIsMissingExpectedValues) completionHandler(objectId: nil, createdAt: nil, error: responseError) } } } // Delete an object of the specified class type with the given objectId // className: the object model classname of the data type on Parse public func deleteObjectOfClassName(className: String, objectId: String? = nil, completionHandler: (error: NSError?) -> Void) { performHttpMethod(WebClient.HttpDelete, ofClassName: className, objectId: objectId) { jsonData, error in completionHandler(error: error) } } // Update an object of the specified class type and objectId with the new properties. // className: the object model classname of the data type on Parse // withProperties: key value pair attributes to update the object. // objectId: the unique id of the object to update. // completionHandler - updatedAt: the time object is updated when update successful public func updateObjectOfClassName(className: String, withProperties properties: [String:AnyObject], objectId: String? = nil, completionHandler: (updatedAt: String?, error: NSError?) -> Void) { print("Raw Data: \(properties)") performHttpMethod(WebClient.HttpPut, ofClassName: className, withProperties: properties, objectId: objectId) { jsonData, error in if let updatedAt = jsonData?.valueForKey(ParseJsonKey.UpdatedAt) as? String { completionHandler(updatedAt: updatedAt, error: nil) } else if error != nil { completionHandler(updatedAt: nil, error: error) } else { let responseError = ParseClient.errorForCode(.ResponseForUpdateIsMissingExpectedValues) completionHandler(updatedAt: nil, error: responseError) } } } // Perform an HTTP/HTTPS request with the specified configuration and content. // method: the HTTP method to use // ofClassName: the PARSE classname targeted by the request. // withProperties: the data properties // objectId: the objectId targeted by the request // requestHandler - jsonData: the parsed body content of the response private func performHttpMethod(method: String, ofClassName className: String, withProperties properties: [String:AnyObject] = [String:AnyObject](), objectId: String? = nil, requestHandler: (jsonData: AnyObject?, error: NSError?) -> Void ) { do { let body = try NSJSONSerialization.dataWithJSONObject(properties, options: NSJSONWritingOptions.PrettyPrinted) var targetUrlString = "\(ParseClient.ObjectUrl)/\(className)" if let objectId = objectId { targetUrlString += "/\(objectId)" } if let request = webClient.createHttpRequestUsingMethod(method, forUrlString: targetUrlString, withBody: body, includeHeaders: StandardHeaders) { webClient.executeRequest(request, completionHandler: requestHandler) } else { requestHandler(jsonData: nil, error: WebClient.errorForCode(.UnableToCreateRequest)) } } catch { requestHandler(jsonData: nil, error: ParseClient.errorForCode(ErrorCode.ParseServerError)) } } } // MARK: - Constants extension ParseClient { static let BaseUrl = "https://api.parse.com" static let BasePath = "/1/classes" static let ObjectUrl = BaseUrl + BasePath // use reverse-sort by Updated time as default static let DefaultSortOrder = "-\(ParseJsonKey.UpdatedAt)" struct DateFormat { static let ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SZZZZZ" } struct Locale { static let EN_US_POSIX = "en_US_POSIX" } static var DateFormatter: NSDateFormatter { let dateFormatter = NSDateFormatter() let enUSPosixLocale = NSLocale(localeIdentifier: ParseClient.Locale.EN_US_POSIX) dateFormatter.locale = enUSPosixLocale dateFormatter.dateFormat = ParseClient.DateFormat.ISO8601 return dateFormatter } struct ParseParameter { static let Limit = "limit" static let Skip = "skip" static let Order = "order" static let Where = "where" } struct ParseJsonKey { static let Results = "results" static let Error = "error" static let Count = "count" static let ObjectId = "objectId" static let CreateAt = "createdAt" static let UpdatedAt = "updatedAt" } struct Logic { static let LessThan = "lt" static let GreaterThan = "gt" } } // MARK: - Errors { extension ParseClient { private static let ErrorDomain = "ParseClient" private enum ErrorCode: Int, CustomStringConvertible { case ResponseContainedNoResultObject = 1 case ResponseForCreateIsMissingExpectedValues case ResponseForUpdateIsMissingExpectedValues case ParseServerError var description: String { switch self { case ResponseContainedNoResultObject: return "Server did not send any results." case ResponseForCreateIsMissingExpectedValues: return "Response for Creating Object did not return an error but did not contain expected properties either." case ResponseForUpdateIsMissingExpectedValues: return "Response for Updating Object did not return an error but did not contain expected properties either." default: return "Unknown Error" } } } // createErrorWithCode // helper function to simplify creation of error object private static func errorForCode(code: ErrorCode, var message: String? = nil) -> NSError { if message == nil { message = code.description } let userInfo = [NSLocalizedDescriptionKey : message!] return NSError(domain: ParseClient.ErrorDomain, code: code.rawValue, userInfo: userInfo) } }
mit
7b1354b37e18d8a28f9fc587d54239a7
46.454936
168
0.653039
5.38529
false
false
false
false
Ehrippura/firefox-ios
Client/Frontend/Browser/TopTabsViewController.swift
1
22193
/* 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 WebKit struct TopTabsUX { static let TopTabsViewHeight: CGFloat = 44 static let TopTabsBackgroundColor = UIColor(rgb: 0x2a2a2e) static let TopTabsBackgroundPadding: CGFloat = 35 static let TopTabsBackgroundShadowWidth: CGFloat = 12 static let TabWidth: CGFloat = 190 static let CollectionViewPadding: CGFloat = 15 static let FaderPading: CGFloat = 8 static let SeparatorWidth: CGFloat = 1 static let HighlightLineWidth: CGFloat = 3 static let TabNudge: CGFloat = 1 // Nudge the favicon and close button by 1px static let TabTitleWidth: CGFloat = 110 static let TabTitlePadding: CGFloat = 10 static let AnimationSpeed: TimeInterval = 0.1 static let SeparatorYOffset: CGFloat = 7 static let SeparatorHeight: CGFloat = 32 } protocol TopTabsDelegate: class { func topTabsDidPressTabs() func topTabsDidPressNewTab(_ isPrivate: Bool) func topTabsDidTogglePrivateMode() func topTabsDidChangeTab() } protocol TopTabCellDelegate: class { func tabCellDidClose(_ cell: TopTabCell) } class TopTabsViewController: UIViewController { let tabManager: TabManager weak var delegate: TopTabsDelegate? fileprivate var isPrivate = false let faviconNotification = NSNotification.Name(rawValue: FaviconManager.FaviconDidLoad) lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout()) collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.clipsToBounds = false collectionView.accessibilityIdentifier = "Top Tabs View" return collectionView }() fileprivate lazy var tabsButton: TabsButton = { let tabsButton = TabsButton.tabTrayButton() tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: UIControlEvents.touchUpInside) tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton" return tabsButton }() fileprivate lazy var newTab: UIButton = { let newTab = UIButton.newTabButton() newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: UIControlEvents.touchUpInside) return newTab }() lazy var privateModeButton: PrivateModeButton = { let privateModeButton = PrivateModeButton() privateModeButton.light = true privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: UIControlEvents.touchUpInside) return privateModeButton }() fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = { let delegate = TopTabsLayoutDelegate() delegate.tabSelectionDelegate = self return delegate }() fileprivate var tabsToDisplay: [Tab] { return self.isPrivate ? tabManager.privateTabs : tabManager.normalTabs } // Handle animations. fileprivate var tabStore: [Tab] = [] //the actual datastore fileprivate var pendingUpdatesToTabs: [Tab] = [] //the datastore we are transitioning to fileprivate var needReloads: [Tab?] = [] // Tabs that need to be reloaded fileprivate var isUpdating = false fileprivate var pendingReloadData = false fileprivate var oldTabs: [Tab]? // The last state of the tabs before an animation fileprivate weak var oldSelectedTab: Tab? // Used to select the right tab when transitioning between private/normal tabs init(tabManager: TabManager) { self.tabManager = tabManager super.init(nibName: nil, bundle: nil) collectionView.dataSource = self collectionView.delegate = tabLayoutDelegate [UICollectionElementKindSectionHeader, UICollectionElementKindSectionFooter].forEach { collectionView.register(TopTabsHeaderFooter.self, forSupplementaryViewOfKind: $0, withReuseIdentifier: "HeaderFooter") } NotificationCenter.default.addObserver(self, selector: #selector(TopTabsViewController.reloadFavicons(_:)), name: faviconNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: faviconNotification, object: nil) self.tabManager.removeDelegate(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.tabsToDisplay != self.tabStore { self.reloadData() } } override func viewDidLoad() { super.viewDidLoad() tabManager.addDelegate(self) self.tabStore = self.tabsToDisplay let topTabFader = TopTabFader() view.addSubview(topTabFader) topTabFader.addSubview(collectionView) view.addSubview(tabsButton) view.addSubview(newTab) view.addSubview(privateModeButton) newTab.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(tabsButton.snp.leading).offset(-10) make.size.equalTo(view.snp.height) } tabsButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(view).offset(-10) make.size.equalTo(view.snp.height) } privateModeButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(10) make.size.equalTo(view.snp.height) } topTabFader.snp.makeConstraints { make in make.top.bottom.equalTo(view) make.leading.equalTo(privateModeButton.snp.trailing) make.trailing.equalTo(newTab.snp.leading) } collectionView.snp.makeConstraints { make in make.edges.equalTo(topTabFader) } view.backgroundColor = UIColor(rgb: 0x272727) tabsButton.applyTheme(Theme.NormalMode) if let currentTab = tabManager.selectedTab { applyTheme(currentTab.isPrivate ? Theme.PrivateMode : Theme.NormalMode) } updateTabCount(tabStore.count, animated: false) } func switchForegroundStatus(isInForeground reveal: Bool) { // Called when the app leaves the foreground to make sure no information is inadvertently revealed if let cells = self.collectionView.visibleCells as? [TopTabCell] { let alpha: CGFloat = reveal ? 1 : 0 for cell in cells { cell.titleText.alpha = alpha cell.favicon.alpha = alpha } } } func updateTabCount(_ count: Int, animated: Bool = true) { self.tabsButton.updateTabCount(count, animated: animated) } func tabsTrayTapped() { delegate?.topTabsDidPressTabs() } func newTabTapped() { if pendingReloadData { return } self.delegate?.topTabsDidPressNewTab(self.isPrivate) LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "Add tab button in the URL Bar on iPad" as AnyObject]) } func togglePrivateModeTapped() { if isUpdating || pendingReloadData { return } let isPrivate = self.isPrivate delegate?.topTabsDidTogglePrivateMode() self.pendingReloadData = true // Stops animations from happening let oldSelectedTab = self.oldSelectedTab self.oldSelectedTab = tabManager.selectedTab self.privateModeButton.setSelected(!isPrivate, animated: true) //if private tabs is empty and we are transitioning to it add a tab if tabManager.privateTabs.isEmpty && !isPrivate { tabManager.addTab(isPrivate: true) } //get the tabs from which we will select which one to nominate for tribute (selection) //the isPrivate boolean still hasnt been flipped. (It'll be flipped in the BVC didSelectedTabChange method) let tabs = !isPrivate ? tabManager.privateTabs : tabManager.normalTabs if let tab = oldSelectedTab, tabs.index(of: tab) != nil { tabManager.selectTab(tab) } else { tabManager.selectTab(tabs.last) } } func reloadFavicons(_ notification: Notification) { // Notifications might be called from a different thread. Make sure animations only happen on the main thread. DispatchQueue.main.async { if let tab = notification.object as? Tab, self.tabStore.index(of: tab) != nil { self.needReloads.append(tab) self.performTabUpdates() } } } func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) { assertIsMainThread("Only animate on the main thread") guard let currentTab = tabManager.selectedTab, let index = tabStore.index(of: currentTab), !collectionView.frame.isEmpty else { return } if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame { if centerCell { collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false) } else { // Padding is added to ensure the tab is completely visible (none of the tab is under the fader) let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0) if animated { UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: { self.collectionView.scrollRectToVisible(padFrame, animated: true) }) } else { collectionView.scrollRectToVisible(padFrame, animated: false) } } } } } extension TopTabsViewController: Themeable { func applyTheme(_ themeName: String) { tabsButton.applyTheme(themeName) tabsButton.titleBackgroundColor = view.backgroundColor ?? UIColor(rgb: 0x272727) tabsButton.textColor = UIColor(rgb: 0xb1b1b3) isPrivate = (themeName == Theme.PrivateMode) privateModeButton.styleForMode(privateMode: isPrivate) privateModeButton.tintColor = isPrivate ? UIColor(rgb: 0xf9f9fa) : UIColor(rgb: 0xb1b1b3) privateModeButton.imageView?.tintColor = privateModeButton.tintColor newTab.tintColor = UIColor(rgb: 0xb1b1b3) collectionView.backgroundColor = view.backgroundColor } } extension TopTabsViewController: TopTabCellDelegate { func tabCellDidClose(_ cell: TopTabCell) { // Trying to remove tabs while animating can lead to crashes as indexes change. If updates are happening don't allow tabs to be removed. guard let index = collectionView.indexPath(for: cell)?.item else { return } let tab = tabStore[index] if tabsToDisplay.index(of: tab) != nil { tabManager.removeTab(tab) } } } extension TopTabsViewController: UICollectionViewDataSource { @objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let index = indexPath.item let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TopTabCell.Identifier, for: indexPath) as! TopTabCell tabCell.delegate = self let tab = tabStore[index] tabCell.style = tab.isPrivate ? .dark : .light tabCell.titleText.text = tab.displayTitle if tab.displayTitle.isEmpty { if tab.webView?.url?.baseDomain?.contains("localhost") ?? true { tabCell.titleText.text = Strings.AppMenuNewTabTitleString } else { tabCell.titleText.text = tab.webView?.url?.absoluteDisplayString } tabCell.accessibilityLabel = tab.url?.aboutComponent ?? "" tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tabCell.titleText.text ?? "") } else { tabCell.accessibilityLabel = tab.displayTitle tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tab.displayTitle) } tabCell.selectedTab = (tab == tabManager.selectedTab) if let siteURL = tab.url?.displayURL { tabCell.favicon.setIcon(tab.displayFavicon, forURL: siteURL, completed: { (color, url) in if siteURL == url { tabCell.favicon.image = tabCell.favicon.image?.createScaled(CGSize(width: 15, height: 15)) tabCell.favicon.backgroundColor = color == .clear ? .white : color tabCell.favicon.contentMode = .center } }) } else { tabCell.favicon.image = UIImage(named: "defaultFavicon") tabCell.favicon.contentMode = .scaleAspectFit tabCell.favicon.backgroundColor = .clear } return tabCell } @objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tabStore.count } @objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderFooter", for: indexPath) as! TopTabsHeaderFooter view.arrangeLine(kind) return view } } extension TopTabsViewController: TabSelectionDelegate { func didSelectTabAtIndex(_ index: Int) { let tab = tabStore[index] if tabsToDisplay.index(of: tab) != nil { tabManager.selectTab(tab) } } } // Collection Diff (animations) extension TopTabsViewController { struct TopTabChangeSet { let reloads: Set<IndexPath> let inserts: Set<IndexPath> let deletes: Set<IndexPath> init(reloadArr: [IndexPath], insertArr: [IndexPath], deleteArr: [IndexPath]) { reloads = Set(reloadArr) inserts = Set(insertArr) deletes = Set(deleteArr) } var all: [Set<IndexPath>] { return [inserts, reloads, deletes] } } // create a TopTabChangeSet which is a snapshot of updates to perfrom on a collectionView func calculateDiffWith(_ oldTabs: [Tab], to newTabs: [Tab], and reloadTabs: [Tab?]) -> TopTabChangeSet { let inserts: [IndexPath] = newTabs.enumerated().flatMap { index, tab in if oldTabs.index(of: tab) == nil { return IndexPath(row: index, section: 0) } return nil } let deletes: [IndexPath] = oldTabs.enumerated().flatMap { index, tab in if newTabs.index(of: tab) == nil { return IndexPath(row: index, section: 0) } return nil } // Create based on what is visibile but filter out tabs we are about to insert/delete. let reloads: [IndexPath] = reloadTabs.flatMap { tab in guard let tab = tab, newTabs.index(of: tab) != nil else { return nil } return IndexPath(row: newTabs.index(of: tab)!, section: 0) }.filter { return inserts.index(of: $0) == nil && deletes.index(of: $0) == nil } return TopTabChangeSet(reloadArr: reloads, insertArr: inserts, deleteArr: deletes) } func updateTabsFrom(_ oldTabs: [Tab]?, to newTabs: [Tab], on completion: (() -> Void)? = nil) { assertIsMainThread("Updates can only be performed from the main thread") guard let oldTabs = oldTabs, !self.isUpdating, !self.pendingReloadData else { return } // Lets create our change set let update = self.calculateDiffWith(oldTabs, to: newTabs, and: needReloads) flushPendingChanges() // If there are no changes. We have nothing to do if update.all.every({ $0.isEmpty }) { completion?() return } // The actual update block. We update the dataStore right before we do the UI updates. let updateBlock = { self.tabStore = newTabs self.collectionView.deleteItems(at: Array(update.deletes)) self.collectionView.insertItems(at: Array(update.inserts)) self.collectionView.reloadItems(at: Array(update.reloads)) } //Lets lock any other updates from happening. self.isUpdating = true self.pendingUpdatesToTabs = newTabs // This var helps other mutations that might happen while updating. // The actual update UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: { self.collectionView.performBatchUpdates(updateBlock) }) { (_) in self.isUpdating = false self.pendingUpdatesToTabs = [] // Sometimes there might be a pending reload. Lets do that. if self.pendingReloadData { return self.reloadData() } // There can be pending animations. Run update again to clear them. let tabs = self.oldTabs ?? self.tabStore self.updateTabsFrom(tabs, to: self.tabsToDisplay, on: { if !update.inserts.isEmpty || !update.reloads.isEmpty { self.scrollToCurrentTab() } }) } } fileprivate func flushPendingChanges() { oldTabs = nil needReloads.removeAll() } fileprivate func reloadData() { assertIsMainThread("reloadData must only be called from main thread") if self.isUpdating || self.collectionView.frame == CGRect.zero { self.pendingReloadData = true return } isUpdating = true self.tabStore = self.tabsToDisplay self.newTab.isUserInteractionEnabled = false self.flushPendingChanges() UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: { self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.collectionView.layoutIfNeeded() self.scrollToCurrentTab(true, centerCell: true) }, completion: { (_) in self.isUpdating = false self.pendingReloadData = false self.performTabUpdates() self.newTab.isUserInteractionEnabled = true }) } } extension TopTabsViewController: TabManagerDelegate { // Because we don't know when we are about to transition to private mode // check to make sure that the tab we are trying to add is being added to the right tab group fileprivate func tabsMatchDisplayGroup(_ a: Tab?, b: Tab?) -> Bool { if let a = a, let b = b, a.isPrivate == b.isPrivate { return true } return false } func performTabUpdates() { guard !isUpdating else { return } let fromTabs = !self.pendingUpdatesToTabs.isEmpty ? self.pendingUpdatesToTabs : self.oldTabs self.oldTabs = fromTabs ?? self.tabStore if self.pendingReloadData && !isUpdating { self.reloadData() } else { self.updateTabsFrom(self.oldTabs, to: self.tabsToDisplay) } } // This helps make sure animations don't happen before the view is loaded. fileprivate var isRestoring: Bool { return self.tabManager.isRestoring || self.collectionView.frame == CGRect.zero } func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) { if isRestoring { return } if !tabsMatchDisplayGroup(selected, b: previous) { self.reloadData() } else { self.needReloads.append(selected) self.needReloads.append(previous) performTabUpdates() delegate?.topTabsDidChangeTab() } } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { // We need to store the earliest oldTabs. So if one already exists use that. self.oldTabs = self.oldTabs ?? tabStore } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) { if isRestoring || (tabManager.selectedTab != nil && !tabsMatchDisplayGroup(tab, b: tabManager.selectedTab)) { return } performTabUpdates() } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { // We need to store the earliest oldTabs. So if one already exists use that. self.oldTabs = self.oldTabs ?? tabStore } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) { if isRestoring { return } // If we deleted the last private tab. We'll be switching back to normal browsing. Pause updates till then if self.tabsToDisplay.isEmpty { self.pendingReloadData = true return } // dont want to hold a ref to a deleted tab if tab === oldSelectedTab { oldSelectedTab = nil } performTabUpdates() } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { self.reloadData() } func tabManagerDidAddTabs(_ tabManager: TabManager) { self.reloadData() } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { self.reloadData() } }
mpl-2.0
8e9e22e69ca4e3e83933234773c1b4df
38.559715
168
0.647772
5.180439
false
false
false
false
forwk1990/PropertyExchange
PropertyExchange/YPRightManageViewController.swift
1
2043
// // YPInvestmentManageViewController.swift // PropertyExchange // // Created by 尹攀 on 16/10/16. // Copyright © 2016年 com.itachi. All rights reserved. // import UIKit class YPRightManageViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.setNavigationBar() self.view.addSubview(self.nothingView) } private func setNavigationBarStyle(){ self.navigationController?.navigationBar.setBackgroundImage(UIImage(color:UIColor.white), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage(color: UIColor.colorWithHex(hex: 0xDCDCDC)) self.navigationController?.navigationBar.backgroundColor = UIColor.white } private func setNavigationBar(){ self.setNavigationBarStyle() self.view.backgroundColor = UIColor.colorWithHex(hex: 0xf5f5f5) self.automaticallyAdjustsScrollViewInsets = false //self.edgesForExtendedLayout = UIRectEdge.top self.title = "债权转让" let backButton = UIButton(type: .custom) backButton.addTarget(self, action:#selector(self.backButtonTouched(sender:)), for: .touchUpInside) backButton.setImage(UIImage(named: "后退"), for: .normal) backButton.sizeToFit() let leftBarButton = UIBarButtonItem(customView: backButton) self.navigationItem.leftBarButtonItem = leftBarButton } @objc private func backButtonTouched(sender:UIButton){ _ = self.navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } lazy var nothingView:YPNothingView = { let _nothingView = YPNothingView() _nothingView.frame = CGRect(x: 0, y: -64, width: ScreenWidth, height: ScreenHeight) _nothingView.model = (title:"暂无债权转让项目",image:UIImage(named:"无数据")!,operationTitle:"去投资",controller:YPProjectInverstmentViewController.self) return _nothingView }() }
mit
fc36feddb949accff3bd3d734601fbe3
31.721311
143
0.737976
4.406181
false
false
false
false
ConfusedVorlon/HSTableView
Sources/HSTableView/HSTVSectionInfo.swift
1
2374
// // HSTVSectionInfo.swift // SwiftExperiment // // Created by Rob Jonson on 30/05/2016. // Copyright © 2016 HobbyistSoftware. All rights reserved. // import UIKit open class HSTVSectionInfo: HSTVRowInfo { public static let defaultHeaderHeight:CGFloat = 40 open var headerHeight:CGFloat? // Defaults to 40 if title or header is set, or 0 otherwise open var footerHeight:CGFloat? // Defaults to 0 open var header:UIView? var index=0 public init(table: HSTableView, section: HSTVSection?) { super.init() self.table=table self.section=section } override func nextResponder() -> HSTVRowInfo? { return table.info } func viewForHeaderInSection() -> UIView? { if let header = header { return header } if let title = self.inheritedTitle { let label=UILabel.init() label.text=title label.textAlignment=NSTextAlignment.center label.backgroundColor=UIColor.lightGray if #available(iOS 13.0, *) { label.backgroundColor = UIColor.secondarySystemBackground label.textColor = UIColor.label } return label } return nil } internal lazy var inheritedHeaderHeight : CGFloat? = { return self.inherited({ row -> CGFloat? in let section = row as! HSTVSectionInfo? return section?.headerHeight }) }() internal lazy var inheritedFooterHeight : CGFloat? = { return self.inherited({ row -> CGFloat? in let section = row as! HSTVSectionInfo? return section?.footerHeight }) }() func tableViewHeightForHeaderInSection() -> CGFloat { //If we don't have a header, and we don't have a title to auto-generate one, then zero height if header == nil && self.inheritedTitle == nil { return 0 } return inheritedHeaderHeight ?? HSTVSectionInfo.defaultHeaderHeight } func tableViewHeightForFooterInSection() -> CGFloat { if let height = inheritedFooterHeight { return height } else { return 0 } } }
mit
bdb7ff28a121dd6472fd60fc4880fadd
25.076923
101
0.569322
5.215385
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/CameraViews.swift
1
14254
// // CameraViews.swift // Telegram // // Created by Mikhail Filimonov on 14/08/2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import TelegramVoip enum CameraState : Equatable { case notInited case initializing case inited } final class OutgoingVideoView : Control { private var progressIndicator: ProgressIndicator? = nil private let videoContainer = Control() var isMirrored: Bool = false { didSet { CATransaction.begin() if isMirrored { let rect = videoContainer.bounds var fr = CATransform3DIdentity fr = CATransform3DTranslate(fr, rect.width / 2, 0, 0) fr = CATransform3DScale(fr, -1, 1, 1) fr = CATransform3DTranslate(fr, -(rect.width / 2), 0, 0) videoContainer.layer?.sublayerTransform = fr } else { videoContainer.layer?.sublayerTransform = CATransform3DIdentity } CATransaction.commit() } } var isMoved: Bool = false var updateAspectRatio:((Float)->Void)? = nil let _cameraInitialized: ValuePromise<CameraState> = ValuePromise(.notInited, ignoreRepeated: true) var cameraInitialized: Signal<CameraState, NoError> { return _cameraInitialized.get() } var firstFrameHandler:(()->Void)? = nil var videoView: (OngoingCallContextPresentationCallVideoView?, Bool)? { didSet { self._cameraInitialized.set(.initializing) if let value = videoView, let videoView = value.0 { videoView.setVideoContentMode(.resizeAspectFill) videoContainer.addSubview(videoView.view) videoView.view.frame = self.bounds videoView.view.layer?.cornerRadius = .cornerRadius let oldView = oldValue?.0?.view videoView.setOnFirstFrameReceived({ [weak self, weak oldView] aspectRatio in guard let `self` = self else { return } self._cameraInitialized.set(.inited) if !self._hidden { self.backgroundColor = .clear oldView?.removeFromSuperview() if let progressIndicator = self.progressIndicator { self.progressIndicator = nil progressIndicator.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak progressIndicator] _ in progressIndicator?.removeFromSuperview() }) } self.updateAspectRatio?(aspectRatio) } self.firstFrameHandler?() }) if !value.1 { self._cameraInitialized.set(.inited) } } else { self._cameraInitialized.set(.notInited) } needsLayout = true } } private var _hidden: Bool = false var isViewHidden: Bool { return _hidden } func unhideView(animated: Bool) { if let view = videoView?.0?.view, _hidden { subviews.enumerated().forEach { _, view in if !(view is Control) { view.removeFromSuperview() } } videoContainer.addSubview(view, positioned: .below, relativeTo: self.subviews.first) view.layer?.animateScaleCenter(from: 0.2, to: 1.0, duration: 0.2) view.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } _hidden = false } func hideView(animated: Bool) { if let view = self.videoView?.0?.view, !_hidden { view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] completed in view?.removeFromSuperview() view?.layer?.removeAllAnimations() }) view.layer?.animateScaleCenter(from: 1, to: 0.2, duration: 0.2) } _hidden = true } override var isEventLess: Bool { didSet { self.userInteractionEnabled = !isEventLess //overlay.isEventLess = isEventLess } } static var defaultSize: NSSize = NSMakeSize(floor(100 * System.aspectRatio), 100) enum ResizeDirection { case topLeft case topRight case bottomLeft case bottomRight } let overlay: Control = Control() private var disabledView: NSVisualEffectView? private var notAvailableView: TextView? private var animation:DisplayLinkAnimator? = nil required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.overlay.forceMouseDownCanMoveWindow = true self.layer?.cornerRadius = .cornerRadius self.layer?.masksToBounds = true self.addSubview(videoContainer) self.addSubview(overlay) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { super.layout() self.videoContainer.frame = bounds self.overlay.frame = bounds self.videoView?.0?.view.frame = bounds self.progressIndicator?.center() self.disabledView?.frame = bounds let isMirrored = self.isMirrored self.isMirrored = isMirrored if let textView = notAvailableView { textView.resize(frame.width - 40) textView.center() } } func setIsPaused(_ paused: Bool, animated: Bool) { if paused { if disabledView == nil { let current = NSVisualEffectView() current.material = .dark current.state = .active current.blendingMode = .withinWindow current.wantsLayer = true current.layer?.cornerRadius = .cornerRadius current.frame = bounds self.disabledView = current self.addSubview(current, positioned: .below, relativeTo: overlay) if animated { current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } else { self.disabledView?.frame = bounds } } else { if let disabledView = self.disabledView { self.disabledView = nil if animated { disabledView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak disabledView] _ in disabledView?.removeFromSuperview() }) } else { disabledView.removeFromSuperview() } } } } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize) } private(set) var savedFrame: NSRect? = nil func updateFrame(_ frame: NSRect, animated: Bool) { if self.savedFrame != frame && animation == nil { let duration: Double = 0.15 if animated { let fromFrame = self.frame let toFrame = frame let animation = DisplayLinkAnimator(duration: duration, from: 0.0, to: 1.0, update: { [weak self] value in let x = fromFrame.minX - (fromFrame.minX - toFrame.minX) * value let y = fromFrame.minY - (fromFrame.minY - toFrame.minY) * value let w = fromFrame.width - (fromFrame.width - toFrame.width) * value let h = fromFrame.height - (fromFrame.height - toFrame.height) * value let updated = NSMakeRect(x, y, w, h) self?.frame = updated }, completion: { [weak self] in guard let `self` = self else { return } self.animation = nil self.frame = frame self.savedFrame = frame }) self.animation = animation } else { self.frame = frame self.animation = nil } } updateCursorRects() savedFrame = frame } private func updateCursorRects() { } override func cursorUpdate(with event: NSEvent) { super.cursorUpdate(with: event) updateCursorRects() } func runResizer(at point: NSPoint) -> ResizeDirection? { let rects: [(NSRect, ResizeDirection)] = [(NSMakeRect(0, frame.height - 10, 10, 10), .bottomLeft), (NSMakeRect(frame.width - 10, 0, 10, 10), .topRight), (NSMakeRect(0, 0, 10, 10), .topLeft), (NSMakeRect(frame.width - 10, frame.height - 10, 10, 10), .bottomRight)] for rect in rects { if NSPointInRect(point, rect.0) { return rect.1 } } return nil } override var mouseDownCanMoveWindow: Bool { return isEventLess } } final class IncomingVideoView : Control { var updateAspectRatio:((Float)->Void)? = nil let _cameraInitialized: ValuePromise<CameraState> = ValuePromise(.notInited, ignoreRepeated: true) var cameraInitialized: Signal<CameraState, NoError> { return _cameraInitialized.get() } var firstFrameHandler:(()->Void)? = nil private var disabledView: NSVisualEffectView? var videoView: OngoingCallContextPresentationCallVideoView? { didSet { _cameraInitialized.set(.initializing) if let videoView = videoView { addSubview(videoView.view, positioned: .below, relativeTo: self.subviews.first) videoView.view.background = .clear videoView.setOnFirstFrameReceived({ [weak self, weak oldValue] aspectRatio in if let videoView = oldValue { videoView.view.removeFromSuperview() } self?._cameraInitialized.set(.inited) self?.videoView?.view.background = .black self?.updateAspectRatio?(aspectRatio) self?.firstFrameHandler?() }) } else { _cameraInitialized.set(.notInited) self.firstFrameHandler?() } needsLayout = true } } required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.layer?.cornerRadius = .cornerRadius } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { super.layout() for subview in subviews { subview.frame = bounds } if let textView = disabledView?.subviews.first as? TextView { let layout = textView.textLayout layout?.measure(width: frame.width - 40) textView.update(layout) textView.center() } } func setIsPaused(_ paused: Bool, peer: TelegramUser?, animated: Bool) { if paused { if disabledView == nil { let current = NSVisualEffectView() current.material = .dark current.state = .active current.blendingMode = .withinWindow current.wantsLayer = true current.frame = bounds self.disabledView = current addSubview(current) if animated { current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } else { self.disabledView?.frame = bounds } } else { if let disabledView = self.disabledView { self.disabledView = nil if animated { disabledView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak disabledView] _ in disabledView?.removeFromSuperview() }) } else { disabledView.removeFromSuperview() } } } needsLayout = true } private var _hidden: Bool = false var isViewHidden: Bool { return _hidden } func unhideView(animated: Bool) { if let view = videoView?.view, _hidden { self.subviews.enumerated().forEach { _, view in if !(view is Control) { view.removeFromSuperview() } } addSubview(view, positioned: .below, relativeTo: self.subviews.first) view._change(opacity: 1, animated: animated) // view.layer?.animateScaleCenter(from: 0.2, to: 1.0, duration: 0.2) } _hidden = false } func hideView(animated: Bool) { if let view = self.videoView?.view, !_hidden { view._change(opacity: 1, animated: animated, removeOnCompletion: false, completion: { [weak view] completed in view?.removeFromSuperview() view?.layer?.removeAllAnimations() }) // view.layer?.animateScaleCenter(from: 1, to: 0.2, duration: 0.2) } _hidden = true } override var mouseDownCanMoveWindow: Bool { return true } }
gpl-2.0
e62db6a525caf747a275427baed8117e
32.935714
167
0.521785
5.413217
false
false
false
false
practicalswift/swift
test/type/infer/local_variables.swift
36
659
// RUN: %target-typecheck-verify-swift func dict_to_array(_: Dictionary<String, Int>) -> [(String, Int)] { return Array<(String, Int)>() } func infer_type(_ i: Int, f: Float) { // Simple types var i2 = i i2 = i // Tuples var (i3, f2) = (i, f) var i_and_f = (i, f) i3 = i2 f2 = f i_and_f = (i3, f2) _ = i_and_f } func infer_generic_args() { // Simple types var x : Dictionary = ["Hello" : 1] var i : Int = x["Hello"]! // Tuples var (d, s) : (Dictionary, Array) = ( ["Hello" : 1], [1, 2, 3] ) i = d["Hello"]! i = s[i] // Function types let f : (Dictionary) -> Array = dict_to_array _ = f(d) as [(String, Int)] }
apache-2.0
70583b98913d78895e7493ebebcc7092
17.828571
67
0.525038
2.564202
false
false
false
false
huangboju/Moots
UICollectionViewLayout/MultiDirectionCollectionView-master/MultiDirectionCollectionView/CustomCollectionViewLayout.swift
2
7220
import UIKit class CustomCollectionViewLayout: UICollectionViewLayout { // Used for calculating each cells CGRect on screen. // CGRect will define the Origin and Size of the cell. let CELL_HEIGHT = 30.0 let CELL_WIDTH = 100.0 let STATUS_BAR = UIApplication.shared.statusBarFrame.height // Dictionary to hold the UICollectionViewLayoutAttributes for // each cell. The layout attribtues will define the cell's size // and position (x, y, and z index). I have found this process // to be one of the heavier parts of the layout. I recommend // holding onto this data after it has been calculated in either // a dictionary or data store of some kind for a smooth performance. var cellAttrsDictionary = Dictionary<IndexPath, UICollectionViewLayoutAttributes>() // Defines the size of the area the user can move around in // within the collection view. var contentSize = CGSize.zero // Used to determine if a data source update has occured. // Note: The data source would be responsible for updating // this value if an update was performed. var dataSourceDidUpdate = true override var collectionViewContentSize : CGSize { return self.contentSize } override func prepare() { // Only update header cells. if !dataSourceDidUpdate { // Determine current content offsets. let xOffset = collectionView!.contentOffset.x let yOffset = collectionView!.contentOffset.y if let sectionCount = collectionView?.numberOfSections, sectionCount > 0 { for section in 0...sectionCount-1 { // Confirm the section has items. if let rowCount = collectionView?.numberOfItems(inSection: section), rowCount > 0 { // Update all items in the first row. if section == 0 { for item in 0...rowCount-1 { // Build indexPath to get attributes from dictionary. let indexPath = IndexPath(item: item, section: section) // Update y-position to follow user. if let attrs = cellAttrsDictionary[indexPath] { var frame = attrs.frame // Also update x-position for corner cell. if item == 0 { frame.origin.x = xOffset } frame.origin.y = yOffset attrs.frame = frame } } // For all other sections, we only need to update // the x-position for the fist item. } else { // Build indexPath to get attributes from dictionary. let indexPath = IndexPath(item: 0, section: section) // Update y-position to follow user. if let attrs = cellAttrsDictionary[indexPath] { var frame = attrs.frame frame.origin.x = xOffset attrs.frame = frame } } // else } // num of items in section > 0 } // sections for loop } // num of sections > 0 // Do not run attribute generation code // unless data source has been updated. return } // Acknowledge data source change, and disable for next time. dataSourceDidUpdate = false // Cycle through each section of the data source. if let sectionCount = collectionView?.numberOfSections, sectionCount > 0 { for section in 0...sectionCount-1 { // Cycle through each item in the section. if let rowCount = collectionView?.numberOfItems(inSection: section), rowCount > 0 { for item in 0...rowCount-1 { // Build the UICollectionVieLayoutAttributes for the cell. let cellIndex = IndexPath(item: item, section: section) let xPos = Double(item) * CELL_WIDTH let yPos = Double(section) * CELL_HEIGHT let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: cellIndex) cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT) // Determine zIndex based on cell type. if section == 0 && item == 0 { cellAttributes.zIndex = 4 } else if section == 0 { cellAttributes.zIndex = 3 } else if item == 0 { cellAttributes.zIndex = 2 } else { cellAttributes.zIndex = 1 } // Save the attributes. cellAttrsDictionary[cellIndex] = cellAttributes } } } } // Update content size. let contentWidth = Double(collectionView!.numberOfItems(inSection: 0)) * CELL_WIDTH let contentHeight = Double(collectionView!.numberOfSections) * CELL_HEIGHT self.contentSize = CGSize(width: contentWidth, height: contentHeight) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { // Create an array to hold all elements found in our current view. var attributesInRect = [UICollectionViewLayoutAttributes]() // Check each element to see if it should be returned. for cellAttributes in cellAttrsDictionary.values { if rect.intersects(cellAttributes.frame) { attributesInRect.append(cellAttributes) } } // Return list of elements. return attributesInRect } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return cellAttrsDictionary[indexPath]! } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } }
mit
370b6c8e2a96e35cbe23a4ea688b5db5
43.02439
111
0.490582
6.817753
false
false
false
false
wangchong321/tucao
WCWeiBo/WCWeiBo/Classes/Model/NewFeature/NewFeatureCollectionViewController.swift
1
3375
// // NewFeatureCollectionViewController.swift // WCWeiBo // // Created by 王充 on 15/5/14. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class NewFeatureCollectionViewController: UICollectionViewController { @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) flowLayout.itemSize = view.frame.size } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// 设置布局 /// 图片总数 let imageNumber = 4 // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return imageNumber } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("NewFeatureCell", forIndexPath: indexPath) as! NewFeatureCollectionViewCell cell.imageIndex = indexPath.item return cell } override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let path = collectionView.indexPathsForVisibleItems().last as! NSIndexPath if path.item == imageNumber - 1 { let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCollectionViewCell cell.showStartButton() } } //: 懒加载数组怎么搞 // lazy var images: NSArray? = { // let imageNumber = 4 // let array = NSMutableArray() // for var i = 0 ; i< imageNumber ;i++ { // let imgString = "new_feature_" + \(i) // // } // return array // }() } class NewFeatureCollectionViewCell : UICollectionViewCell{ @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var startBtn: UIButton! @IBAction func showStartClick() { // println(__FUNCTION__) NSNotificationCenter.defaultCenter().postNotificationName(WCSwitchRootViewControllerNotification, object: "Main") } var imageIndex: Int = 0{ didSet{ var imageName = "new_feature_"+"\(imageIndex + 1)" imageView.image = UIImage(named:imageName) startBtn.hidden = true } } func showStartButton() { startBtn.hidden = false /// 设置动画效果 startBtn.transform = CGAffineTransformMakeScale(0, 0) /// duration: 动画时长 /// delay: 动画延迟多长时间执行 /// Damping : 弹簧系数 0~1 /// Velocity : 弹簧起始发力速度 UIView.animateWithDuration(2.0, delay: 0, usingSpringWithDamping: 0.1, initialSpringVelocity: 15.0, options: nil, animations: { () -> Void in self.startBtn.transform = CGAffineTransformMakeScale(1.0, 1.0) }) { (_) -> Void in println("动画完成") } } }
mit
e90822fcdc02106bc537f40524ea8b5d
31.65
160
0.645942
5.157978
false
false
false
false
nakiostudio/EasyPeasy
EasyPeasy/PositionAttribute+UIKit.swift
1
11318
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if os(iOS) || os(tvOS) import UIKit /** PositionAttribute extension adding some convenience methods to operate with UIKit elements as `UIViews` or `UILayoutGuides` */ public extension PositionAttribute { /** Establishes a position relationship between the `UIView` the attribute is applied to and the `UIView` passed as parameter. It's also possible to link this relationship to a particular attribute of the `view` parameter by supplying `attribute`. - parameter view: The reference view - parameter attribute: The attribute of `view` we are establishing the relationship to - returns: The current `Attribute` instance */ @discardableResult func to(_ view: UIView, _ attribute: ReferenceAttribute? = nil) -> Self { self.referenceItem = view self.referenceAttribute = attribute return self } /** Establishes a position relationship between the `UIView` the attribute is applied to and the `UILayoutSupport` passed as parameter. It's also possible to link this relationship to a particular attribute of the `layoutSupport` parameter by supplying `attribute`. - parameter layoutSupport: The reference `UILayoutSupport` - parameter attribute: The attribute of `view` we are establishing the relationship to - returns: The current `Attribute` instance */ @discardableResult func to(_ layoutSupport: UILayoutSupport, _ attribute: ReferenceAttribute? = nil) -> Self { self.referenceItem = layoutSupport self.referenceAttribute = attribute return self } /** Establishes a position relationship between the `UIView` the attribute is applied to and the `UILayoutGuide` passed as parameter. It's also possible to link this relationship to a particular attribute of the `view` parameter by supplying `attribute`. - parameter layoutGuide: The reference `UILayoutGuide` - parameter attribute: The attribute of `view` we are establishing the relationship to - returns: The current `Attribute` instance */ @available(iOS 9.0, *) @discardableResult func to(_ layoutGuide: UILayoutGuide, _ attribute: ReferenceAttribute? = nil) -> Self { self.referenceItem = layoutGuide self.referenceAttribute = attribute return self } } /** The object’s left margin. For UIView objects, the margins are defined by their layoutMargins property */ public class LeftMargin: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .leftMargin } } /** The object’s right margin. For UIView objects, the margins are defined by their layoutMargins property */ public class RightMargin: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .rightMargin } } /** The object’s top margin. For UIView objects, the margins are defined by their layoutMargins property */ public class TopMargin: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .topMargin } } /** The object’s bottom margin. For UIView objects, the margins are defined by their layoutMargins property */ public class BottomMargin: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .bottomMargin } } /** The object’s leading margin. For UIView objects, the margins are defined by their layoutMargins property */ public class LeadingMargin: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .leadingMargin } } /** The object’s trailing margin. For UIView objects, the margins are defined by their layoutMargins property */ public class TrailingMargin: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .trailingMargin } } /** The center along the x-axis between the object’s left and right margin. For UIView objects, the margins are defined by their layoutMargins property */ public class CenterXWithinMargins: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .centerXWithinMargins } } /** The center along the y-axis between the object’s top and bottom margin. For UIView objects, the margins are defined by their layoutMargins property */ public class CenterYWithinMargins: PositionAttribute { /// `Attribute` applied to the view public override var createAttribute: ReferenceAttribute { return .centerYWithinMargins } } /** The object’s margins. For UIView objects, the margins are defined by their layoutMargins property */ public class Margins: CompoundAttribute { /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with `constant = 0.0`, `multiplier = 1.0` and `RelatedBy = .Equal` - returns: the `CompoundAttribute` instance created */ public override init() { super.init() self.attributes = [ TopMargin(), LeftMargin(), RightMargin(), BottomMargin() ] } /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with `constant = value`, `multiplier = 1.0` and `RelatedBy = .Equal` - parameter value: `constant` of the constraint - returns: the `CompoundAttribute` instance created */ public override init(_ value: CGFloat) { super.init() self.attributes = [ TopMargin(value), LeftMargin(value), RightMargin(value), BottomMargin(value) ] } /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with `constant`, `multiplier` and `RelatedBy` properties defined by the `Constant` supplied - parameter constant: `Constant` struct aggregating `constant`, `multiplier` and `relatedBy` properties - returns: the `CompoundAttribute` instance created */ public override init(_ constant: Constant) { super.init() self.attributes = [ TopMargin(constant), LeftMargin(constant), RightMargin(constant), BottomMargin(constant) ] } /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with the `constant` properties specified by the `UIEdgeInsets` parameter, `multiplier = 1.0` and `RelatedBy = .Equal` - parameter edgeInsets: `UIEdgeInsets` that gives value to the `constant` properties of each one of the sub `Attribute` objects - returns: the `CompoundAttribute` instance created */ public init(_ edgeInsets: Insets) { super.init() self.attributes = [ TopMargin(CGFloat(edgeInsets.top)), LeftMargin(CGFloat(edgeInsets.left)), RightMargin(CGFloat(edgeInsets.right)), BottomMargin(CGFloat(edgeInsets.bottom)) ] } } /** The center along the x-axis between the object’s left and right margin. For UIView objects, the margins are defined by their layoutMargins property */ public class CenterWithinMargins: CompoundAttribute { /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with `constant = 0.0`, `multiplier = 1.0` and `RelatedBy = .Equal` - returns: the `CompoundAttribute` instance created */ public override init() { super.init() self.attributes = [ CenterXWithinMargins(), CenterYWithinMargins() ] } /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with `constant = value`, `multiplier = 1.0` and `RelatedBy = .Equal` - parameter value: `constant` of the constraint - returns: the `CompoundAttribute` instance created */ public override init(_ value: CGFloat) { super.init() self.attributes = [ CenterXWithinMargins(value), CenterYWithinMargins(value) ] } /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with `constant`, `multiplier` and `RelatedBy` properties defined by the `Constant` supplied - parameter constant: `Constant` struct aggregating `constant`, `multiplier` and `relatedBy` properties - returns: the `CompoundAttribute` instance created */ public override init(_ constant: Constant) { super.init() self.attributes = [ CenterXWithinMargins(constant), CenterYWithinMargins(constant) ] } /** Initializer that creates the sub `Attribute` objects shaping the `CompoundAttribute` object with the `constant` properties specified by the `CGPoint` parameter, `multiplier = 1.0` and `RelatedBy = .Equal` - parameter point: `CGPoint` that gives value to the `constant` properties of each one of the sub `Attribute` objects - returns: the `CompoundAttribute` instance created */ public init(_ point: CGPoint) { super.init() self.attributes = [ CenterXWithinMargins(CGFloat(point.x)), CenterYWithinMargins(CGFloat(point.y)) ] } } extension Edges { @available(iOS 9.0, *) public func to(_ layoutGuide: UILayoutGuide) -> Edges { self.attributes = [ Top().to(layoutGuide, .top), Left().to(layoutGuide, .left), Right().to(layoutGuide, .right), Bottom().to(layoutGuide, .bottom), ] return self } public func to(_ view: UIView) -> Edges { self.attributes = [ Top().to(view, .top), Left().to(view, .left), Right().to(view, .right), Bottom().to(view, .bottom), ] return self } } #endif
mit
d7ab9c243987f4adabdea1e5687f57c4
31.096591
114
0.645335
5.147153
false
false
false
false
dxdp/Stage
Stage/ViewHierarchyNode.swift
1
1766
// // ViewHierarchyNode.swift // Stage // // Copyright © 2016 David Parton // // 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 class StageViewHierarchyNode { let name: String let indentLevel: Int var children: [StageViewHierarchyNode] = [] weak var parent: StageViewHierarchyNode? init(name: String, indentLevel: Int) { self.name = name self.indentLevel = indentLevel } func addChild(_ name: String, indentLevel: Int) -> StageViewHierarchyNode { assert(indentLevel > self.indentLevel) let subnode = StageViewHierarchyNode(name: name, indentLevel: indentLevel) subnode.parent = self children.append(subnode) return subnode } }
mit
f18bb188e497992f770b4a2254bcccfa
41.02381
105
0.729178
4.537275
false
false
false
false
mightydeveloper/swift
stdlib/public/SDK/UIKit/UIKit.swift
5
7406
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation @_exported import UIKit //===----------------------------------------------------------------------===// // Equatable types. //===----------------------------------------------------------------------===// @_transparent // @fragile @warn_unused_result public func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool { return lhs.top == rhs.top && lhs.left == rhs.left && lhs.bottom == rhs.bottom && lhs.right == rhs.right } extension UIEdgeInsets : Equatable {} @_transparent // @fragile @warn_unused_result public func == (lhs: UIOffset, rhs: UIOffset) -> Bool { return lhs.horizontal == rhs.horizontal && lhs.vertical == rhs.vertical } extension UIOffset : Equatable {} // These are un-imported macros in UIKit. //===----------------------------------------------------------------------===// // UIDeviceOrientation //===----------------------------------------------------------------------===// #if !os(watchOS) && !os(tvOS) public extension UIDeviceOrientation { var isLandscape: Bool { get { return self == .LandscapeLeft || self == .LandscapeRight } } var isPortrait: Bool { get { return self == .Portrait || self == .PortraitUpsideDown } } var isFlat: Bool { get { return self == .FaceUp || self == .FaceDown } } var isValidInterfaceOrientation: Bool { get { switch (self) { case .Portrait, .PortraitUpsideDown, .LandscapeLeft, .LandscapeRight: return true default: return false } } } } @warn_unused_result public func UIDeviceOrientationIsLandscape( orientation: UIDeviceOrientation ) -> Bool { return orientation.isLandscape } @warn_unused_result public func UIDeviceOrientationIsPortrait( orientation: UIDeviceOrientation ) -> Bool { return orientation.isPortrait } @warn_unused_result public func UIDeviceOrientationIsValidInterfaceOrientation( orientation: UIDeviceOrientation) -> Bool { return orientation.isValidInterfaceOrientation } #endif //===----------------------------------------------------------------------===// // UIInterfaceOrientation //===----------------------------------------------------------------------===// #if !os(watchOS) && !os(tvOS) public extension UIInterfaceOrientation { var isLandscape: Bool { get { return self == .LandscapeLeft || self == .LandscapeRight } } var isPortrait: Bool { get { return self == .Portrait || self == .PortraitUpsideDown } } } @warn_unused_result public func UIInterfaceOrientationIsPortrait( orientation: UIInterfaceOrientation) -> Bool { return orientation.isPortrait } @warn_unused_result public func UIInterfaceOrientationIsLandscape( orientation: UIInterfaceOrientation ) -> Bool { return orientation.isLandscape } #endif // Overlays for variadic initializers. #if !os(watchOS) && !os(tvOS) public extension UIActionSheet { convenience init(title: String?, delegate: UIActionSheetDelegate?, cancelButtonTitle: String?, destructiveButtonTitle: String?, // Hack around overload ambiguity with non-variadic constructor. // <rdar://problem/16704770> otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...) { self.init(title: title, delegate: delegate, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle) self.addButtonWithTitle(firstButtonTitle) for buttonTitle in moreButtonTitles { self.addButtonWithTitle(buttonTitle) } } } #endif #if !os(watchOS) && !os(tvOS) public extension UIAlertView { convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, // Hack around overload ambiguity with non-variadic constructor. // <rdar://problem/16704770> otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...) { self.init(title: title, message: message, delegate: delegate, cancelButtonTitle: cancelButtonTitle) self.addButtonWithTitle(firstButtonTitle) for buttonTitle in moreButtonTitles { self.addButtonWithTitle(buttonTitle) } } } #endif #if !os(watchOS) struct _UIViewMirror : _MirrorType { static var _views = NSMutableSet() var _v : UIView init(_ v : UIView) { _v = v } var value: Any { get { return _v } } var valueType: Any.Type { get { return (_v as Any).dynamicType } } var objectIdentifier: ObjectIdentifier? { get { return .None } } var count: Int { get { return 0 } } subscript(_: Int) -> (String, _MirrorType) { _preconditionFailure("_MirrorType access out of bounds") } var summary: String { get { return "" } } var quickLookObject: PlaygroundQuickLook? { // iOS 7 or greater only var result: PlaygroundQuickLook? = nil switch _UIViewMirror._views.member(_v) { case nil: _UIViewMirror._views.addObject(_v) let bounds = _v.bounds // in case of an empty rectangle abort the logging if (bounds.size.width == 0) || (bounds.size.height == 0) { return nil } UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) // UIKit is about to update this to be optional, so make it work // with both older and newer SDKs. (In this context it should always // be present.) let ctx: CGContext! = UIGraphicsGetCurrentContext() UIColor(white:1.0, alpha:0.0).set() CGContextFillRect(ctx, bounds) _v.layer.renderInContext(ctx) let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() result = .Some(.View(image)) _UIViewMirror._views.removeObject(_v) default: () } return result } var disposition : _MirrorDisposition { get { return .Aggregate } } } extension UIView : _Reflectable { /// Returns a mirror that reflects `self`. public func _getMirror() -> _MirrorType { return _UIViewMirror(self) } } #endif extension UIColor : _ColorLiteralConvertible { public required convenience init(colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) { self.init(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha)) } } public typealias _ColorLiteralType = UIColor extension UIImage : _ImageLiteralConvertible { private convenience init!(failableImageLiteral name: String) { self.init(named: name) } public required convenience init(imageLiteral name: String) { self.init(failableImageLiteral: name) } } public typealias _ImageLiteralType = UIImage
apache-2.0
9644125646506db5d7613c49e7a4447c
27.159696
80
0.60505
5.048398
false
false
false
false
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/Features/CacheSystem/Extensions/ExtensionURLRequest.swift
1
2076
// // ExtensionURLRequest.swift // // Copyright (c) 2020 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation extension Foundation.URLRequest { var cld_URLRequestWithoutFragment : URLRequest { guard let URLObject = url else { return self } var request = URLRequest(url: URLObject.cld_URLBasePathWithoutFragment) request.cachePolicy = cachePolicy request.timeoutInterval = timeoutInterval request.mainDocumentURL = mainDocumentURL request.networkServiceType = networkServiceType request.allowsCellularAccess = allowsCellularAccess request.httpMethod = httpMethod request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = httpBody request.httpBodyStream = httpBodyStream request.httpShouldHandleCookies = httpShouldHandleCookies request.httpShouldUsePipelining = httpShouldUsePipelining return request } }
mit
cf8296445478ae439c6c1e1e8812be45
44.130435
82
0.729287
5.038835
false
false
false
false
wordlessj/Bamboo
Tests/Auto/ItemsChain/ItemsSizeTests.swift
1
2474
// // ItemsSizeTests.swift // Bamboo // // Copyright (c) 2017 Javier Zhang (https://wordlessj.github.io/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest import Bamboo class ItemsSizeTests: BaseTestCase { func testWidth() { let constraints = subviews.bb.width(value).constraints let testConstraints = subviews.map { NSLayoutConstraint(item: $0, dimension: .width, constant: value) } XCTAssertEqual(constraints, testConstraints) } func testHeight() { let constraints = subviews.bb.height(value).constraints let testConstraints = subviews.map { NSLayoutConstraint(item: $0, dimension: .height, constant: value) } XCTAssertEqual(constraints, testConstraints) } func testSize() { let constraints = subviews.bb.size().constraints let testConstraints = betweenConstraints(.width) + betweenConstraints(.height) XCTAssertEqual(constraints, testConstraints) } func testSizeWithValues() { let width: CGFloat = 2 let height: CGFloat = 3 let constraints = subviews.bb.size(width: width, height: height).constraints let testConstraints = subviews.flatMap { [NSLayoutConstraint(item: $0, dimension: .width, constant: width), NSLayoutConstraint(item: $0, dimension: .height, constant: height)] } XCTAssertEqual(constraints, testConstraints) } }
mit
144706bfc16dbca7d648723310d85461
41.655172
112
0.710186
4.581481
false
true
false
false
austinzheng/swift
test/SILOptimizer/merge_exclusivity.swift
4
11287
// RUN: %target-swift-frontend -O -enforce-exclusivity=checked -emit-sil -primary-file %s | %FileCheck %s --check-prefix=TESTSIL // REQUIRES: optimized_stdlib,asserts // REQUIRES: PTRSIZE=64 public var check: UInt64 = 0 @inline(never) func sum(_ x: UInt64, _ y: UInt64) -> UInt64 { return x &+ y } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest1yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb5 // TESTSIL: [[B2:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb6 // TESTSIL: [[B3:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL: bb7 // TESTSIL: [[B4:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B4]] // TESTSIL: store {{.*}} to [[B4]] // TESTSIL: end_access [[B4]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest1yySiF' @inline(never) public func MergeTest1(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) if (e == 0) { check = sum(check, UInt64(1)) } else { check = sum(check, UInt64(2)) } } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest2yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb6 // TESTSIL: [[B2:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb7 // TESTSIL: [[B3:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest2yySiF' @inline(never) public func MergeTest2(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { if (e == 0) { check = sum(check, UInt64(1)) } else { check = sum(check, UInt64(2)) } } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest3yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest3yySiF' @inline(never) public func MergeTest3(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest4yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb7 // TESTSIL: [[B2:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb8 // TESTSIL: [[B3:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest4yySiF' @inline(never) public func MergeTest4(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { if (e == 0) { check = sum(check, UInt64(1)) } check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest5yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL: bb6 // TESTSIL: [[B2:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B2]] // TESTSIL: store {{.*}} to [[B2]] // TESTSIL: end_access [[B2]] // TESTSIL: bb7 // TESTSIL: [[B3:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B3]] // TESTSIL: store {{.*}} to [[B3]] // TESTSIL: end_access [[B3]] // TESTSIL: bb8 // TESTSIL: [[B4:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL-NEXT: load [[B4]] // TESTSIL: store {{.*}} to [[B4]] // TESTSIL: end_access [[B4]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest5yySiF' @inline(never) public func MergeTest5(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { if (e == 0) { check = sum(check, UInt64(1)) } else { check = sum(check, UInt64(2)) } check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest6yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest6yySiF' @inline(never) public func MergeTest6(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { check = sum(check, UInt64(e)) } check = sum(check, UInt64(e)) } } } @inline(never) public func foo() { } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest7yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest7yySiF' @inline(never) public func MergeTest7(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { foo() } check = sum(check, UInt64(e)) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity10MergeTest8yySiF : $@convention(thin) // TESTSIL: bb0 // TESTSIL: [[GLOBALVAR:%.*]] = global_addr @$s17merge_exclusivity5checks6UInt64Vvp // TESTSIL: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[GLOBALVAR]] // TESTSIL: end_access [[B1]] // TESTSIL-NOT: begin_access // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity10MergeTest8yySiF' @inline(never) public func MergeTest8(_ N: Int) { let range = 0..<10000 check = 0 for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { foo() } check = sum(check, UInt64(e)) } } for _ in 1...N { for e in range { check = sum(check, UInt64(e)) for _ in range { foo() } check = sum(check, UInt64(e)) } } } // Large, test that tests the interaction between access merging, // and the rest of the access optimizations. public protocol WriteProt { func writeTo(_ stream: StreamClass) } public final class StreamClass { private var buffer: [UInt8] public init() { self.buffer = [] } public func write(_ byte: UInt8) { buffer.append(byte) } public func write(_ value: WriteProt) { value.writeTo(self) } public func writeEscaped(_ string: String) { writeEscaped(string: string.utf8) } public func writeEscaped<T: Collection>( string sequence: T ) where T.Iterator.Element == UInt8 { for character in sequence { buffer.append(character) buffer.append(character) } } } public func toStream(_ stream: StreamClass, _ value: WriteProt) -> StreamClass { stream.write(value) return stream } extension UInt8: WriteProt { public func writeTo(_ stream: StreamClass) { stream.write(self) } } public func asWriteProt(_ string: String) -> WriteProt { return EscapedString(value: string) } private struct EscapedString: WriteProt { let value: String func writeTo(_ stream: StreamClass) { _ = toStream(stream, UInt8(ascii: "a")) stream.writeEscaped(value) _ = toStream(stream, UInt8(ascii: "a")) } } public func asWriteProt<T>(_ items: [T], transform: @escaping (T) -> String) -> WriteProt { return EscapedTransforme(items: items, transform: transform) } private struct EscapedTransforme<T>: WriteProt { let items: [T] let transform: (T) -> String func writeTo(_ stream: StreamClass) { for (i, item) in items.enumerated() { if i != 0 { _ = toStream(stream, asWriteProt(transform(item))) } _ = toStream(stream, asWriteProt(transform(item))) } } } // TESTSIL-LABEL: sil [noinline] @$s17merge_exclusivity14run_MergeTest9yySiF : $@convention(thin) // TESTSIL: [[REFADDR:%.*]] = ref_element_addr {{.*}} : $StreamClass, #StreamClass.buffer // TESTSIL-NEXT: [[B1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[REFADDR]] // TESTSIL: end_access [[B1]] // TESTSIL: [[BCONF:%.*]] = begin_access [modify] [dynamic] [[REFADDR]] // TESTSIL: apply {{.*}} : $@convention(method) (Int, @inout Array<UInt8>) -> () // TESTSIL: end_access [[BCONF]] // TESTSIL: [[BCONF:%.*]] = begin_access [modify] [dynamic] [[REFADDR]] // TESTSIL: apply {{.*}} : $@convention(method) (Int, @inout Array<UInt8>) -> () // TESTSIL: end_access [[BCONF]] // TESTSIL: [[BCONF:%.*]] = begin_access [modify] [dynamic] [[REFADDR]] // TESTSIL: apply {{.*}} : $@convention(method) (Int, @inout Array<UInt8>) -> () // TESTSIL: end_access [[BCONF]] // TESTSIL-LABEL: } // end sil function '$s17merge_exclusivity14run_MergeTest9yySiF' @inline(never) public func run_MergeTest9(_ N: Int) { struct Thing { var value: String init(_ value: String) { self.value = value } } let listOfStrings: [String] = (0..<10).map { "This is the number: \($0)!\n" } let listOfThings: [Thing] = listOfStrings.map(Thing.init) for _ in 1...N { let stream = StreamClass() _ = toStream(stream, asWriteProt(listOfThings, transform: { $0.value })) } }
apache-2.0
3e007c6c04985cf1033ee01990d986c0
30.884181
129
0.617968
3.309
false
true
false
false
xusader/firefox-ios
Client/Frontend/Reader/ReadabilityService.swift
2
4112
/* 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 WebKit private let ReadabilityServiceSharedInstance = ReadabilityService() private let ReadabilityTaskDefaultTimeout = 15 private let ReadabilityServiceDefaultConcurrency = 1 enum ReadabilityOperationResult { case Success(ReadabilityResult) case Error(NSError) case Timeout } class ReadabilityOperation: NSOperation, WKNavigationDelegate, ReadabilityBrowserHelperDelegate { var url: NSURL var semaphore: dispatch_semaphore_t var result: ReadabilityOperationResult? var browser: Browser! init(url: NSURL) { self.url = url self.semaphore = dispatch_semaphore_create(0) } override func main() { if self.cancelled { return } // Setup a browser, attach a Readability helper. Kick all this off on the main thread since UIKit // and WebKit are not safe from other threads. dispatch_async(dispatch_get_main_queue(), { () -> Void in let configuration = WKWebViewConfiguration() self.browser = Browser(configuration: configuration) self.browser.webView.navigationDelegate = self if let readabilityBrowserHelper = ReadabilityBrowserHelper(browser: self.browser) { readabilityBrowserHelper.delegate = self self.browser.addHelper(readabilityBrowserHelper, name: ReadabilityBrowserHelper.name()) } // Load the page in the webview. This either fails with a navigation error, or we get a readability // callback. Or it takes too long, in which case the semaphore times out. self.browser.loadRequest(NSURLRequest(URL: self.url)) }) if dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, Int64(Double(ReadabilityTaskDefaultTimeout) * Double(NSEC_PER_SEC)))) != 0 { result = ReadabilityOperationResult.Timeout } // Maybe this is where we should store stuff in the cache / run a callback? if let result = self.result { switch result { case .Timeout: // Don't do anything on timeout break case .Success(let readabilityResult): var error: NSError? = nil if !ReaderModeCache.sharedInstance.put(url, readabilityResult, error: &error) { if error != nil { println("Failed to store readability results in the cache: \(error?.localizedDescription)") // TODO Fail } } case .Error(let error): // TODO Not entitely sure what to do on error. Needs UX discussion and followup bug. break } } } func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { result = ReadabilityOperationResult.Error(error) dispatch_semaphore_signal(semaphore) } func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { result = ReadabilityOperationResult.Error(error) dispatch_semaphore_signal(semaphore) } func readabilityBrowserHelper(readabilityBrowserHelper: ReadabilityBrowserHelper, didFinishWithReadabilityResult readabilityResult: ReadabilityResult) { result = ReadabilityOperationResult.Success(readabilityResult) dispatch_semaphore_signal(semaphore) } } class ReadabilityService { class var sharedInstance: ReadabilityService { return ReadabilityServiceSharedInstance } var queue: NSOperationQueue init() { queue = NSOperationQueue() queue.maxConcurrentOperationCount = ReadabilityServiceDefaultConcurrency } func process(url: NSURL) { queue.addOperation(ReadabilityOperation(url: url)) } }
mpl-2.0
3df2bcdce79cadd739b7631af6efa9ed
36.054054
156
0.663667
5.489987
false
false
false
false
mrdepth/EVEOnlineAPI
EVEAPI/EVEAPI/EVEKills.swift
1
1349
// // EVEKills.swift // EVEAPI // // Created by Artem Shimanski on 30.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit public class EVEKillsItem: EVEObject { public var solarSystemID: Int = 0 public var shipKills: Int = 0 public var factionKills: Int = 0 public var podKills: Int = 0 public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "solarSystemID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "shipKills":EVESchemeElementType.Int(elementName:nil, transformer:nil), "factionKills":EVESchemeElementType.Int(elementName:nil, transformer:nil), "podKills":EVESchemeElementType.Int(elementName:nil, transformer:nil), ] } } public class EVEKills: EVEResult { public var solarSystems: [EVEKillsItem] = [] public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "solarSystems":EVESchemeElementType.Rowset(elementName: nil, type: EVEKillsItem.self, transformer: nil) ] } }
mit
d2f21f6901a16249cf11ecbf1e0494ff
24.923077
106
0.732938
3.575597
false
false
false
false
4faramita/TweeBox
TweeBox/TweetParams.swift
1
1099
// // TweetParams.swift // TweeBox // // Created by 4faramita on 2017/8/21. // Copyright © 2017年 4faramita. All rights reserved. // import Foundation class TweetParams: ParamsProtocol { public var tweetID: String? public var trimUser = false public var includeMyRetweet = true public var includeEntities = true public var includeExtAltText = true init(of tweetID: String) { self.tweetID = tweetID } public func getParams() -> [String: Any] { var params = [String: String]() guard tweetID != nil else { return params } params["id"] = tweetID! if trimUser { params["trim_user"] = "true" } if !includeMyRetweet { params["include_my_retweet"] = "false" } if !includeEntities { params["include_entities"] = "false" } if !includeExtAltText { params["include_ext_alt_text"] = "false" } return params } }
mit
f1ab0e3763c8d2c7e303ed8ae7c9ef25
19.679245
55
0.523723
4.473469
false
false
false
false
noxytrux/RescueKopter
Geom/Matrix33.swift
1
20359
// // Matrix33.swift // SwiftGeom // // Created by Marcin Pędzimąż on 23.10.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit struct Matrix33 { private let maxLenght = 3 var m: [[Float32]] = [[0,0,0],[0,0,0],[0,0,0]] init() { zero() } init(row0: Vector3, row1: Vector3, row2: Vector3) { m[0][0] = row0.x m[0][1] = row0.y m[0][2] = row0.z m[1][0] = row1.x m[1][1] = row1.y m[1][2] = row1.z m[2][0] = row2.x m[2][1] = row2.y m[2][2] = row2.z } init(other: Matrix33) { m = [[Float32]](other.m) } init(q: Quaternion) { fromQuat(q) } subscript(row: Int, col: Int) -> Float32 { get { assert(indexIsValid(row, column: col), "Index out of range") return m[row][col] } set { assert(indexIsValid(row, column: col), "Index out of range") m[row][col] = newValue } } func indexIsValid(row: Int, column: Int) -> Bool { return row >= 0 && row < maxLenght && column >= 0 && column < maxLenght } } extension Matrix33: CustomStringConvertible { //dispaly in column major (OpenGL like) var description: String { let row0 = "\(m[0][0]),\(m[1][0]),\(m[2][0])" let row1 = "\(m[0][1]),\(m[1][1]),\(m[2][1])" let row2 = "\(m[0][2]),\(m[1][2]),\(m[2][2])" return "[\(row0),\n\(row1),\n\(row2)]" } } extension Matrix33 { func isFinite() -> Bool { return m[0][0].isFinite && m[0][1].isFinite && m[0][2].isFinite && m[1][0].isFinite && m[1][1].isFinite && m[1][2].isFinite && m[2][0].isFinite && m[2][1].isFinite && m[2][2].isFinite } mutating func fromQuat(q: Quaternion) { let w = q.w; let x = q.x; let y = q.y; let z = q.z; self[0,0] = 1.0 - y*y*2.0 - z*z*2.0 self[0,1] = x*y*2.0 - w*z*2.0 self[0,2] = x*z*2.0 + w*y*2.0 self[1,0] = x*y*2.0 + w*z*2.0 self[1,1] = 1.0 - x*x*2.0 - z*z*2.0 self[1,2] = y*z*2.0 - w*x*2.0 self[2,0] = x*z*2.0 - w*y*2.0 self[2,1] = y*z*2.0 + w*x*2.0 self[2,2] = 1.0 - x*x*2.0 - y*y*2.0 } func toQuat(inout q:Quaternion) { var tr:Float32, s:Float32 tr = self[0,0] + self[1,1] + self[2,2] if(tr >= 0) { s = sqrt(tr + 1) q.w = 0.5 * s s = 0.5 / s q.x = (m[2][1] - m[1][2]) * s q.y = (m[0][2] - m[2][0]) * s q.z = (m[1][0] - m[0][1]) * s } else { var i = 0 if m[1][1] > m[0][0] { i = 1 } if m[2][2] > m[i][i] { i = 2 } switch (i) { case 0: s = sqrt((self[0,0] - (self[1,1] + self[2,2])) + 1) q.x = 0.5 * s s = 0.5 / s q.y = (self[0,1] + self[1,0]) * s q.z = (self[2,0] + self[0,2]) * s q.w = (self[2,1] - self[1,2]) * s case 1: s = sqrt((self[1,1] - (self[2,2] + self[0,0])) + 1) q.y = 0.5 * s s = 0.5 / s q.z = (self[1,2] + self[2,1]) * s q.x = (self[0,1] + self[1,0]) * s q.w = (self[0,2] - self[2,0]) * s case 2: s = sqrt((self[2,2] - (self[0,0] + self[1,1])) + 1) q.z = 0.5 * s s = 0.5 / s q.x = (self[2,0] + self[0,2]) * s q.y = (self[1,2] + self[2,1]) * s q.w = (self[1,0] - self[0,1]) * s default: () break } } } mutating func setColumn(col:Int, v:Vector3) { self[0,col] = v.x self[1,col] = v.y self[2,col] = v.z } mutating func setRow(row:Int, v:Vector3) { self[row,0] = v.x self[row,1] = v.y self[row,2] = v.z } func getColumn(col:Int, inout v:Vector3) { v.x = self[0,col] v.y = self[1,col] v.z = self[2,col] } func getRow(row:Int, inout v:Vector3) { v.x = self[row,0] v.y = self[row,1] v.z = self[row,2] } func isIdentity() -> Bool { if self[0,0] != 1.0 { return false } if self[0,1] != 0.0 { return false } if self[0,2] != 0.0 { return false } if self[1,0] != 0.0 { return false } if self[1,1] != 1.0 { return false } if self[1,2] != 0.0 { return false } if self[2,0] != 0.0 { return false } if self[2,1] != 0.0 { return false } if self[2,2] != 1.0 { return false } return true; } mutating func zero() { m[0][0] = 0 m[0][1] = 0 m[0][2] = 0 m[1][0] = 0 m[1][1] = 0 m[1][2] = 0 m[2][0] = 0 m[2][1] = 0 m[2][2] = 0 } mutating func identity() { m[0][0] = 1 m[0][1] = 0 m[0][2] = 0 m[1][0] = 0 m[1][1] = 1 m[1][2] = 0 m[2][0] = 0 m[2][1] = 0 m[2][2] = 1 } mutating func negative() { m[0][0] = -m[0][0] m[0][1] = -m[0][1] m[0][2] = -m[0][2] m[1][0] = -m[1][0] m[1][1] = -m[1][1] m[1][2] = -m[1][2] m[2][0] = -m[2][0] m[2][1] = -m[2][1] m[2][2] = -m[2][2] } mutating func diagonal(v: Vector3) { m[0][0] = v.x m[0][1] = 0 m[0][2] = 0 m[1][0] = 0 m[1][1] = v.y m[1][2] = 0 m[2][0] = 0 m[2][1] = 0 m[2][2] = v.z } mutating func star(v: Vector3) { m[0][0] = 0.0 m[0][1] = -v.z m[0][2] = v.y m[1][0] = v.z m[1][1] = 0.0 m[1][2] = -v.x m[2][0] = -v.y m[2][1] = v.x m[2][2] = 0.0 } mutating func setTransposed(other: Matrix33) { self[0,0] = other[0,0] self[0,1] = other[1,0] self[0,2] = other[2,0] self[1,0] = other[0,1] self[1,1] = other[1,1] self[1,2] = other[2,1] self[2,0] = other[0,2] self[2,1] = other[1,2] self[2,2] = other[2,2] } mutating func setTransposed() { swapValues(&self[0,1], b: &self[1,0]) swapValues(&self[1,2], b: &self[2,1]) swapValues(&self[0,2], b: &self[2,0]) } mutating func multiplyDiagonal(v: Vector3) { m[0][0] *= v.x m[0][1] *= v.y m[0][2] *= v.z m[1][0] *= v.x m[1][1] *= v.y m[1][2] *= v.z m[2][0] *= v.x m[2][1] *= v.y m[2][2] *= v.z } mutating func multiplyDiagonalTranspose(d: Vector3) { var temp: Float32 = 0 m[0][0] = m[0][0] * d.x m[1][1] = m[1][1] * d.y m[2][2] = m[2][2] * d.z temp = m[1][0] * d.y m[1][0] = m[0][1] * d.x m[0][1] = temp temp = m[2][0] * d.z m[2][0] = m[0][2] * d.x m[0][2] = temp temp = m[2][1] * d.z m[2][1] = m[1][2] * d.y m[1][2] = temp } //MARK: vector multiply func multiply(src: Vector3, inout dst: Vector3) { var x:Float32,y:Float32,z:Float32 x = m[0][0] * src.x + m[0][1] * src.y + m[0][2] * src.z y = m[1][0] * src.x + m[1][1] * src.y + m[1][2] * src.z z = m[2][0] * src.x + m[2][1] * src.y + m[2][2] * src.z dst.x = x; dst.y = y; dst.z = z; } func multiplyByTranspose(src: Vector3, inout dst: Vector3) { var x:Float32,y:Float32,z:Float32; x = m[0][0] * src.x + m[1][0] * src.y + m[2][0] * src.z y = m[0][1] * src.x + m[1][1] * src.y + m[2][1] * src.z z = m[0][2] * src.x + m[1][2] * src.y + m[2][2] * src.z dst.x = x; dst.y = y; dst.z = z; } //MARK: matrix multiply mutating func multiply(left: Matrix33, right: Matrix33) { var a:Float32,b:Float32,c:Float32,d:Float32,e:Float32,f:Float32,g:Float32,h:Float32,i:Float32 a = left[0,0] * right[0,0] + left[0,1] * right[1,0] + left[0,2] * right[2,0] b = left[0,0] * right[0,1] + left[0,1] * right[1,1] + left[0,2] * right[2,1] c = left[0,0] * right[0,2] + left[0,1] * right[1,2] + left[0,2] * right[2,2] d = left[1,0] * right[0,0] + left[1,1] * right[1,0] + left[1,2] * right[2,0] e = left[1,0] * right[0,1] + left[1,1] * right[1,1] + left[1,2] * right[2,1] f = left[1,0] * right[0,2] + left[1,1] * right[1,2] + left[1,2] * right[2,2] g = left[2,0] * right[0,0] + left[2,1] * right[1,0] + left[2,2] * right[2,0] h = left[2,0] * right[0,1] + left[2,1] * right[1,1] + left[2,2] * right[2,1] i = left[2,0] * right[0,2] + left[2,1] * right[1,2] + left[2,2] * right[2,2] m[0][0] = a m[0][1] = b m[0][2] = c m[1][0] = d m[1][1] = e m[1][2] = f m[2][0] = g m[2][1] = h m[2][2] = i } mutating func multiplyTransposeLeft(left: Matrix33, right: Matrix33) { var a:Float32,b:Float32,c:Float32,d:Float32,e:Float32,f:Float32,g:Float32,h:Float32,i:Float32 a = left[0,0] * right[0,0] + left[1,0] * right[1,0] + left[2,0] * right[2,0] b = left[0,0] * right[0,1] + left[1,0] * right[1,1] + left[2,0] * right[2,1] c = left[0,0] * right[0,2] + left[1,0] * right[1,2] + left[2,0] * right[2,2] d = left[0,1] * right[0,0] + left[1,1] * right[1,0] + left[2,1] * right[2,0] e = left[0,1] * right[0,1] + left[1,1] * right[1,1] + left[2,1] * right[2,1] f = left[0,1] * right[0,2] + left[1,1] * right[1,2] + left[2,1] * right[2,2] g = left[0,2] * right[0,0] + left[1,2] * right[1,0] + left[2,2] * right[2,0] h = left[0,2] * right[0,1] + left[1,2] * right[1,1] + left[2,2] * right[2,1] i = left[0,2] * right[0,2] + left[1,2] * right[1,2] + left[2,2] * right[2,2] m[0][0] = a m[0][1] = b m[0][2] = c m[1][0] = d m[1][1] = e m[1][2] = f m[2][0] = g m[2][1] = h m[2][2] = i } mutating func multiplyTransposeRight(left: Matrix33, right: Matrix33) { var a:Float32,b:Float32,c:Float32,d:Float32,e:Float32,f:Float32,g:Float32,h:Float32,i:Float32 a = left[0,0] * right[0,0] + left[0,1] * right[0,1] + left[0,2] * right[0,2] b = left[0,0] * right[1,0] + left[0,1] * right[1,1] + left[0,2] * right[1,2] c = left[0,0] * right[2,0] + left[0,1] * right[2,1] + left[0,2] * right[2,2] d = left[1,0] * right[0,0] + left[1,1] * right[0,1] + left[1,2] * right[0,2] e = left[1,0] * right[1,0] + left[1,1] * right[1,1] + left[1,2] * right[1,2] f = left[1,0] * right[2,0] + left[1,1] * right[2,1] + left[1,2] * right[2,2] g = left[2,0] * right[0,0] + left[2,1] * right[0,1] + left[2,2] * right[0,2] h = left[2,0] * right[1,0] + left[2,1] * right[1,1] + left[2,2] * right[1,2] i = left[2,0] * right[2,0] + left[2,1] * right[2,1] + left[2,2] * right[2,2] m[0][0] = a m[0][1] = b m[0][2] = c m[1][0] = d m[1][1] = e m[1][2] = f m[2][0] = g m[2][1] = h m[2][2] = i } mutating func multiplyTransposeRight(left: Vector3, right: Vector3) { m[0][0] = left.x * right.x m[0][1] = left.x * right.y m[0][2] = left.x * right.z m[1][0] = left.y * right.x m[1][1] = left.y * right.y m[1][2] = left.y * right.z m[2][0] = left.z * right.x m[2][1] = left.z * right.y m[2][2] = left.z * right.z } //MARK: rotation mutating func rotX(angle: Float32) { let Cos: Float32 = cosf(angle) let Sin: Float32 = sinf(angle) identity() m[2][2] = Cos m[1][1] = Cos m[1][2] = -Sin m[2][1] = Sin } mutating func rotY(angle: Float32) { let Cos: Float32 = cosf(angle) let Sin: Float32 = sinf(angle) identity() m[2][2] = Cos m[0][0] = Cos m[0][2] = Sin m[2][0] = -Sin } mutating func rotZ(angle: Float32) { let Cos: Float32 = cosf(angle) let Sin: Float32 = sinf(angle) identity() m[1][1] = Cos m[0][0] = Cos m[0][1] = -Sin m[1][0] = Sin } func determinant() -> Float32 { let a = m[0][0] * m[1][1] * m[2][2] let b = m[0][1] * m[1][2] * m[2][1] let c = m[0][2] * m[1][0] * m[2][1] let d = m[0][2] * m[1][1] * m[2][0] let e = m[0][1] * m[1][0] * m[2][2] let f = m[0][0] * m[1][2] * m[2][1] return a + b + c - d - e - f } func getInverse(inout dest: Matrix33) -> Bool { var b00: Float32,b01: Float32,b02: Float32,b10: Float32,b11: Float32,b12: Float32,b20: Float32,b21: Float32,b22: Float32 b00 = m[1][1] * m[2][2] - m[1][2] * m[2][1] b01 = m[0][2] * m[2][1] - m[0][1] * m[2][2] b02 = m[0][1] * m[1][2] - m[0][2] * m[1][1] b10 = m[1][2] * m[2][0] - m[1][0] * m[2][2] b11 = m[0][0] * m[2][2] - m[0][2] * m[2][0] b12 = m[0][2] * m[1][0] - m[0][0] * m[1][2] b20 = m[1][0] * m[2][1] - m[1][1] * m[2][0] b21 = m[0][1] * m[2][0] - m[0][0] * m[2][1] b22 = m[0][0] * m[1][1] - m[0][1] * m[1][0] var d: Float32 = b00 * m[0][0] + b01 * m[1][0] + b02 * m[2][0] if d == 0.0 { //singular matrix dest.identity() return false } d = 1.0 / d dest[0,0] = b00 * d dest[0,1] = b01 * d dest[0,2] = b02 * d dest[1,0] = b10 * d dest[1,1] = b11 * d dest[1,2] = b12 * d dest[2,0] = b20 * d dest[2,1] = b21 * d dest[2,2] = b22 * d return true; } //MARK: raw data GET func getColumnMajor(inout rawMatrix: Matrix3x3) { rawMatrix.m01 = m[0][0] rawMatrix.m04 = m[0][1] rawMatrix.m07 = m[0][2] rawMatrix.m02 = m[1][0] rawMatrix.m05 = m[1][1] rawMatrix.m08 = m[1][2] rawMatrix.m03 = m[2][0] rawMatrix.m06 = m[2][1] rawMatrix.m09 = m[2][2] } func gerRowMajor(inout rawMatrix: Matrix3x3) { rawMatrix.m01 = m[0][0] rawMatrix.m02 = m[0][1] rawMatrix.m03 = m[0][2] rawMatrix.m04 = m[1][0] rawMatrix.m05 = m[1][1] rawMatrix.m06 = m[1][2] rawMatrix.m07 = m[2][0] rawMatrix.m08 = m[2][1] rawMatrix.m09 = m[2][2] } func getColumnMajorStride4(inout rawMatrix: Matrix4x4) { rawMatrix.m01 = m[0][0] rawMatrix.m05 = m[0][1] rawMatrix.m09 = m[0][2] rawMatrix.m02 = m[1][0] rawMatrix.m06 = m[1][1] rawMatrix.m10 = m[1][2] rawMatrix.m03 = m[2][0] rawMatrix.m07 = m[2][1] rawMatrix.m11 = m[2][2] } func getRowMajorStride4(inout rawMatrix: Matrix4x4) { rawMatrix.m01 = m[0][0] rawMatrix.m02 = m[0][1] rawMatrix.m03 = m[0][2] rawMatrix.m05 = m[1][0] rawMatrix.m06 = m[1][1] rawMatrix.m07 = m[1][2] rawMatrix.m09 = m[2][0] rawMatrix.m10 = m[2][1] rawMatrix.m11 = m[2][2] } //MARK: raw data SET mutating func setColumnMajor(rawMatrix: Matrix3x3) { m[0][0] = rawMatrix.m01 m[0][1] = rawMatrix.m04 m[0][2] = rawMatrix.m07 m[1][0] = rawMatrix.m02 m[1][1] = rawMatrix.m05 m[1][2] = rawMatrix.m08 m[2][0] = rawMatrix.m03 m[2][1] = rawMatrix.m06 m[2][2] = rawMatrix.m09 } mutating func setRowMajor(rawMatrix: Matrix3x3) { m[0][0] = rawMatrix.m01 m[0][1] = rawMatrix.m02 m[0][2] = rawMatrix.m03 m[1][0] = rawMatrix.m04 m[1][1] = rawMatrix.m05 m[1][2] = rawMatrix.m06 m[2][0] = rawMatrix.m07 m[2][1] = rawMatrix.m08 m[2][2] = rawMatrix.m09 } mutating func setColumnMajorStride4(rawMatrix: Matrix4x4) { m[0][0] = rawMatrix.m01 m[0][1] = rawMatrix.m05 m[0][2] = rawMatrix.m09 m[1][0] = rawMatrix.m02 m[1][1] = rawMatrix.m06 m[1][2] = rawMatrix.m10 m[2][0] = rawMatrix.m03 m[2][1] = rawMatrix.m07 m[2][2] = rawMatrix.m11 } mutating func setRowMajorStride4(rawMatrix: Matrix4x4) { m[0][0] = rawMatrix.m01 m[0][1] = rawMatrix.m02 m[0][2] = rawMatrix.m03 m[1][0] = rawMatrix.m05 m[1][1] = rawMatrix.m06 m[1][2] = rawMatrix.m07 m[2][0] = rawMatrix.m09 m[2][1] = rawMatrix.m10 m[2][2] = rawMatrix.m11 } } func + (left: Matrix33, right: Matrix33) -> Matrix33 { var outMatrix = Matrix33() outMatrix[0,0] = left[0,0] + right[0,0] outMatrix[0,1] = left[0,1] + right[0,1] outMatrix[0,2] = left[0,2] + right[0,2] outMatrix[1,0] = left[1,0] + right[1,0] outMatrix[1,1] = left[1,1] + right[1,1] outMatrix[1,2] = left[1,2] + right[1,2] outMatrix[2,0] = left[2,0] + right[2,0] outMatrix[2,1] = left[2,1] + right[2,1] outMatrix[2,2] = left[2,2] + right[2,2] return outMatrix } func - (left: Matrix33, right: Matrix33) -> Matrix33 { var outMatrix = Matrix33() outMatrix[0,0] = left[0,0] - right[0,0] outMatrix[0,1] = left[0,1] - right[0,1] outMatrix[0,2] = left[0,2] - right[0,2] outMatrix[1,0] = left[1,0] - right[1,0] outMatrix[1,1] = left[1,1] - right[1,1] outMatrix[1,2] = left[1,2] - right[1,2] outMatrix[2,0] = left[2,0] - right[2,0] outMatrix[2,1] = left[2,1] - right[2,1] outMatrix[2,2] = left[2,2] - right[2,2] return outMatrix } func * (left: Matrix33, right: Float32) -> Matrix33 { var outMatrix = Matrix33() outMatrix[0,0] = left[0,0] * right outMatrix[0,1] = left[0,1] * right outMatrix[0,2] = left[0,2] * right outMatrix[1,0] = left[1,0] * right outMatrix[1,1] = left[1,1] * right outMatrix[1,2] = left[1,2] * right outMatrix[2,0] = left[2,0] * right outMatrix[2,1] = left[2,1] * right outMatrix[2,2] = left[2,2] * right return outMatrix } func * (left: Matrix33, right: Matrix33) -> Matrix33 { var outMatrix = Matrix33() outMatrix.multiply(left, right: right) return outMatrix } func * (left: Matrix33, right: Vector3) -> Vector3 { var dest = Vector3() left.multiply(right, dst: &dest) return dest } func += (inout left: Matrix33, right: Matrix33) { left = left + right } func -= (inout left: Matrix33, right: Matrix33) { left = left - right } func *= (inout left: Matrix33, right: Matrix33) { left = left * right }
mit
0b22ee4b9c1147d323fb151062fa1269
24.605031
192
0.40956
2.644667
false
false
false
false
marty-suzuki/QiitaWithFluxSample
QiitaSession/QiitaSession/Request/AccessTokensRequest.swift
1
849
// // AccessTokensRequest.swift // QiitaWithFluxSample // // Created by marty-suzuki on 2017/04/15. // Copyright © 2017年 marty-suzuki. All rights reserved. // import APIKit public struct AccessTokensRequest: QiitaRequest { public typealias Response = AccessTokensResponse public let method: HTTPMethod = .post public let path: String = "/access_tokens" public var queryParameters: [String : Any]? { return [ "client_id" : clientId, "client_secret" : clientSecret, "code" : code ] } public let clientId: String public let clientSecret: String public let code: String public init(clientId: String, clientSecret: String, code: String) { self.clientId = clientId self.clientSecret = clientSecret self.code = code } }
mit
a9dfc8c9b40378ed6aee95d9c62e24a3
24.636364
71
0.63948
4.360825
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Profiles/Template/Sections/ChartDataSection.swift
1
2361
/* * Copyright (c) 2020, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 class ChartDataSection<T>: Section { var items: [T] = [] func dequeCell(for index: Int, from tableView: UITableView) -> UITableViewCell { let chartValues = items.map(transform) let cell = tableView.dequeueCell(ofType: LinearChartTableViewCell.self) cell.update(with: chartValues) return cell } func reset() { items.removeAll() } var sectionTitle: String { "" } var numberOfItems: Int { 1 } var id: Identifier<Section> var isHidden: Bool = false func update(with data: T) { items.append(data) } func transform(_ item: T) -> (x: Double, y: Double) { (0, 0) } init(id: Identifier<Section>) { self.id = id } func cellHeight(for index: Int) -> CGFloat { 350.0 } }
bsd-3-clause
4b75d83ed9a4780fd5f60268ec833c35
34.772727
84
0.720034
4.404851
false
false
false
false
EugeneVegner/sws-copyleaks-sdk-test
Example/PlagiarismChecker/ProcessDetailsViewController.swift
1
4208
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ import UIKit import PlagiarismChecker class ProcessDetailsViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var processIdLabel: UILabel! @IBOutlet weak var processStatusLabel: UILabel! @IBOutlet weak var processCreatedLabel: UILabel! @IBOutlet weak var updateButton: UIButton! @IBOutlet weak var resultsButton: UIButton! @IBOutlet weak var deleteButton: UIButton! var processId: String = "" var processStatus: String = "Finished" var processCreated: String = "" override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Process Detail" updateView() } func updateView() { processIdLabel.text = processId processStatusLabel.text = processStatus processCreatedLabel.text = processCreated let isFinished: Bool = (processStatus == "Finished") resultsButton.enabled = isFinished deleteButton.enabled = isFinished } @IBAction func deleteAction(sender: AnyObject) { if activityIndicator.isAnimating() { return } activityIndicator.startAnimating() let cloud = CopyleaksCloud(.Businesses) cloud.deleteProcess(processIdLabel.text!) { (result) in self.activityIndicator.stopAnimating() if result.isSuccess { self.activityIndicator.stopAnimating() self.navigationController?.popViewControllerAnimated(true) } else { Alert("Error", message: result.error?.localizedFailureReason ?? "Unknown error") } } } @IBAction func statusAction(sender: AnyObject) { if activityIndicator.isAnimating() { return } activityIndicator.startAnimating() let cloud = CopyleaksCloud(.Businesses) cloud.statusProcess(processIdLabel.text!) { (result) in self.activityIndicator.stopAnimating() if result.isSuccess { self.activityIndicator.stopAnimating() if let status = result.value?["Status"] as? String { self.processStatus = status } self.updateView() } else { Alert("Error", message: result.error?.localizedFailureReason ?? "Unknown error") } } } // MARK: - Memory override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showResults" { (segue.destinationViewController as! ResultsViewController).processId = processId } } }
mit
39b6e61b90992436f12decb1e80c086f
30.878788
96
0.639971
5.40874
false
false
false
false
sora0077/iTunesMusicKit
src/Endpoint/ListGenres.swift
1
2518
// // ListGenres.swift // iTunesMusicKit // // Created by 林達也 on 2015/10/14. // Copyright © 2015年 jp.sora0077. All rights reserved. // import Foundation import APIKit import Alamofire public struct ListGenres { public let country: String var id: String public init(country: String = "jp") { self.country = country self.id = "34" } } extension Dictionary { func map<T, U>(@noescape transform: (Dictionary.Generator.Element) throws -> (T, U)) rethrows -> [T: U] { var projection: [T: U] = [:] for val in self { let (k, v) = try transform(val) projection[k] = v } return projection } } extension ListGenres: iTunesRequestToken { public typealias Response = Genres public typealias SerializedObject = [String: AnyObject] public var method: HTTPMethod { return .GET } public var path: String { return "https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/genres" } public var parameters: [String: AnyObject]? { return [ "cc": country, "id": id ] } public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { let dict = object[id] as! SerializedObject return Genres( id: dict["id"] as! String, name: dict["name"] as! String, topAlbums: dict["rssUrls"]!["topAlbums"] as! String, topSongs: dict["rssUrls"]!["topSongs"] as! String, genre: (dict["subgenres"] as! [String: SerializedObject]).map { k, dict in (k, Genres.Genre( id: dict["id"] as! String, name: dict["name"] as! String, topAlbums: dict["rssUrls"]!["topAlbums"] as! String, topSongs: dict["rssUrls"]!["topSongs"] as! String, subgenre: (dict["subgenres"] as? [String: SerializedObject])?.map { k, dict in (k, Genres.Genre.Subgenre( id: dict["id"] as! String, name: dict["name"] as! String, topAlbums: dict["rssUrls"]!["topAlbums"] as! String, topSongs: dict["rssUrls"]!["topSongs"] as! String )) } ?? [:] )) } ) } }
mit
aaf563312dfa3ff7e4cba801e27e0b47
28.186047
126
0.514548
4.504488
false
false
false
false
pyanfield/ataturk_olympic
swift_programming_1.1-2.5.playground/section-1.swift
1
24445
import UIKit var str = "Hello, playground" let label = "This is a test" let width = 4 // 这里要显示转换 width 到 string let widthLabel = label + String(width) let bookSummary = "I have \(width) books" // // 这里声明类的时候,使用方括号包含类型的方式,后面的小括号是做初始化 var fruites = [String]() fruites = ["apple","peach","orange","banana"] fruites.append("kaka") println(fruites) // 可变参量是保存在一个数组中 func sumOf(numbers: Int...) -> Int{ var sum=0 for number in numbers{ sum += number } return sum } sumOf(11,22,33) // func makeIncrease() -> (Int -> Int){ func addOne(number : Int) -> Int{ return number + 1 } return addOne } var increse = makeIncrease() increse(7) // func hasAnyMatches(list :[Int], condition: Int -> Bool) -> Bool{ for item in list{ // if 后必须要跟一个明确的 bool 值 if condition(item) { return true } } return false } func lessThanTen(number :Int) -> Bool{ return number < 10 } var numbers = [10,20,5,2,30] // 这里调用函数作为参数的时候,这里的 lessThanTen 是不带小括号的,有小括号表示调用 var matched = hasAnyMatches(numbers, lessThanTen) // map 的参数就是 transform: (T) -> U,所以可以使用 (number :Int) -> Int numbers.map({ (number :Int) -> Int in let result = 3*number return result }) // numbers.map({number in 3*number}) // 如果闭包作为最后一个参数传给一个函数的时候,可以直接跟在括号后面,这里 sort 最后一个参数是 isOrderedBefore: (T, T) -> Bool numbers.map(){ (number :Int) -> Int in let result = 3*number return result } sort(&numbers){ (a :Int, b :Int) -> Bool in return a > b } sort(&numbers){$0 > $1} // class Shape{ var numberOfSides = 0 var name :String // 构造函数是没有 func 关键字定义的 // 析构函数是 deinit init(name :String){ self.name = name } func simpleDescription() -> String{ return "A shape with \(numberOfSides) sides." } } class Square :Shape{ var sideLength: Double init(sideLength :Double, name :String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } var perimeter :Double{ get{ return sideLength * Double(numberOfSides) } set{ // 默认新值是 newValue,可以在 set 之后自定义 sideLength = newValue / Double(numberOfSides) } } // 含有 willSet 和 didSet 方法 func area() -> Double{ return sideLength * sideLength } // 函数重写关键字 override override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } let square = Square(sideLength: 5.0, name: "mini square") square.area() square.simpleDescription() square.perimeter square.perimeter = 10 // enum Rank: Int { // 枚举的原始值是 Int 类型,只需要设置第一个原始值,也可以不设置原始值 // 注意这里的 case 关键字 case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.rawValue) } } } // toRaw() ,fromRaw() 实现枚举值和原始值的转换 let ace = Rank.Ace let aceRawValue = ace.rawValue Rank(rawValue: 11)?.simpleDescription() Rank.Five.simpleDescription() enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription() // 使用struct来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们之间最大的一个区别就是 结构体是传值,类是传引用 struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() // 一个枚举成员的实例可以有实例值。相同枚举成员的实例可以有不同的值。创建实例的时候传入值即可。 // 实例值和原始值是不同的:枚举成员的原始值对于所有实例都是相同的,而且你是在定义枚举的时候设置原始值。 enum ServerResponse { case Result(String, String) case Error(String) } let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.") switch success { // 注意这里的取值 case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error(error): let serverResponse = "Failure... \(error)" } // 类、枚举和结构体都可以实现协议。 protocol ExampleProtocol{ var simpleDes: String { get } mutating func adjust() } class SimpleClass:ExampleProtocol { var simpleDes: String = "A Simple Class" // 这里不用声明 mutating 是因为类中的方法经常会修改 func adjust() { simpleDes += " Should Be Adjusted" } } var sc = SimpleClass() sc.adjust() struct SimpleStruct:ExampleProtocol { var simpleDes: String = "Simple Struct" // 标记会修改结构体的方法 mutating func adjust() { simpleDes += " (adjusted)" } } var ss = SimpleStruct() ss.adjust() let ts = ss.simpleDes // 使用extension来为现有的类型添加功能,比如新的方法和参数。 // 你可以使用扩展来改造定义在别处,甚至是从外部库或者框架引入的一个类型,使得这个类型遵循某个协议。 extension Int: ExampleProtocol{ var simpleDes: String{ return "The Number is \(self)" } mutating func adjust(){ self += 50 } } 7.simpleDes // func repeat<ItemType>(item: ItemType, times: Int) -> [ItemType]{ var result = [ItemType]() // 注意这里 ..< 和 ... 的区别 for i in 0 ..< times{ result.append(item) } return result } repeat("ok", 7) // 泛型也可用于 类,枚举,结构体 // where 用来指定对类型的需求,简单起见,你可以忽略where,只在冒号后面写协议或者类名。<T: Equatable>和<T where T: Equatable>是等价的。 func anyCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1, 2, 3], [3]) // 与其他大部分编程语言不同,Swift 并不强制要求你在每条语句的结尾处使用分号(;),当然,你也可以按照你自己的习惯添加分号。有一种情况下必须要用分号,即你打算在同一行内写多条独立的语句. // 尽量不要使用UInt,除非你真的需要存储一个和当前平台原生字长相同的无符号整数。除了这种情况,最好使用Int,即使你要存储的值已知是非负的。 // 统一使用Int可以提高代码的可复用性,避免不同类型数字之间的转换,并且匹配数字的类型推断,请参考类型安全和类型推断。 // Double表示64位浮点数,Float表示32位浮点数 // Double精确度很高,至少有15位数字,而Float最少只有6位数字。 // Swift 是一个类型安全(type safe)的语言。它会在编译你的代码时进行类型检查(type checks),并把不匹配的类型标记为错误。 // 当推断浮点数的类型时,Swift 总是会选择Double而不是Float。 // 浮点字面量可以是十进制(没有前缀)或者是十六进制(前缀是0x)。小数点两边必须有至少一个十进制数字(或者是十六进制的数字)。 // 浮点字面量还有一个可选的指数(exponent),在十进制浮点数中通过大写或者小写的e来指定,在十六进制浮点数中通过大写或者小写的p来指定。 // 如果一个十进制数的指数为exp,那这个数相当于基数和10^exp的乘积:1.25e2 表示 1.25 × 10^2,等于 125.0 println(1.25e2) println(1.25e-2) // 如果一个十六进制数的指数为exp,那这个数相当于基数和2^exp的乘积:0xFp2 表示 15 × 2^2,等于 60.0 println(0xFp2) println(0xFp-2) // 数值类字面量可以包括额外的格式来增强可读性。整数和浮点数都可以添加额外的零并且包含下划线,并不会影响字面量: let paddedDouble = 000123.456 let oneMillion = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1 // 类型别名(type aliases)就是给现有类型定义另一个名字。你可以使用typealias关键字来定义类型别名。 typealias MyInt8 = UInt8 let mi16: MyInt8 = 0 println(MyInt8.max) // 元组(tuples)把多个值组合成一个复合值。元组内的值可以是任意类型,并不要求是相同类型。 let http404Error = (404, "Not Found") // 可以将一个元组的内容分解(decompose)成单独的常量和变量,然后你就可以正常使用它们了: let (statusCode, statusMessage) = http404Error println("The status code is \(statusCode)") println("The status message is \(statusMessage)") // 只需要一部分元组值,分解的时候可以把要忽略的部分用下划线(_)标记: let (justTheStatusCode, _) = http404Error println("The status code is \(justTheStatusCode)") // 还可以通过下标来访问元组中的单个元素,下标从零开始: println("The status code is \(http404Error.0)") println("The status message is \(http404Error.1)") // 可以在定义元组的时候给单个元素命名: let http200Status = (statusCode: 200, description: "OK") println("The status code is \(http200Status.statusCode)") println("The status message is \(http200Status.description)") // 元组在临时组织值的时候很有用,但是并不适合创建复杂的数据结构。如果你的数据结构并不是临时使用,请使用类或者结构体而不是元组。 let possibleNumber = "123" let convertedNumber = possibleNumber.toInt() // convertedNumber 被推测为类型 "Int?", 或者类型 "optional Int",而不是一个Int。 // 当你确定可选类型确实包含值之后,你可以在可选的名字后面加一个感叹号(!)来获取值。这个惊叹号表示“我知道这个可选有值,请使用它。”这被称为可选值的强制解析(forced unwrapping) if (convertedNumber != nil) { println("\(possibleNumber) has an integer value of \(convertedNumber!)") } else { println("\(possibleNumber) could not be converted to an integer") } // 使用可选绑定(optional binding)来判断可选类型是否包含值,如果包含就把值赋给一个临时常量或者变量。 if let actualNumber = possibleNumber.toInt() { println("\(possibleNumber) has an integer value of \(actualNumber)") } else { println("\(possibleNumber) could not be converted to an integer") } // 如果转换成功,actualNumber常量可以在if语句的第一个分支中使用。它已经被可选类型包含的值初始化过,所以不需要再使用!后缀来获取它的值. // 你可以在可选绑定中使用常量和变量。如果你想在if语句的第一个分支中操作actualNumber的值,你可以改成if var actualNumber,这样可选类型包含的值就会被赋给一个变量而非常量。 // 你可以给可选变量赋值为nil来表示它没有值: var serverResponseCode: Int? = 404 serverResponseCode = nil // nil不能用于非可选的常量和变量。如果你声明一个可选常量或者变量但是没有赋值,它们会自动被设置为nil. // 有时候在程序架构中,第一次被赋值之后,可以确定一个可选类型总会有值。在这种情况下,每次都要判断和解析可选值是非常低效的,因为可以确定它总会有值。 // 这种类型的可选状态被定义为隐式解析可选类型(implicitly unwrapped optionals)。把想要用作可选的类型的后面的问号(String?)改成感叹号(String!)来声明一个隐式解析可选类型。 // 当可选类型被第一次赋值之后就可以确定之后一直有值的时候,隐式解析可选类型非常有用。隐式解析可选类型主要被用在 Swift 中类的构造过程中,请参考类实例之间的循环强引用。 // 断言会在运行时判断一个逻辑条件是否为true。从字面意思来说,断言“断言”一个条件是否为真。 // 你可以使用断言来保证在运行其他代码之前,某些重要的条件已经被满足。如果条件判断为true,代码运行会继续进行;如果条件判断为false,代码运行停止,你的应用被终止。 /* 当条件可能为假时使用断言,但是最终一定要保证条件为真,这样你的代码才能继续运行。断言的适用情景: 1.整数类型的下标索引被传入一个自定义下标脚本实现,但是下标索引值可能太小或者太大。 2.需要给函数传入一个值,但是非法的值可能导致函数不能正常执行。 3.一个可选值现在是nil,但是后面的代码运行需要一个非nil值。 */ // 不同于 C 语言和 Objective-C,Swift 中是可以对浮点数进行求余的。 println(9%2) println(8%2.5) // Swift 也提供恒等===和不恒等!==这两个比较符来判断两个对象是否引用同一个对象实例。更多细节在类与结构。 // 空合运算符(a ?? b)将对可选类型a进行空判断,如果a包含一个值就进行解封,否则就返回一个默认值b.这个运算符有两个条件: // 表达式a必须是Optional类型 // 默认值b的类型必须要和a存储值的类型保持一致 // 空合并运算符是对以下代码的简短表达方法 a != nil ? a! : b // 闭区间运算符(a...b)定义一个包含从a到b(包括a和b)的所有值的区间 for index in 1...5 { println("\(index) * 5 = \(index * 5)") } // 半开区间(a..<b)定义一个从a到b但不包括b的区间 // 2.3 // isEmpty 判断字符串是否为空,注意这里不是 isEmpty() var emptyString = "" var anotherEmptyString = String() if emptyString.isEmpty{ println("empty string") } if anotherEmptyString.isEmpty{ println("another empty string") } // Swift 的String类型是值类型。NSString 是指针传递,传的时一个引用。 // Swift 的String类型表示特定序列的Character(字符) 类型值的集合。 for cha in "Anfield"{ println(cha) } // 通过标明一个Character类型注解并通过字符字面量进行赋值,可以建立一个独立的字符常量或变量: let cha: Character = "7" // 通过调用全局countElements函数,并将字符串作为参数进行传递,可以获取该字符串的字符数量。 let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪" println("unusualMenagerie has \(countElements(unusualMenagerie)) characters") unusualMenagerie.utf16Count unusualMenagerie.lowercaseString // 不同的 Unicode 字符以及相同 Unicode 字符的不同表示方式可能需要不同数量的内存空间来存储。 // 所以 Swift 中的字符在一个字符串中并不一定占用相同的内存空间。因此字符串的长度不得不通过迭代字符串中每一个字符的长度来进行计算。 // 如果您正在处理一个长字符串,需要注意countElements函数必须遍历字符串中的字符以精准计算字符串的长度。 // 另外需要注意的是通过countElements返回的字符数量并不总是与包含相同字符的NSString的length属性相同。 // NSString的length属性是基于利用 UTF-16 表示的十六位代码单元数字,而不是基于 Unicode 字符。 // 为了解决这个问题,NSString的length属性在被 Swift 的String访问时会成为utf16count。 let 🐌 = "蜗牛" println(🐌) // 您不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。 // 通过调用字符串的 hasPrefix/hasSuffix 方法来检查字符串是否拥有特定前缀/后缀。 两个方法均需要以字符串作为参数传入并传出Boolean值 // 可以通过字符串的 uppercaseString 和 lowercaseString 属性来访问大写/小写版本的字符串。 // 可以通过字符串的 utf8,utf16,unicodeScalars 来访问它的 UTF-8, UTF-16, 21位的 Unicode (Unicode Scalars) for c in "Anfield".utf8{ println(c) } // 2.4 // Swift 语言里的数组和字典中存储的数据值类型必须明确。数据值在被存储进入某个数组之前类型必须明确,方法是通过显式的类型标注或类型推断,而且不是必须是class类型。 // 声明数组可以用 Array<type> 或者 [type] 的方式 var shoppingList: [String] = ["iPhone","iPad","Mac"] // 通过类型推断也可以直接 var shoppingList = ["iPhone","iPad","Mac"] if !shoppingList.isEmpty{ shoppingList.append("iMac") shoppingList += ["MBA","MBP"] } println(shoppingList.count) shoppingList[2...5] = ["Google","Facebook"] shoppingList shoppingList.insert("Apple", atIndex: 2) shoppingList shoppingList.removeAtIndex(1) shoppingList.removeLast() shoppingList for (index, value) in enumerate(shoppingList){ println("\(index+1) : \(value)") } // 创建数组 var testArr1 = [Int]() var testArr2: [Int] = [] var testArr3 = [Int](count: 7, repeatedValue: 0) var testArr4 = Array(count: 7, repeatedValue: 0.0) // Swift 的字典使用Dictionary<KeyType, ValueType> ( 或者 [KeyType:ValueType] )定义,其中KeyType是字典中键的数据类型,ValueType是字典中对应于这些键所存储值的数据类型。 // KeyType的唯一限制就是可哈希的,这样可以保证它是独一无二的,所有的 Swift 基本类型(例如String,Int, Double和Bool)都是默认可哈希的,并且所有这些类型都可以在字典中当做键使用。 // 未关联值的枚举成员(参见枚举)也是默认可哈希的。 // Dictionary 的 updateValue(forKey:) 方法可以设置或者更新特定键对应的值,返回的时一个可选值,如果该键之前设置过值,那么返回之前的旧值,否则返回 nil var dic = [String:String]() dic = ["Name":"Liverpool","Location":"England","History":"Great","Fans":"KOP"] // 返回可选类型 var oldValue: String? = dic.updateValue("Steven", forKey:"Captain") dic dic.count // 返回可选类型 var cap: String? = dic["Captain"] // 可以通过设置 nil 值的方式,清除一个键值对 dic["Captain"] = nil dic // 返回可选类型 var history: String? = dic.removeValueForKey("History") dic dic.keys dic.values // 清空 Dictionary dic = [:] dic // 对字典来说,不可变性也意味着我们不能替换其中任何现有键所对应的值。不可变字典的内容在被首次设定之后不能更改。 // 不可变性对数组来说有一点不同,当然我们不能试着改变任何不可变数组的大小,但是我们可以重新设定相对现存索引所对应的值。 // Nil Coalescing Operator (a ?? b) // The nil coalescing operator is shorthand for the code below: // a != nil ? a! : b let defaultColorName = "red" var userDefinedColorName: String? // defaults to nil var colorNameToUse = userDefinedColorName ?? defaultColorName // 2.5 for index in 1...5 { println("\(index) times 5 is \(index * 5)") } // 不需要知道区间内每一项的值,可以使用下划线(_)替代变量名来忽略对值的访问: let base = 3 let power = 10 var answer = 1 for _ in 1...power { answer *= base } println("\(base) to the power of \(power) is \(answer)") // Swift 不需要使用圆括号将“initialization; condition; increment”包括起来。 for var index = 0; index < 3; ++index { println("index is \(index)") } // while循环的另外一种形式是do-while,它和while的区别是在判断循环条件之前,先执行一次循环的代码块,然后重复循环直到条件为false。 // 与 C 语言和 Objective-C 中的switch语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。 // 这也就是说,不需要在 case 分支中显式地使用break语句。 // 每一个 case 分支都必须包含至少一条语句. let anotherCharacter: Character = "a" switch anotherCharacter { case "a": println("The letter a") // 如果注释掉这行的话,会报编译错误 case "A": println("The letter A") default: println("Not the letter A") } // case 分支的模式也可以是一个值的区间。 let count = 3_000_000_000_000 let countedThings = "stars in the Milky Way" var naturalCount: String switch count { case 0: naturalCount = "no" case 1...3: naturalCount = "a few" case 4...9: naturalCount = "several" case 10...99: naturalCount = "tens of" case 100...999: naturalCount = "hundreds of" case 1000...999_999: naturalCount = "thousands of" default: naturalCount = "millions and millions of" } println("There are \(naturalCount) \(countedThings).") // 可以使用元组在同一个switch语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_)来匹配所有可能的值。 let somePoint = (1, 1) switch somePoint { case (0, 0): println("(0, 0) is at the origin") case (_, 0): println("(\(somePoint.0), 0) is on the x-axis") case (0, _): println("(0, \(somePoint.1)) is on the y-axis") case (-2...2, -2...2): println("(\(somePoint.0), \(somePoint.1)) is inside the box") default: println("(\(somePoint.0), \(somePoint.1)) is outside of the box") } // 不像 C 语言,Swift 允许多个 case 匹配同一个值。实际上,在这个例子中,点(0, 0)可以匹配所有四个 case。但是,如果存在多个匹配,那么只会执行第一个被匹配到的 case 分支。 // case 值绑定 let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): println("on the x-axis with an x value of \(x)") case (0, let y): println("on the y-axis with a y value of \(y)") case let (x, y): println("somewhere else at (\(x), \(y))") } // case 分支的模式可以使用where语句来判断额外的条件。 let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: println("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: println("(\(x), \(y)) is on the line x == -y") case let (x, y): println("(\(x), \(y)) is just some arbitrary point") } // 其他关键字 continue, break, fallthrough // 带标签的语句 let finalSquare = 25 var board = [Int](count: finalSquare + 1, repeatedValue: 0) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 var square1 = 0 var diceRoll = 0 // 声明一个标签 gameLoop: while square1 != finalSquare { if ++diceRoll == 7 { diceRoll = 1 } switch square1 + diceRoll { case finalSquare: // 到达最后一个方块,游戏结束 break gameLoop case let newSquare where newSquare > finalSquare: // 超出最后一个方块,再掷一次骰子 continue gameLoop default: // 本次移动有效 square1 += diceRoll square1 += board[square1] } } println("Game over!")
mit
6f940e33a8c82d58780af1ef3e96a315
25.976115
171
0.683195
2.937576
false
false
false
false
TongjiUAppleClub/WeCitizens
WeCitizens/ReplyTableViewController.swift
1
15777
// // ReplyTableViewController.swift // WeCitizens // // Created by Harold LIU on 2/24/16. // Copyright © 2016 Tongji Apple Club. All rights reserved. // import UIKit import MJRefresh import FoldingCell import MBProgressHUD class ReplyTableViewController: UITableViewController,SSRadioButtonControllerDelegate, JumpVoiceDelegate{ let kCloseCellHeight:CGFloat = 280 let kOpenCellHeight:CGFloat = 940 var cellHeights = [CGFloat]() var currentUserChoose:String?{ didSet{ print(currentUserChoose) } } var replyId:String? var voiceId:String? var replyList = [Reply]() var replyModel = ReplyModel() var userModel = UserModel() var queryTimes = 0 let number = 10 //MARK:- Life Cycle override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension self.clearsSelectionOnViewWillAppear = false if let id = replyId { // 根据ID获取reply replyModel.getReply(withId: id, resultHandler: { (result, error) in if let _ = error { print("get reply with id error: \(error)") } else { if let reply = result { print("get reply with id") print(reply.user) self.replyList.append(reply) self.cellHeights = [CGFloat](count: self.replyList.count, repeatedValue: self.kCloseCellHeight) self.tableView.reloadData() } } }) } else if let id = voiceId { print("id:\(id)") replyModel.getReplies(id).then { (replies) -> Void in if 0 == replies.count { let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.mode = .Text hud.labelText = "暂无回应" hud.hide(true, afterDelay: 2.0) } else { self.replyList = replies } self.cellHeights = [CGFloat](count: self.replyList.count, repeatedValue: self.kCloseCellHeight) self.tableView.reloadData() } .error { err in print("用voiceID获取reply时错误\(err)") } } else { tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in print("RefreshingHeader") //上拉刷新,在获取数据后清空旧数据,并做缓存 self.queryTimes = 0 self.getReplyFromRemote() dispatch_async(dispatch_get_main_queue()) { () -> Void in self.tableView.mj_header.endRefreshing() } }) tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { () -> Void in print("RefreshingFooter") //1.下拉加载数据,将新数据append到数组中,不缓存 self.replyModel.getReply(self.number, queryTimes: self.queryTimes, cityName: "shanghai", needStore: false, resultHandler: { (results, error) -> Void in if let _ = error { //有错误,给用户提示 print("get reply fail with error:\(error!.userInfo)") self.processError(error!.code) } else { if let replies = results { replies.forEach({ (reply) -> () in self.replyList.append(reply) }) self.cellHeights = [CGFloat](count: self.replyList.count, repeatedValue: self.kCloseCellHeight) self.tableView.reloadData() self.queryTimes += 1 } else { print("no data in refreshing footer") } } }) dispatch_async(dispatch_get_main_queue()) { () -> Void in self.tableView.mj_footer.endRefreshing() } }) tableView.mj_header.automaticallyChangeAlpha = true //1.读缓存,如果有数据的话在tableView中填数据 self.replyModel.getReply("shanghai") { (results, error) -> () in if let _ = error { //有错误,给用户提示 print("get reply from local fail with error:\(error!.userInfo)") self.processError(error!.code) } else { if let replies = results { self.replyList = replies self.cellHeights = [CGFloat](count: self.replyList.count, repeatedValue: self.kCloseCellHeight) self.tableView.reloadData() } else { //没取到数据 print("no data from local") } } } //2.向后台请求数据,返回数据时做缓存 getReplyFromRemote() } } func getReplyFromRemote() { self.replyModel.getReply(self.number, queryTimes: self.queryTimes, cityName: "shanghai", needStore: true, resultHandler: { (results, error) -> Void in if let _ = error { //有错误,给用户提示 print("get voice fail with error:\(error!.userInfo)") self.processError(error!.code) } else { if let replies = results { self.replyList = replies self.cellHeights = [CGFloat](count: self.replyList.count, repeatedValue: self.kCloseCellHeight) self.tableView.reloadData() self.queryTimes += 1 } else { //没取到数据 print("no data in refreshing header") } } }) } func jumpVoiceDetail(voiceId:String) { let controller = storyboard?.instantiateViewControllerWithIdentifier("VoiceDetailTableView") as! VoiceDetailTableViewController controller.voiceId = voiceId print("voice id: \(voiceId)") self.navigationController?.pushViewController(controller, animated: true) } func processError(errorCode:Int) { let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.mode = .Text let errorMessage:(label:String, detail:String) = convertPFNSErrorToMssage(errorCode) hud.labelText = errorMessage.label hud.detailsLabelText = errorMessage.detail hud.hide(true, afterDelay: 2.0) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.backgroundColor = UIColor(red: 216/255, green: 216/255, blue: 216/255, alpha: 1.0) } //MARK:- TableView Data Source & Delegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return replyList.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 2 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: (CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 0)) ) view.backgroundColor = UIColor.clearColor() return view } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell is FoldingCell { let foldingCell = cell as! FoldingCell foldingCell.backgroundColor = UIColor.clearColor() if cellHeights[indexPath.section] == kCloseCellHeight { foldingCell.selectedAnimation(false, animated: false, completion:nil) } else { foldingCell.selectedAnimation(true, animated: false, completion: nil) } } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FoldingCell", forIndexPath: indexPath) as! ReplyTableViewCell imagesBinder(cell.imgContainer, images: self.replyList[indexPath.section].images) dataBinder(cell, reply: self.replyList[indexPath.section]) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return cellHeights[indexPath.section] } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! FoldingCell if cell.isAnimating() { return } var duration = 0.0 if cellHeights[indexPath.section] == kCloseCellHeight { // open cell cellHeights[indexPath.section] = kOpenCellHeight cell.selectedAnimation(true, animated: true, completion: nil) duration = 0.5 } else {// close cell cellHeights[indexPath.section] = kCloseCellHeight cell.selectedAnimation(false, animated: true, completion: nil) duration = 0.8 } UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { () -> Void in tableView.beginUpdates() tableView.endUpdates() }, completion: nil) } //MARK:- Actions //TODO:- User Action Update to the server func CheckResponse(sender:UIButton) { print("查看相关提议\(sender.tag)") } func CheckHistory(sender:UIButton) { print("查看过往\(sender.tag)") } func Submit(sender:UIButton) { print("提交\(sender.tag)") print("当前选择:\(currentUserChoose)") } func didSelectButton(aButton: UIButton?) { // print(aButton?.titleLabel?.text) currentUserChoose = aButton?.titleLabel?.text } func ScrollToEvaluate(sender:UIButton) { let indexPath = NSIndexPath(forRow: 0, inSection: sender.tag) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true) } //MARK:- Data Binder func dataBinder(cell:ReplyTableViewCell,reply: Reply) { let user = reply.user! cell.voiceId = reply.voiceId cell.delegate = self if let image = user.avatar { cell.Favatar.image = image cell.CAvatar.image = image } else { cell.Favatar.image = UIImage(named: "avatar") cell.CAvatar.image = UIImage(named: "avatar") } cell.FAgency.text = user.userName cell.CAgency.text = user.userName cell.ResponseTitle.text = reply.title cell.CTitle.text = reply.title cell.SupportPercent.text = "\(reply.satisfyLevel.satisfaction)%"//满意率 cell.CSupport.text = "本回应的当前满意率为 \(reply.satisfyLevel.satisfaction)%" cell.CContent.text = reply.content let dateStr = reply.dateStr cell.ResponseTime.text = dateStr cell.CResponseTime.text = dateStr //投票这个功能不简单,让我再想想 // if let attitude = reply.satisfyLevel!.attitude { // //这人有态度,把态度值填上,提交按钮禁用 // } else { // //还未投票 // } var tmp = [CGFloat]() tmp.append(CGFloat(reply.satisfyLevel.level1)) tmp.append(CGFloat(reply.satisfyLevel.level2)) tmp.append(CGFloat(reply.satisfyLevel.level3)) tmp.append(CGFloat(reply.satisfyLevel.level4)) cell.drawBarChart(tmp) } func imagesBinder(containter:UIView,images:[UIImage]) { let Xoffset = CGFloat(6) let Yoffset = CGFloat(4) for view in containter.subviews { if view.tag == 1 { view.removeFromSuperview() } } switch images.count { case 1: let imgView = UIImageView(image: images.first) imgView.frame = containter.frame imgView.frame.origin = CGRectZero.origin imgView.frame.size.width = tableView.frame.width - 40 containter.addSubview(imgView) break; case 2: let img1 = UIImageView(image: images[1]) img1.frame = containter.frame img1.frame.origin = CGRectZero.origin img1.frame.size.width = tableView.frame.width - 30 img1.frame.size.width /= 2 containter.addSubview(img1) let img2 = UIImageView(image: images[0]) img2.frame = img1.frame img2.frame.origin.x += (img2.frame.size.width + Xoffset) containter.addSubview(img2) break; case 3: let img1 = UIImageView(image: images[0]) img1.frame = containter.frame img1.frame.size.width = tableView.frame.width - 40 img1.frame.origin = CGRectZero.origin img1.frame.size.width /= 2 img1.frame.size.height += Yoffset containter.addSubview(img1) let img2 = UIImageView(image: images[1]) img2.frame = img1.frame img2.frame.origin.x += (img2.frame.size.width + Xoffset) img2.frame.size.height /= 2 containter.addSubview(img2) let img3 = UIImageView(image: images[2]) img3.frame = img2.frame img3.frame.origin.y += img3.frame.size.height + Yoffset containter.addSubview(img3) break; case 4: let img1 = UIImageView(image: images[0]) img1.frame = containter.frame img1.frame.size.width = tableView.frame.width - 40 img1.frame.origin = CGRectZero.origin img1.frame.size.width /= 2 img1.frame.size.height /= 2 containter.addSubview(img1) let img2 = UIImageView(image: images[1]) img2.frame = img1.frame img2.frame.origin.x += (img2.frame.size.width + Xoffset) containter.addSubview(img2) let img3 = UIImageView(image: images[2]) img3.frame = img2.frame img3.frame.origin.y += img3.frame.size.height + Yoffset containter.addSubview(img3) let img4 = UIImageView(image: images[3]) img4.frame = img3.frame img4.frame.origin.x = img1.frame.origin.x containter.addSubview(img4) break; default: containter.removeFromSuperview() break; } for view in containter.subviews { view.tag = 1 view.layer.masksToBounds = false view.layer.cornerRadius = 5 view.clipsToBounds = true } } }
mit
9762ade561f1d5b4f4cc9dbe355db7ac
36.368932
167
0.553975
4.94095
false
false
false
false
vector-im/vector-ios
Riot/Managers/UISIAutoReporter/UISIAutoReporter.swift
1
8547
// // Copyright 2021 New Vector Ltd // // 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 import MatrixSDK import Combine struct UISIAutoReportData { let eventId: String? let roomId: String? let senderKey: String? let deviceId: String? let userId: String? let sessionId: String? } extension UISIAutoReportData: Codable { enum CodingKeys: String, CodingKey { case eventId = "event_id" case roomId = "room_id" case senderKey = "sender_key" case deviceId = "device_id" case userId = "user_id" case sessionId = "session_id" } } /// Listens for failed decryption events and silently sends reports RageShake server. /// Also requests that message senders send a matching report to have both sides of the interaction. @available(iOS 14.0, *) @objcMembers class UISIAutoReporter: NSObject, UISIDetectorDelegate { struct ReportInfo: Hashable { let roomId: String let sessionId: String } // MARK: - Properties private static let autoRsRequest = "im.vector.auto_rs_request" private static let reportSpacing = 60 private let bugReporter: MXBugReportRestClient private let dispatchQueue = DispatchQueue(label: "io.element.UISIAutoReporter.queue") // Simple in memory cache of already sent report private var alreadyReportedUisi = Set<ReportInfo>() private let e2eDetectedSubject = PassthroughSubject<UISIDetectedMessage, Never>() private let matchingRSRequestSubject = PassthroughSubject<MXEvent, Never>() private var cancellables = Set<AnyCancellable>() private var sessions = [MXSession]() private var enabled = false { didSet { guard oldValue != enabled else { return } detector.enabled = enabled } } // MARK: - Setup override init() { self.bugReporter = MXBugReportRestClient.vc_bugReportRestClient(appName: BuildSettings.bugReportUISIId) super.init() // Simple rate limiting, for any rage-shakes emitted we guarantee a spacing between requests. e2eDetectedSubject .bufferAndSpace(spacingDelay: Self.reportSpacing) .sink { [weak self] in guard let self = self else { return } self.sendRageShake(source: $0) }.store(in: &cancellables) matchingRSRequestSubject .bufferAndSpace(spacingDelay: Self.reportSpacing) .sink { [weak self] in guard let self = self else { return } self.sendMatchingRageShake(source: $0) }.store(in: &cancellables) self.enabled = RiotSettings.shared.enableUISIAutoReporting RiotSettings.shared.publisher(for: RiotSettings.UserDefaultsKeys.enableUISIAutoReporting) .sink { [weak self] _ in guard let self = self else { return } self.enabled = RiotSettings.shared.enableUISIAutoReporting } .store(in: &cancellables) } private lazy var detector: UISIDetector = { let detector = UISIDetector() detector.delegate = self return detector }() var reciprocateToDeviceEventType: String { return Self.autoRsRequest } // MARK: - Public func uisiDetected(source: UISIDetectedMessage) { dispatchQueue.async { let reportInfo = ReportInfo(roomId: source.roomId, sessionId: source.sessionId) let alreadySent = self.alreadyReportedUisi.contains(reportInfo) if !alreadySent { self.alreadyReportedUisi.insert(reportInfo) self.e2eDetectedSubject.send(source) } } } func add(_ session: MXSession) { sessions.append(session) detector.enabled = enabled session.eventStreamService.add(eventStreamListener: detector) } func remove(_ session: MXSession) { if let index = sessions.firstIndex(of: session) { sessions.remove(at: index) } session.eventStreamService.remove(eventStreamListener: detector) } func uisiReciprocateRequest(source: MXEvent) { guard source.type == Self.autoRsRequest else { return } self.matchingRSRequestSubject.send(source) } // MARK: - Private private func sendRageShake(source: UISIDetectedMessage) { MXLog.debug("[UISIAutoReporter] sendRageShake") guard let session = sessions.first else { return } let uisiData = UISIAutoReportData( eventId: source.eventId, roomId: source.roomId, senderKey: source.senderKey, deviceId: source.senderDeviceId, userId: source.senderUserId, sessionId: source.sessionId ).jsonString ?? "" self.bugReporter.vc_sendBugReport( description: "Auto-reporting decryption error", sendLogs: true, sendCrashLog: true, additionalLabels: [ "Z-UISI", "ios", "uisi-recipient" ], customFields: ["auto_uisi": uisiData], success: { reportUrl in let contentMap = MXUsersDevicesMap<NSDictionary>() let content = [ "event_id": source.eventId, "room_id": source.roomId, "session_id": source.sessionId, "device_id": source.senderDeviceId, "user_id": source.senderUserId, "sender_key": source.senderKey, "recipient_rageshake": reportUrl ] contentMap.setObject(content as NSDictionary, forUser: source.senderUserId, andDevice: source.senderDeviceId) session.matrixRestClient.sendDirectToDevice( eventType: Self.autoRsRequest, contentMap: contentMap, txnId: nil ) { response in if response.isFailure { MXLog.warning("failed to send auto-uisi to device") } } }, failure: { [weak self] error in guard let self = self else { return } self.dispatchQueue.async { self.alreadyReportedUisi.remove(ReportInfo(roomId: source.roomId, sessionId: source.sessionId)) } }) } private func sendMatchingRageShake(source: MXEvent) { MXLog.debug("[UISIAutoReporter] sendMatchingRageShake") let eventId = source.content["event_id"] as? String let roomId = source.content["room_id"] as? String let sessionId = source.content["session_id"] as? String let deviceId = source.content["device_id"] as? String let userId = source.content["user_id"] as? String let senderKey = source.content["sender_key"] as? String let matchingIssue = source.content["recipient_rageshake"] as? String var description = "Auto-reporting decryption error (sender)" if let matchingIssue = matchingIssue { description += "\nRecipient rageshake: \(matchingIssue)" } let uisiData = UISIAutoReportData( eventId: eventId, roomId: roomId, senderKey: senderKey, deviceId: deviceId, userId: userId, sessionId: sessionId ).jsonString ?? "" self.bugReporter.vc_sendBugReport( description: description, sendLogs: true, sendCrashLog: true, additionalLabels: [ "Z-UISI", "ios", "uisi-sender" ], customFields: [ "auto_uisi": uisiData, "recipient_rageshake": matchingIssue ?? "" ] ) } }
apache-2.0
921fa4fbcdb22bd11bb5aca020e7165a
35.216102
125
0.597754
4.859011
false
false
false
false
troystribling/BlueCap
Examples/BlueCap/BlueCap/Utils/UIAlertControllerExtensions.swift
1
1348
// // UIAlertViewExtensions.swift // BlueCap // // Created by Troy Stribling on 7/6/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit extension UIAlertController { class func alert(title: String? = nil, error: Swift.Error, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController { let alert = UIAlertController(title: title ?? "Error", message: error.localizedDescription, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: handler)) return alert } class func alertOnErrorWithMessage(_ message: String, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController { let alert = UIAlertController(title: "Error", message:message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:handler)) return alert } class func alert(message: String, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController { let alert = UIAlertController(title: "Alert", message:message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:handler)) return alert } }
mit
a0ce72a3b0dabed88459ca879e43571a
42.483871
146
0.703264
4.493333
false
false
false
false
FutureXInc/kulture
Kultur/Kulture/HomeContainerViewController.swift
1
2815
// // HomeContainerViewController.swift // Kulture // // Created by Bhalla, Kapil on 5/7/17. // Copyright © 2017 FutureXInc. All rights reserved. // import UIKit class HomeContainerViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var menuView: UIView! @IBOutlet weak var contentView: UIView! var originalLeftMargin: CGFloat! var contentViewController: UIViewController! { didSet(oldContentViewController) { view.layoutIfNeeded() if oldContentViewController != nil { oldContentViewController.willMove(toParentViewController: nil) oldContentViewController.view.removeFromSuperview() oldContentViewController.didMove(toParentViewController: nil) } contentViewController.willMove(toParentViewController: self) contentView.addSubview(contentViewController.view) contentViewController.didMove(toParentViewController: self) UIView.animate(withDuration: 0.3) { () -> Void in self.leftMarginConstraint.constant = 0 self.view.layoutIfNeeded() } } } var menuViewController: MenuViewController! { didSet { // to initialize the view view.layoutIfNeeded() // add to the menu view the view contained in the menuViewController. menuView.addSubview(menuViewController.view) } } @IBAction func slideContentViewPGR(_ sender: UIPanGestureRecognizer) { // print ("Sliding the view") let translation = sender.translation(in: view) let velocity = sender.velocity(in: view) if sender.state == .began { originalLeftMargin = leftMarginConstraint.constant } else if sender.state == .changed { leftMarginConstraint.constant = originalLeftMargin + translation.x } else if sender.state == .ended { UIView.animate(withDuration: 0.4, animations: { if velocity.x > 0 { // open menu view self.leftMarginConstraint.constant = self.view.frame.size.width - 125 } else { // close menu view self.leftMarginConstraint.constant = 0 } self.view.layoutIfNeeded() }) } } @IBOutlet weak var leftMarginConstraint: NSLayoutConstraint! }
apache-2.0
335eca4ad071ff29481a5c395e2850aa
30.617978
89
0.599502
5.696356
false
false
false
false
mutualmobile/VIPER-SWIFT
VIPER-SWIFT/Classes/Modules/Add/User Interface/Transition/AddDismissalTransition.swift
1
1366
// // AddDismissalTransition.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit class AddDismissalTransition : NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.72 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! AddViewController let finalCenter = CGPoint(x: 160.0, y: (fromVC.view.bounds.size.height / 2) - 1000.0) let options = UIViewAnimationOptions.curveEaseIn UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 0.64, initialSpringVelocity: 0.22, options: options, animations: { fromVC.view.center = finalCenter fromVC.transitioningBackgroundView.alpha = 0.0 }, completion: { finished in fromVC.view.removeFromSuperview() transitionContext.completeTransition(true) } ) } }
mit
0abbc5a96245ebe5d0202b1b9c7846fe
33.15
126
0.65593
5.485944
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/MomentModule/Model/CWMoment.swift
2
1903
// // CWMoment.swift // CWWeChat // // Created by wei chen on 2017/3/29. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit enum CWMomentType: Int { case normal // 图文 case vidio // 视频 case url case music //音乐 } /// 图片 class CWMomentPhoto: NSObject { var thumbnailURL: URL var largetURL: URL var size: CGSize = CGSize.zero init(thumbnailURL: URL, largetURL: URL, size: CGSize = .zero) { self.thumbnailURL = thumbnailURL self.largetURL = largetURL self.size = size } } class CWMomentVideo: NSObject { var videoURL: URL init(videoURL: URL) { self.videoURL = videoURL } } class CWMultimedia: NSObject { var url: URL var imageURL: URL var title: String var source: String? init(url: URL, imageURL: URL, title: String, source: String? = nil) { self.url = url self.imageURL = imageURL self.title = title self.source = source } } class CWMoment: NSObject { /// 分享id var momentId: String /// 用户名 var username: String /// 用户id var userId: String var date: Date var type: CWMomentType = .normal var content: String? var videoModel: CWMomentVideo? var multimedia: CWMultimedia? var imageArray = [CWMomentPhoto]() var commentArray = [CWMomentReply]() var praiseArray = [CWMomentReply]() // 是否上传成功 var sendSuccess: Bool = true // 是否已经读过 var isRead: Bool = false // 是否点赞 var isPraise: Bool = false // 是否删除 var isDelete: Bool = false init(momentId: String, username: String, userId: String, date: Date) { self.momentId = momentId self.username = username self.userId = userId self.date = date } }
mit
c5c67e0d64b2b74afc073182ea679633
18.891304
74
0.595628
3.868922
false
false
false
false
lanjing99/RxSwiftDemo
03-subjects-and-variable/challenge/Challenge1-Finished/RxSwift.playground/Contents.swift
1
2047
//: Please build the scheme 'RxSwiftPlayground' first import RxSwift example(of: "PublishSubject") { let disposeBag = DisposeBag() let dealtHand = PublishSubject<[(String, Int)]>() func deal(_ cardCount: UInt) { var deck = cards var cardsRemaining: UInt32 = 52 var hand = [(String, Int)]() for _ in 0..<cardCount { let randomIndex = Int(arc4random_uniform(cardsRemaining)) hand.append(deck[randomIndex]) deck.remove(at: randomIndex) cardsRemaining -= 1 } // Add code to update dealtHand here if points(for: hand) > 21 { dealtHand.onError(HandError.busted) } else { dealtHand.onNext(hand) } } // Add subscription to handSubject here dealtHand .subscribe( onNext: { print(cardString(for: $0), "for", points(for: $0), "points") }, onError: { print(String(describing: $0).capitalized) }) .addDisposableTo(disposeBag) deal(3) } /*: 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
aff809bc9d376acb9db2cd97f9fe09c9
30.984375
78
0.710308
4.355319
false
false
false
false
shajrawi/swift
validation-test/stdlib/StringViews.swift
4
25367
//===--- StringViews.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 // //===----------------------------------------------------------------------===// // RUN: %target-run-stdlib-swift // REQUIRES: executable_test import Swift import StdlibUnittest import StdlibUnicodeUnittest import StdlibCollectionUnittest #if _runtime(_ObjC) // FIXME: Foundation leaks through StdlibUnittest. It adds some conformances // that overload resolution picks up in this code. import Foundation #endif // CHECK: testing... print("testing...") let replacementUTF16: UTF16.CodeUnit = 0xFFFD let replacementUTF8: [UTF8.CodeUnit] = [0xEF, 0xBF, 0xBD] let replacementScalar = UnicodeScalar(replacementUTF16)! let replacementCharacter = Character(replacementScalar) // This string contains a variety of non-ASCII characters, including // Unicode scalars that must be represented with a surrogate pair in // UTF16, grapheme clusters composed of multiple Unicode scalars, and // invalid UTF16 that should be replaced with replacement characters. let winterUTF16 = Array("🏂☃❅❆❄︎⛄️❄️".utf16) + [0xD83C, 0x0020, 0xDF67, 0xD83C] var winter = winterUTF16.withUnsafeBufferPointer { String._fromInvalidUTF16($0) } let winterInvalidUTF8: [UTF8.CodeUnit] = replacementUTF8 + ([0x20] as [UTF8.CodeUnit]) + replacementUTF8 + replacementUTF8 let winterUTF8: [UTF8.CodeUnit] = [ 0xf0, 0x9f, 0x8f, 0x82, 0xe2, 0x98, 0x83, 0xe2, 0x9d, 0x85, 0xe2, 0x9d, 0x86, 0xe2, 0x9d, 0x84, 0xef, 0xb8, 0x8e, 0xe2, 0x9b, 0x84, 0xef, 0xb8, 0x8f, 0xe2, 0x9d, 0x84, 0xef, 0xb8, 0x8f ] + winterInvalidUTF8 let summer = "school's out!" let summerBytes: [UInt8] = [ 0x73, 0x63, 0x68, 0x6f, 0x6f, 0x6c, 0x27, 0x73, 0x20, 0x6f, 0x75, 0x74, 0x21] var tests = TestSuite("StringViews") tests.test("decoding") { expectEqualSequence( winterUTF8, winter.utf8 ) expectEqualSequence( [0xd83c, 0xdfc2, 0x2603, 0x2745, 0x2746, 0x2744, 0xfe0e, 0x26c4, 0xfe0f, 0x2744, 0xfe0f, replacementUTF16, 0x0020, replacementUTF16, replacementUTF16 ], winter.utf16 ) expectEqualSequence( summerBytes, summer.utf8 ) expectEqualSequence( summerBytes.map {UTF16.CodeUnit($0)}, summer.utf16 ) } // winter UTF8 grapheme clusters ([]) and unicode scalars (|) // [f0 9f 8f 82] [e2 98 83] [e2 9d 85] [e2 9d 86] [e2 9d 84 | ef b8 8e] // [e2 9b 84 | ef b8 8f] [e2 9d 84 | ef b8 8f] //===--- To UTF8 ----------------------------------------------------------===// func checkToUTF8( _ id: String, mapIndex: @escaping (String.Index, String.UTF8View)->String.Index? ) { tests.test("index-mapping/character-to-utf8/\(id)") { // the first three utf8 code units at the start of each grapheme // cluster expectEqualSequence( [ [0xf0, 0x9f, 0x8f], [0xe2, 0x98, 0x83], [0xe2, 0x9d, 0x85], [0xe2, 0x9d, 0x86], [0xe2, 0x9d, 0x84], [0xe2, 0x9b, 0x84], [0xe2, 0x9d, 0x84], replacementUTF8, [0x20] + replacementUTF8[0..<2], replacementUTF8, replacementUTF8 ] as [[UTF8.CodeUnit]], winter.indices.map { i in (0..<3).map { let w = winter return w.utf8[w.utf8.index(mapIndex(i, w.utf8)!, offsetBy: $0)] } }, sameValue: ==) expectEqual( winter.utf8.endIndex, mapIndex(winter.endIndex, winter.utf8)) expectEqualSequence( summerBytes, summer.indices.map { summer.utf8[mapIndex($0, summer.utf8)!] } ) expectEqual( summer.utf8.endIndex, mapIndex(summer.endIndex, summer.utf8)) } tests.test("index-mapping/unicode-scalar-to-utf8/\(id)") { // the first three utf8 code units at the start of each unicode // scalar expectEqualSequence( [ [0xf0, 0x9f, 0x8f], [0xe2, 0x98, 0x83], [0xe2, 0x9d, 0x85], [0xe2, 0x9d, 0x86], [0xe2, 0x9d, 0x84], [0xef, 0xb8, 0x8e], [0xe2, 0x9b, 0x84], [0xef, 0xb8, 0x8f], [0xe2, 0x9d, 0x84], [0xef, 0xb8, 0x8f], replacementUTF8, [0x20] + replacementUTF8[0..<2], replacementUTF8, replacementUTF8 ] as [[UTF8.CodeUnit]], winter.unicodeScalars.indices.map { i in (0..<3).map { let w = winter return w.utf8[w.utf8.index(mapIndex(i, w.utf8)!, offsetBy: $0)] } }, sameValue: ==) expectEqual( winter.utf8.endIndex, mapIndex(winter.unicodeScalars.endIndex, winter.utf8)) expectEqualSequence( summerBytes, summer.unicodeScalars.indices.map { summer.utf8[mapIndex($0, summer.utf8)!] } ) expectEqual( summer.utf8.endIndex, mapIndex(summer.unicodeScalars.endIndex, summer.utf8)) } tests.test("index-mapping/utf16-to-utf8/\(id)") { // check the first three utf8 code units at the start of each utf16 // code unit expectEqualSequence( [ [0xf0, 0x9f, 0x8f], // Prior to UTF-8 String, this tested for empty array in "legacy mode" or // the replacemnet character otherwise. However, SE-0180 (String Index // Overhual) dictates subscript behavior should treat it as emergent // behavior from its encoded offset, hence we should get the same 3 code // units as prior for non-scalar-aligned UTF-16 offsets applied to the // UTF-8 view. // // Old code: // // does not align with any utf8 code unit // id == "legacy" ? [] : replacementUTF8, id == "legacy" ? [] : [0xf0, 0x9f, 0x8f], [0xe2, 0x98, 0x83], [0xe2, 0x9d, 0x85], [0xe2, 0x9d, 0x86], [0xe2, 0x9d, 0x84], [0xef, 0xb8, 0x8e], [0xe2, 0x9b, 0x84], [0xef, 0xb8, 0x8f], [0xe2, 0x9d, 0x84], [0xef, 0xb8, 0x8f], replacementUTF8, [0x20] + replacementUTF8[0..<2], replacementUTF8, replacementUTF8 ] as [[UTF8.CodeUnit]], winter.utf16.indices.map { i16 in mapIndex(i16, winter.utf8).map { i8 in (0..<3).map { winter.utf8[winter.utf8.index(i8, offsetBy: $0)] } } ?? [] }, sameValue: ==) expectNotNil(mapIndex(winter.utf16.endIndex, winter.utf8)) expectEqual( winter.utf8.endIndex, mapIndex(winter.utf16.endIndex, winter.utf8)!) expectEqualSequence( summerBytes, summer.utf16.indices.map { summer.utf8[mapIndex($0, summer.utf8)!] } ) expectNotNil(mapIndex(summer.utf16.endIndex, summer.utf8)) expectEqual( summer.utf8.endIndex, mapIndex(summer.utf16.endIndex, summer.utf8)!) } tests.test("index-mapping/utf8-to-utf8/\(id)") { // should always succeed for i in winter.utf8.indices { expectEqual(i, mapIndex(i, winter.utf8)!) } } } checkToUTF8("legacy") { $0.samePosition(in: $1) } checkToUTF8("interchange") { i, _ in i } //===--- To UTF16 ---------------------------------------------------------===// func checkToUTF16( _ id: String, mapIndex: @escaping (String.Index, String.UTF16View)->String.Index? ) { func err(_ codeUnit: Unicode.UTF16.CodeUnit) -> Unicode.UTF16.CodeUnit? { return id == "legacy" ? nil : codeUnit } tests.test("index-mapping/character-to-utf16/\(id)") { expectEqualSequence( [ 0xd83c, // 0xdfc2, 0x2603, 0x2745, 0x2746, 0x2744, // 0xfe0e, 0x26c4, // 0xfe0f, 0x2744, // 0xfe0f, replacementUTF16, 0x20, replacementUTF16, replacementUTF16 ] as [UTF16.CodeUnit], winter.indices.map { winter.utf16[mapIndex($0, winter.utf16)!] }, sameValue: ==) expectEqual(winter.utf16.endIndex, mapIndex(winter.endIndex, winter.utf16)) expectEqualSequence( summerBytes.map { UTF16.CodeUnit($0) }, summer.indices.map { summer.utf16[mapIndex($0, summer.utf16)!] } ) expectEqual(summer.utf16.endIndex, mapIndex(summer.endIndex, summer.utf16)) } tests.test("index-mapping/unicode-scalar-to-utf16/\(id)") { expectEqualSequence( [ 0xd83c, // 0xdfc2, 0x2603, 0x2745, 0x2746, 0x2744, 0xfe0e, 0x26c4, 0xfe0f, 0x2744, 0xfe0f, replacementUTF16, 0x20, replacementUTF16, replacementUTF16 ] as [UTF16.CodeUnit], winter.unicodeScalars.indices.map { winter.utf16[mapIndex($0, winter.utf16)!] }) expectEqual( winter.utf16.endIndex, mapIndex(winter.unicodeScalars.endIndex, winter.utf16)) expectEqualSequence( summerBytes.map { UTF16.CodeUnit($0) }, summer.unicodeScalars.indices.map { summer.utf16[mapIndex($0, summer.utf16)!] } ) expectEqual( summer.utf16.endIndex, mapIndex(summer.unicodeScalars.endIndex, summer.utf16)) } tests.test("index-mapping/utf8-to-utf16/\(id)") { expectEqualSequence( [ 0xd83c, err(0xd83c), err(0xd83c), err(0xd83c), 0x2603, err(0x2603), err(0x2603), 0x2745, err(0x2745), err(0x2745), 0x2746, err(0x2746), err(0x2746), 0x2744, err(0x2744), err(0x2744), 0xfe0e, err(0xfe0e), err(0xfe0e), 0x26c4, err(0x26c4), err(0x26c4), 0xfe0f, err(0xfe0f), err(0xfe0f), 0x2744, err(0x2744), err(0x2744), 0xfe0f, err(0xfe0f), err(0xfe0f), replacementUTF16, err(replacementUTF16), err(replacementUTF16), 0x20, replacementUTF16, err(replacementUTF16), err(replacementUTF16), replacementUTF16, err(replacementUTF16), err(replacementUTF16) ] as [UTF16.CodeUnit?], winter.utf8.indices.map { mapIndex($0, winter.utf16).map { winter.utf16[$0] } }, sameValue: ==) expectNotNil(mapIndex(winter.utf8.endIndex, winter.utf16)) expectEqual( winter.utf16.endIndex, mapIndex(winter.utf8.endIndex, winter.utf16)!) expectEqualSequence( summerBytes.map { UTF16.CodeUnit($0) }, summer.utf8.indices.map { summer.utf16[mapIndex($0, summer.utf16)!] } ) expectNotNil(mapIndex(summer.utf8.endIndex, summer.utf16)) expectEqual( summer.utf16.endIndex, mapIndex(summer.utf8.endIndex, summer.utf16)!) } } checkToUTF16("legacy") { $0.samePosition(in: $1) } checkToUTF16("interchange") { i, _ in i } //===--- To UnicodeScalar -------------------------------------------------===// func checkToUnicodeScalar( _ id: String, mapIndex: @escaping (String.Index, String.UnicodeScalarView)->String.Index? ) { func err(_ scalarValue: UInt32) -> UnicodeScalar? { return id == "legacy" ? nil : UnicodeScalar(scalarValue) } tests.test("index-mapping/character-to-unicode-scalar/\(id)") { let winterCharacterUnicodeScalars: [UnicodeScalar] = [ UnicodeScalar(0x1f3c2)!, UnicodeScalar(0x2603)!, UnicodeScalar(0x2745)!, UnicodeScalar(0x2746)!, UnicodeScalar(0x2744)!, // 0xfe0e, UnicodeScalar(0x26c4)!, // 0xfe0f, UnicodeScalar(0x2744)!, // 0xfe0f replacementScalar, UnicodeScalar(0x20)!, replacementScalar, replacementScalar ] expectEqualSequence( winterCharacterUnicodeScalars, winter.indices.map { let w = winter return w.unicodeScalars[mapIndex($0, w.unicodeScalars)!] }) expectEqual(winter.unicodeScalars.endIndex, mapIndex(winter.endIndex, winter.unicodeScalars)) expectEqualSequence( summerBytes.map { UnicodeScalar($0) }, summer.indices.map { summer.unicodeScalars[mapIndex($0, summer.unicodeScalars)!] } ) expectEqual(summer.unicodeScalars.endIndex, mapIndex(summer.endIndex, summer.unicodeScalars)) } tests.test("index-mapping/utf8-to-unicode-scalar/\(id)") { // Define expectation separately to help the type-checker, which // otherwise runs out of time solving. let winterUtf8UnicodeScalars: [UnicodeScalar?] = [ UnicodeScalar(0x1f3c2), err(0x1f3c2), err(0x1f3c2), err(0x1f3c2), UnicodeScalar(0x2603), err(0x2603), err(0x2603), UnicodeScalar(0x2745), err(0x2745), err(0x2745), UnicodeScalar(0x2746), err(0x2746), err(0x2746), UnicodeScalar(0x2744), err(0x2744), err(0x2744), UnicodeScalar(0xfe0e), err(0xfe0e), err(0xfe0e), UnicodeScalar(0x26c4), err(0x26c4), err(0x26c4), UnicodeScalar(0xfe0f), err(0xfe0f), err(0xfe0f), UnicodeScalar(0x2744), err(0x2744), err(0x2744), UnicodeScalar(0xfe0f), err(0xfe0f), err(0xfe0f), replacementScalar, err(replacementScalar.value), err(replacementScalar.value), UnicodeScalar(0x20), replacementScalar, err(replacementScalar.value), err(replacementScalar.value), replacementScalar, err(replacementScalar.value), err(replacementScalar.value) ] expectEqualSequence( winterUtf8UnicodeScalars, winter.utf8.indices.map { i in mapIndex(i, winter.unicodeScalars).map { winter.unicodeScalars[$0] } }, sameValue: ==) expectNotNil(mapIndex(winter.utf8.endIndex, winter.unicodeScalars)) expectEqual( winter.unicodeScalars.endIndex, mapIndex(winter.utf8.endIndex, winter.unicodeScalars)!) expectEqualSequence( summerBytes.map { UnicodeScalar($0) as UnicodeScalar? }, summer.utf8.indices.map { i in mapIndex(i, summer.unicodeScalars).map { summer.unicodeScalars[$0] } }, sameValue: ==) expectNotNil(mapIndex(summer.utf8.endIndex, summer.unicodeScalars)) expectEqual( summer.unicodeScalars.endIndex, mapIndex(summer.utf8.endIndex, summer.unicodeScalars)!) } tests.test("index-mapping/utf16-to-unicode-scalar/\(id)") { let winterUtf16UnicodeScalars: [UnicodeScalar?] = [ UnicodeScalar(0x1f3c2), // Prior to UTF-8 String, this tested for empty array in "legacy mode" or // the replacemnet character otherwise. However, SE-0180 (String Index // Overhual) dictates subscript behavior should treat it as emergent // behavior from its encoded offset, hence we should get the same 3 code // units as prior for non-scalar-aligned UTF-16 offsets applied to the // UTF-8 view. // // Old code: // err(replacementScalar.value), err(0x1f3c2), UnicodeScalar(0x2603), UnicodeScalar(0x2745), UnicodeScalar(0x2746), UnicodeScalar(0x2744), UnicodeScalar(0xfe0e), UnicodeScalar(0x26c4), UnicodeScalar(0xfe0f), UnicodeScalar(0x2744), UnicodeScalar(0xfe0f), replacementScalar, UnicodeScalar(0x20), replacementScalar, replacementScalar ] expectEqualSequence( winterUtf16UnicodeScalars, winter.utf16.indices.map { i in mapIndex(i, winter.unicodeScalars).map { winter.unicodeScalars[$0] } }, sameValue: ==) expectNotNil(mapIndex(winter.utf16.endIndex, winter.unicodeScalars)) expectEqual( winter.unicodeScalars.endIndex, mapIndex(winter.utf16.endIndex, winter.unicodeScalars)!) expectEqualSequence( summerBytes.map { UnicodeScalar($0) as UnicodeScalar? }, summer.utf16.indices.map { i in mapIndex(i, summer.unicodeScalars).map { summer.unicodeScalars[$0] } }, sameValue: ==) expectNotNil(mapIndex(summer.utf16.endIndex, summer.unicodeScalars)) expectEqual( summer.unicodeScalars.endIndex, mapIndex(summer.utf16.endIndex, summer.unicodeScalars)!) } } checkToUnicodeScalar("legacy") { $0.samePosition(in: $1) } checkToUnicodeScalar("interchange") { i, _ in i } //===--- To Character -----------------------------------------------------===// func checkToCharacter( _ id: String, mapIndex: @escaping (String.Index, String)->String.Index? ) { func err(_ c: Character) -> Character? { return id == "legacy" ? nil : c } tests.test("index-mapping/unicode-scalar-to-character/\(id)") { let winterUnicodeScalarCharacters: [Character?] = [ "🏂", "☃", "❅", "❆", "❄︎", err("\u{FE0E}"), "⛄️", err("\u{FE0F}"), "❄️", err("\u{FE0F}"), replacementCharacter, "\u{20}", replacementCharacter, replacementCharacter ] expectEqualSequence( winterUnicodeScalarCharacters, winter.unicodeScalars.indices.map { i in mapIndex(i, winter).map { winter[$0] } }, sameValue: ==) expectEqual(winter.endIndex, mapIndex(winter.unicodeScalars.endIndex, winter)!) expectEqualSequence( summerBytes.map { Character(UnicodeScalar($0)) }, summer.unicodeScalars.indices.map { summer[mapIndex($0, summer)!] } ) expectEqual(summer.endIndex, mapIndex(summer.unicodeScalars.endIndex, summer)!) } tests.test("index-mapping/utf8-to-character/\(id)") { // Define expectation separately to help the type-checker, which // otherwise runs out of time solving. let winterUtf8Characters: [Character?] = [ "🏂", err("🏂"), err("🏂"), err("🏂"), "☃", err("☃"), err("☃"), "❅", err("❅"), err("❅"), "❆", err("❆"), err("❆"), "❄︎", err("❄︎"), err("❄︎"), err("\u{fe0e}"), err("\u{fe0e}"), err("\u{fe0e}"), "⛄️", err("⛄️"), err("⛄️"), err("\u{fe0f}"), err("\u{fe0f}"), err("\u{fe0f}"), "❄️", err("❄️"), err("❄️"), err("\u{fe0f}"), err("\u{fe0f}"), err("\u{fe0f}"), replacementCharacter, err(replacementCharacter), err(replacementCharacter), "\u{20}", replacementCharacter, err(replacementCharacter), err(replacementCharacter), replacementCharacter, err(replacementCharacter), err(replacementCharacter), ] expectEqualSequence( winterUtf8Characters, winter.utf8.indices.map { (i:String.Index) -> Character? in mapIndex(i, winter).map { winter[$0] } }, sameValue: ==) expectNotNil(mapIndex(winter.utf8.endIndex, winter)) expectEqual( winter.endIndex, mapIndex(winter.utf8.endIndex, winter)!) expectEqualSequence( summerBytes.map { Character(UnicodeScalar($0)) }, summer.utf8.indices.map { summer[mapIndex($0, summer)!] } ) expectNotNil(mapIndex(summer.utf8.endIndex, summer)) expectEqual( summer.endIndex, mapIndex(summer.utf8.endIndex, summer)!) } tests.test("index-mapping/utf16-to-character/\(id)") { let winterUtf16Characters: [Character?] = [ "🏂", // Prior to UTF-8 String, this tested for empty array in "legacy mode" or // the replacemnet character otherwise. However, SE-0180 (String Index // Overhual) dictates subscript behavior should treat it as emergent // behavior from its encoded offset, hence we should get the same 3 code // units as prior for non-scalar-aligned UTF-16 offsets applied to the // UTF-8 view. Under a mixed-encoding String model, we necessarily have to // clamp all indices to the nearest prior scalar boundary... // // Old code: // err(replacementCharacter), err("🏂"), "☃", "❅", "❆", "❄︎", err("\u{fe0e}"), "⛄️", err("\u{fe0f}"), "❄️", err("\u{fe0f}"), replacementCharacter, "\u{20}", replacementCharacter, replacementCharacter ] expectEqualSequence( winterUtf16Characters, winter.utf16.indices.map { i in mapIndex(i, winter).map { winter[$0] } }, sameValue: ==) expectNotNil(mapIndex(winter.utf16.endIndex, winter)) expectEqual( winter.endIndex, mapIndex(winter.utf16.endIndex, winter)!) expectEqualSequence( summerBytes.map { Character(UnicodeScalar($0)) }, summer.utf16.indices.map { summer[mapIndex($0, summer)!] } ) expectNotNil(mapIndex(summer.utf16.endIndex, summer)) expectEqual( summer.endIndex, mapIndex(summer.utf16.endIndex, summer)!) } } checkToCharacter("legacy") { $0.samePosition(in: $1) } checkToCharacter("interchange") { i, _ in i } //===----------------------------------------------------------------------===// // These are rather complicated due to their internal buffers, so // rigorous tests are required tests.test("UTF8 indexes") { // Make sure that equivalent UTF8 indices computed in different ways // are still equal. // // CHECK-NEXT: true let abc = "abcdefghijklmnop" do { let start = String.Index(abc.startIndex, within: abc.utf8) expectEqual( abc.utf8.index(after: start!), String.Index(abc.index(after: abc.startIndex), within: abc.utf8)) } let diverseCharacters = summer + winter + winter + summer let s = diverseCharacters.unicodeScalars let u8 = diverseCharacters.utf8 let u16 = diverseCharacters.utf16 //===--- nested for...in loops ------------------------------------------===// // Test all valid subranges si0..<si1 of positions in s. ds is // always si0.distance(to: si1) for si0 in s.indices { for (ds, si1) in s.indices[si0..<s.endIndex].enumerated() { // Map those unicode scalar indices into utf8 indices let u8i1 = si1.samePosition(in: u8) let u8i0 = si0.samePosition(in: u8) //===--- while loop -------------------------------------------------===// // Advance an index from u8i0 over ds Unicode scalars (thus // reaching u8i1) by counting leading bytes traversed var u8i0a = u8i0! // <========== NOTE SOURCE COMPATIBILITY BREAKAGE var dsa = 0 // number of Unicode scalars it has advanced over while true { //===--- loop condition -------------------------------------------===// let b = u8[u8i0a] let isLeadingByte = !UTF8.isContinuation(b) if dsa == ds && isLeadingByte { break } // //===--------------------------------------------------------------===// expectNotEqual(u8i0a, u8i1) // We're not there yet if isLeadingByte { // On a unicode scalar boundary? let u16i0a = u8i0a.samePosition(in: u16)! // we should be able to round-trip through UTF16 expectEqual(u8i0a, u16i0a.samePosition(in: u8)!) if UTF16.isLeadSurrogate(u16[u16i0a]) { // We only have well-formed UTF16 in this string, so the // successor points to a trailing surrogate of a pair and // thus shouldn't convert to a UTF8 position expectNil(u16.index(after: u16i0a).samePosition(in: u8)) } dsa = dsa.advanced(by: 1) // we're moving off the beginning of a new Unicode scalar } else { expectNil(u8i0a.samePosition(in: u16)) } u8i0a = u8.index(u8i0a, offsetBy: 1) } expectEqual(u8i0a, u8i1) // We should be there now // Also check some UTF8 positions between unicode scalars for equality var u8i0b = u8i0a for n0 in 0..<8 { var u8i1b = u8i1 for n1 in 0..<8 { expectEqualTest(u8i0b, u8i1b, sameValue: n0 == n1 ? (==) : (!=)) if u8i1b == u8.endIndex { break } u8i1b = u8.index(u8i1b!, offsetBy: 1) } if u8i0b == u8.endIndex { break } u8i0b = u8.index(u8i0b, offsetBy: 1) } } } } tests.test("index/Comparable") .forEach(in: [summer, winter]) { str in checkComparable(str.indices, oracle: <=>) checkComparable(str.unicodeScalars.indices, oracle: <=>) checkComparable(str.utf16.indices, oracle: <=>) checkComparable(str.utf8.indices, oracle: <=>) } tests.test("UTF16->String") { let s = summer + winter + winter + summer let v = s.utf16 for i in v.indices { for j in v.indices[i..<v.endIndex] { if let si = i.samePosition(in: s) { if let sj = j.samePosition(in: s) { expectEqual(s[si..<sj], String(v[i..<j])!) continue } } } } } tests.test("UTF8->String") { let s = summer + winter + winter + summer let v = s.utf8 for i in v.indices { for j in v.indices[i..<v.endIndex] { if let si = i.samePosition(in: s) { if let sj = j.samePosition(in: s) { expectEqual( s[si..<sj], String(v[i..<j])!, "\(String(reflecting: s))[\n \(si..<sj)\n] != String(\n \(String(reflecting: v))[\n \(i..<j)\n ])!" ) continue } } } } } tests.test("UnicodeScalars->String") { let s = summer + winter + winter + summer let v = s.unicodeScalars for i in s.indices { for j in s.indices[i..<s.endIndex] { expectEqual( s[i..<j], String(v[i.samePosition(in: v)!..<j.samePosition(in: v)!]) ) } } } // Note: Strideable conformance for UTF16View.Index when Foundation is imported // has been dropped for Swift 4. tests.test("String.UTF8View/Collection") .forEach(in: utfTests) { test in checkBidirectionalCollection(test.utf8, test.string.utf8) { $0 == $1 } } tests.test("String.UTF16View/BidirectionalCollection") .forEach(in: utfTests) { test in checkBidirectionalCollection(test.utf16, test.string.utf16) { $0 == $1 } } tests.test("String.UTF32View/BidirectionalCollection") .forEach(in: utfTests) { test in checkBidirectionalCollection( test.unicodeScalars, test.string.unicodeScalars) { $0 == $1 } } tests.test("String View Setters") { var string = "abcd🤠👨‍👨‍👦‍👦efg" string.utf8 = winter.utf8 expectEqual(winter, string) string.utf8 = summer.utf8 expectEqual(summer, string) string.utf16 = winter.utf16 expectEqual(winter, string) string.utf16 = summer.utf16 expectEqual(summer, string) string.unicodeScalars = winter.unicodeScalars expectEqual(winter, string) string.unicodeScalars = summer.unicodeScalars expectEqual(summer, string) string = winter expectEqual(winter, string) string = summer expectEqual(summer, string) } runAllTests()
apache-2.0
e02c72e51a3085e43172116ba8779f02
29.636695
122
0.636155
3.49031
false
true
false
false
FromF/OlympusCameraKit
BluetoothSmartTestSwift/BluetoothSmartTestSwift/AppDelegate.swift
1
3124
// // AppDelegate.swift // BluetoothSmartTestSwift // // Created by haruhito on 2015/04/03. // Copyright (c) 2015年 FromF. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var BluetoothSmartName = NSString() var BluetoothSmartPasscode = NSString() var BluetoothSmartNotification : NSString = "BluetoothSmartNotification" class var sharedCamera : OLYCamera { struct Static { static let instance : OLYCamera = OLYCamera() } return Static.instance } 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:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { var oacentralconf = OACentralConfiguration(configurationURL: url) self.BluetoothSmartName = oacentralconf.bleName self.BluetoothSmartPasscode = oacentralconf.bleCode //Notification NSNotificationCenter.defaultCenter().postNotificationName(self.BluetoothSmartNotification as String, object: nil) println("BletoothSmart Name[\(self.BluetoothSmartName)] Passcode[\(self.BluetoothSmartPasscode)]") return true } }
mit
9c71d495a4150dfc80886e5812f56ae7
44.246377
285
0.735106
5.448517
false
false
false
false
thefuntasty/FuntastyKit
Sources/FuntastyKit/Errors/AlertCoordinator.swift
1
4349
import UIKit public class AlertCoordinator: DefaultCoordinator { public typealias ViewController = UIAlertController public enum Source { case button(UIBarButtonItem) case view(UIView) } public enum Style { case alert case actionSheet(source: Source?) var controllerStyle: UIAlertController.Style { switch self { case .alert: return .alert case .actionSheet: return .actionSheet } } } enum InputType { case error(Error) case custom(title: String?, message: String?, actions: [ErrorAction]?) func alertController(preferredStyle: Style = .alert) -> UIAlertController { switch self { case .error(let error): return UIAlertController(error: error, preferredStyle: preferredStyle.controllerStyle) case .custom(let title, let message, let actions): let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle.controllerStyle) (actions ?? [ErrorAction(title: NSLocalizedString("OK", comment: "OK"))]) .forEach { action in let alertAction = action.alertAction() alert.addAction(alertAction) if action.style == .preferred { alert.preferredAction = alertAction } } return alert } } } let parentViewController: UIViewController public weak var viewController: UIAlertController? public weak var delegate: CoordinatorDelegate? private var type: InputType private var preferredStyle: Style // MARK: - Inits public init(parent: UIViewController, error: Error, preferredStyle: Style = .alert) { self.parentViewController = parent self.type = .error(error) self.preferredStyle = preferredStyle } public init(parent: UIViewController, title: String?, message: String?, actions: [ErrorAction]? = nil, preferredStyle: Style = .alert) { self.parentViewController = parent self.type = .custom(title: title, message: message, actions: actions) self.preferredStyle = preferredStyle } public func start() { let alert = type.alertController(preferredStyle: preferredStyle) if case .actionSheet(let source) = preferredStyle, let sourceView = source { switch sourceView { case .button(let button): alert.popoverPresentationController?.barButtonItem = button case .view(let view): alert.popoverPresentationController?.sourceView = view } } parentViewController.present(alert, animated: animated, completion: nil) viewController = alert } public func stop() { delegate?.willStop(in: self) viewController?.dismiss(animated: animated) { self.delegate?.didStop(in: self) } } } public extension ErrorAction { func alertStyle() -> UIAlertAction.Style { switch self.style { case .cancel: return .cancel case .destructive: return .destructive default: return .default } } func alertAction() -> UIAlertAction { return UIAlertAction(title: self.title, style: self.alertStyle(), handler: { _ in self.action?() }) } } public extension DefaultCoordinator { func showAlert(for error: Error, preferredStyle: AlertCoordinator.Style = .alert) { guard let viewController = self.viewController else { return } let alertCoordinator = AlertCoordinator(parent: viewController, error: error, preferredStyle: preferredStyle) alertCoordinator.start() } func showAlert(title: String?, message: String?, actions: [ErrorAction]? = nil, preferredStyle: AlertCoordinator.Style = .alert) { guard let viewController = self.viewController else { return } let alertCoordinator = AlertCoordinator(parent: viewController, title: title, message: message, actions: actions, preferredStyle: preferredStyle) alertCoordinator.start() } }
mit
1737fdb4ca3a2d6ee36a63523a9eec9b
33.515873
153
0.613934
5.533079
false
false
false
false
russbishop/swift
stdlib/public/SDK/Foundation/Decimal.swift
1
15524
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension Decimal { public typealias RoundingMode = NSDecimalNumber.RoundingMode public typealias CalculationError = NSDecimalNumber.CalculationError public static let leastFiniteMagnitude = Decimal(_exponent: 127, _length: 8, _isNegative: 1, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) public static let greatestFiniteMagnitude = Decimal(_exponent: 127, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) public static let leastNormalMagnitude = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) public static let leastNonzeroMagnitude = Decimal(_exponent: -127, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) public static let pi = Decimal(_exponent: -38, _length: 8, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x6623, 0x7d57, 0x16e7, 0xad0d, 0xaf52, 0x4641, 0xdfa7, 0xec58)) public var exponent: Int { get { return Int(_exponent) } } public var significand: Decimal { get { return Decimal(_exponent: 1, _length: _length, _isNegative: _isNegative, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa) } } public init(sign: FloatingPointSign, exponent: Int, significand: Decimal) { self.init(_exponent: Int32(exponent), _length: significand._length, _isNegative: sign == .plus ? 1 : 0, _isCompact: significand._isCompact, _reserved: 0, _mantissa: significand._mantissa) } public init(signOf: Decimal, magnitudeOf magnitude: Decimal) { self.init(_exponent: magnitude._exponent, _length: magnitude._length, _isNegative: signOf._isNegative, _isCompact: magnitude._isCompact, _reserved: 0, _mantissa: magnitude._mantissa) } public var sign: FloatingPointSign { return _isNegative == 0 ? FloatingPointSign.plus : FloatingPointSign.minus } public static var radix: Int { return 10 } public var ulp: Decimal { return Decimal(_exponent: 1, _length: _length, _isNegative: _isNegative, _isCompact: _isCompact, _reserved: 0, _mantissa: _mantissa) } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public mutating func formTruncatingRemainder(dividingBy other: Decimal) { fatalError("Decimal does not yet fully adopt FloatingPoint") } public mutating func add(_ other: Decimal) { var rhs = other NSDecimalAdd(&self, &self, &rhs, .plain) } public mutating func subtract(_ other: Decimal) { var rhs = other NSDecimalSubtract(&self, &self, &rhs, .plain) } public mutating func multiply(by other: Decimal) { var rhs = other NSDecimalMultiply(&self, &self, &rhs, .plain) } public mutating func divide(by other: Decimal) { var rhs = other NSDecimalMultiply(&self, &self, &rhs, .plain) } public mutating func negate() { _isNegative = _isNegative == 0 ? 1 : 0 } public func isEqual(to other: Decimal) -> Bool { var lhs = self var rhs = other return NSDecimalCompare(&lhs, &rhs) == .orderedSame } public func isLess(than other: Decimal) -> Bool { var lhs = self var rhs = other return NSDecimalCompare(&lhs, &rhs) == .orderedAscending } public func isLessThanOrEqualTo(_ other: Decimal) -> Bool { var lhs = self var rhs = other let order = NSDecimalCompare(&lhs, &rhs) return order == .orderedAscending || order == .orderedSame } public func isTotallyOrdered(below other: Decimal) -> Bool { // Notes: Decimal does not have -0 or infinities to worry about if self.isNaN { return false } else if self < other { return true } else if other < self { return false } // fall through to == behavior return true } public var isCanonical: Bool { return true } public var nextUp: Decimal { return self + Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } public var nextDown: Decimal { return self - Decimal(_exponent: _exponent, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0, _mantissa: (0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } } public func +(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalAdd(&res, &leftOp, &rightOp, .plain) return res } public func -(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalSubtract(&res, &leftOp, &rightOp, .plain) return res } public func /(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalDivide(&res, &leftOp, &rightOp, .plain) return res } public func *(lhs: Decimal, rhs: Decimal) -> Decimal { var res = Decimal() var leftOp = lhs var rightOp = rhs NSDecimalMultiply(&res, &leftOp, &rightOp, .plain) return res } public func pow(_ x: Decimal, _ y: Int) -> Decimal { var res = Decimal() var num = x NSDecimalPower(&res, &num, y, .plain) return res } extension Decimal : Hashable, Comparable { internal var doubleValue : Double { var d = 0.0 if _length == 0 && _isNegative == 0 { return Double.nan } for i in 0..<8 { let index = 8 - i - 1 switch index { case 0: d = d * 65536 + Double(_mantissa.0) break case 1: d = d * 65536 + Double(_mantissa.1) break case 2: d = d * 65536 + Double(_mantissa.2) break case 3: d = d * 65536 + Double(_mantissa.3) break case 4: d = d * 65536 + Double(_mantissa.4) break case 5: d = d * 65536 + Double(_mantissa.5) break case 6: d = d * 65536 + Double(_mantissa.6) break case 7: d = d * 65536 + Double(_mantissa.7) break default: fatalError("conversion overflow") } } if _exponent < 0 { for _ in _exponent..<0 { d /= 10.0 } } else { for _ in 0..<_exponent { d *= 10.0 } } return _isNegative != 0 ? -d : d } public var hashValue: Int { return Int(bitPattern: __CFHashDouble(doubleValue)) } } public func ==(lhs: Decimal, rhs: Decimal) -> Bool { var lhsVal = lhs var rhsVal = rhs return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedSame } public func <(lhs: Decimal, rhs: Decimal) -> Bool { var lhsVal = lhs var rhsVal = rhs return NSDecimalCompare(&lhsVal, &rhsVal) == .orderedAscending } extension Decimal : FloatLiteralConvertible { public init(floatLiteral value: Double) { self.init(value) } } extension Decimal : IntegerLiteralConvertible { public init(integerLiteral value: Int) { self.init(value) } } extension Decimal : SignedNumber { } extension Decimal : Strideable { public func distance(to other: Decimal) -> Decimal { return self - other } public func advanced(by n: Decimal) -> Decimal { return self + n } } extension Decimal : AbsoluteValuable { public static func abs(_ x: Decimal) -> Decimal { return Decimal(_exponent: x._exponent, _length: x._length, _isNegative: 0, _isCompact: x._isCompact, _reserved: 0, _mantissa: x._mantissa) } } extension Decimal { public init(_ value: UInt8) { self.init(UInt64(value)) } public init(_ value: Int8) { self.init(Int64(value)) } public init(_ value: UInt16) { self.init(UInt64(value)) } public init(_ value: Int16) { self.init(Int64(value)) } public init(_ value: UInt32) { self.init(UInt64(value)) } public init(_ value: Int32) { self.init(Int64(value)) } public init(_ value: Double) { if value.isNaN { self = Decimal.nan } else if value == 0.0 { self = Decimal(_exponent: 0, _length: 0, _isNegative: 0, _isCompact: 0, _reserved: 0, _mantissa: (0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000)) } else { let negative = value < 0 var val = negative ? -1 * value : value var exponent = 0 while val < Double(UInt64.max - 1) { val *= 10.0 exponent -= 1 } while Double(UInt64.max - 1) < val { val /= 10.0 exponent += 1 } var mantissa = UInt64(val) var i = UInt32(0) // this is a bit ugly but it is the closest approximation of the C initializer that can be expressed here. _mantissa = (0, 0, 0, 0, 0, 0, 0, 0) while mantissa != 0 && i < 8 /* NSDecimalMaxSize */ { switch i { case 0: _mantissa.0 = UInt16(mantissa & 0xffff) break case 1: _mantissa.1 = UInt16(mantissa & 0xffff) break case 2: _mantissa.2 = UInt16(mantissa & 0xffff) break case 3: _mantissa.3 = UInt16(mantissa & 0xffff) break case 4: _mantissa.4 = UInt16(mantissa & 0xffff) break case 5: _mantissa.5 = UInt16(mantissa & 0xffff) break case 6: _mantissa.6 = UInt16(mantissa & 0xffff) break case 7: _mantissa.7 = UInt16(mantissa & 0xffff) break default: fatalError("initialization overflow") } mantissa = mantissa >> 16 i += 1 } _length = i _isNegative = negative ? 1 : 0 _isCompact = 0 _exponent = Int32(exponent) NSDecimalCompact(&self) } } public init(_ value: UInt64) { self.init(Double(value)) } public init(_ value: Int64) { self.init(Double(value)) } public init(_ value: UInt) { self.init(UInt64(value)) } public init(_ value: Int) { self.init(Int64(value)) } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public static var infinity: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") } @available(*, unavailable, message: "Decimal does not yet fully adopt FloatingPoint.") public static var signalingNaN: Decimal { fatalError("Decimal does not yet fully adopt FloatingPoint") } public var isSignalingNaN: Bool { return false } public static var nan: Decimal { return quietNaN } public static var quietNaN: Decimal { return Decimal(_exponent: 0, _length: 0, _isNegative: 1, _isCompact: 0, _reserved: 0, _mantissa: (0, 0, 0, 0, 0, 0, 0, 0)) } /// The IEEE 754 "class" of this type. public var floatingPointClass: FloatingPointClassification { if _length == 0 && _isNegative == 1 { return .quietNaN } else if _length == 0 { return .positiveZero } // NSDecimal does not really represent normal and subnormal in the same manner as the IEEE standard, for now we can probably claim normal for any nonzero, nonnan values if _isNegative == 1 { return .negativeNormal } else { return .positiveNormal } } /// `true` iff `self` is negative. public var isSignMinus: Bool { return _isNegative != 0 } /// `true` iff `self` is normal (not zero, subnormal, infinity, or /// NaN). public var isNormal: Bool { return !isZero && !isInfinite && !isNaN } /// `true` iff `self` is zero, subnormal, or normal (not infinity /// or NaN). public var isFinite: Bool { return !isNaN } /// `true` iff `self` is +0.0 or -0.0. public var isZero: Bool { return _length == 0 && _isNegative == 0 } /// `true` iff `self` is subnormal. public var isSubnormal: Bool { return false } /// `true` iff `self` is infinity. public var isInfinite: Bool { return false } /// `true` iff `self` is NaN. public var isNaN: Bool { return _length == 0 && _isNegative == 1 } /// `true` iff `self` is a signaling NaN. public var isSignaling: Bool { return false } } extension Decimal : CustomStringConvertible { public init?(string: String, locale: Locale? = nil) { let scan = Scanner(string: string) var theDecimal = Decimal() scan.locale = locale if !scan.scanDecimal(&theDecimal) { return nil } self = theDecimal } public var description: String { var val = self return NSDecimalString(&val, nil) } } extension Decimal : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDecimalNumber { return NSDecimalNumber(decimal: self) } public static func _forceBridgeFromObjectiveC(_ x: NSDecimalNumber, result: inout Decimal?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSDecimalNumber, result: inout Decimal?) -> Bool { result = input.decimalValue return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDecimalNumber?) -> Decimal { var result: Decimal? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } }
apache-2.0
ca58ed1f044fbd2410bd5f5d6ebdbbbe
32.529158
205
0.563257
4.325439
false
false
false
false
xiaoxinghu/swift-org
Sources/List.swift
1
2136
// // List.swift // SwiftOrg // // Created by Xiaoxing Hu on 21/09/16. // Copyright © 2016 Xiaoxing Hu. All rights reserved. // import Foundation public struct ListItem: Node { public let text: String? public var checked: Bool? public var subList: List? public init(text t: String? = nil, checked c: Bool? = nil, list l: List? = nil) { text = t subList = l checked = c } public var description: String { return "ListItem(text: \(text), checked: \(checked), subList: \(subList))" } } public struct List: Node { public var items: [ListItem] public var ordered: Bool public var progress: Progress { var progress = Progress() for item in items { if let checked = item.checked { progress.total += 1 if checked { progress.done += 1 } } } return progress } public init(ordered o: Bool, items i: [ListItem] = []) { ordered = o items = i } public var description: String { return "List(ordered: \(ordered), items: \(items))" } } extension OrgParser { func parseList() throws -> List { guard case let (_, Token.listItem(indent, text, ordered, checked)) = tokens.dequeue()! else { throw Errors.unexpectedToken("ListItem expected") } var list = List(ordered: ordered) list.items = [ListItem(text: text, checked: checked)] while let (_, token) = tokens.peek() { if case let .listItem(i, t, _, c) = token { if i > indent { var lastItem = list.items.removeLast() lastItem.subList = try parseList() list.items += [lastItem] } else if i == indent { _ = tokens.dequeue() list.items += [ListItem(text: t, checked: c)] } else { break } } else { break } } return list } }
mit
2a95b39b1f13fef2d59ccb019079531e
26.371795
101
0.497424
4.475891
false
false
false
false
volodg/iAsync.reactiveKit
Sources/QueueStrategies/QueueStrategy.swift
1
1046
// // QueueStrategy.swift // iAsync_reactiveKit // // Created by Vladimir Gorbenko on 09.07.14. // Copyright © 2014 EmbeddedSources. All rights reserved. // import Foundation public protocol QueueStrategy { associatedtype ValueT associatedtype NextT associatedtype ErrorT: Error static func nextPendingStream(queueState: QueueState<ValueT, NextT, ErrorT>) -> StreamOwner<ValueT, NextT, ErrorT>? } extension QueueStrategy { internal static func executePendingStreamFor(queueState: QueueState<ValueT, NextT, ErrorT>, pendingStream: StreamOwner<ValueT, NextT, ErrorT>) { var objectIndex: Int? for (index, stream) in queueState.pendingStreams.enumerated() { if stream === pendingStream { objectIndex = index break } } if let objectIndex = objectIndex { queueState.pendingStreams.remove(at: objectIndex) } queueState.activeStreams.append(pendingStream) pendingStream.performStream() } }
gpl-3.0
05322554a5b7935c1eb092a7da9c08d1
24.487805
148
0.669856
4.644444
false
false
false
false
tsolomko/SWCompression
Sources/LZMA/LZMABitTreeDecoder.swift
1
1464
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation /// Used to decode symbols that need several bits for storing. struct LZMABitTreeDecoder { var probs: [Int] let numBits: Int init(numBits: Int) { self.probs = Array(repeating: LZMAConstants.probInitValue, count: 1 << numBits) self.numBits = numBits } mutating func decode(with rangeDecoder: inout LZMARangeDecoder) -> Int { var m = 1 for _ in 0..<self.numBits { m = (m << 1) + rangeDecoder.decode(bitWithProb: &self.probs[m]) } return m - (1 << self.numBits) } mutating func reverseDecode(with rangeDecoder: inout LZMARangeDecoder) -> Int { return LZMABitTreeDecoder.bitTreeReverseDecode(probs: &self.probs, startIndex: 0, bits: self.numBits, &rangeDecoder) } static func bitTreeReverseDecode(probs: inout [Int], startIndex: Int, bits: Int, _ rangeDecoder: inout LZMARangeDecoder) -> Int { var m = 1 var symbol = 0 for i in 0..<bits { let bit = rangeDecoder.decode(bitWithProb: &probs[startIndex + m]) m <<= 1 m += bit symbol |= bit << i } return symbol } }
mit
2132c8bdaba1c743858783ae3e1dcee2
30.148936
89
0.54235
4.692308
false
false
false
false
LoopKit/LoopKit
LoopKitUI/Charts/GlucoseChart.swift
1
1881
// // GlucoseChart.swift // LoopUI // // Copyright © 2019 LoopKit Authors. All rights reserved. // import Foundation import HealthKit import LoopKit import SwiftCharts open class GlucoseChart { public init() { } public var glucoseUnit: HKUnit = .milligramsPerDeciliter { didSet { if glucoseUnit != oldValue { // Regenerate the glucose display points let oldRange = glucoseDisplayRange glucoseDisplayRange = oldRange } } } public var glucoseDisplayRange: ClosedRange<HKQuantity>? { didSet { if let range = glucoseDisplayRange { glucoseDisplayRangePoints = [ ChartPoint(x: ChartAxisValue(scalar: 0), y: ChartAxisValueDouble(range.lowerBound.doubleValue(for: glucoseUnit))), ChartPoint(x: ChartAxisValue(scalar: 0), y: ChartAxisValueDouble(range.upperBound.doubleValue(for: glucoseUnit))) ] } else { glucoseDisplayRangePoints = [] } } } public private(set) var glucoseDisplayRangePoints: [ChartPoint] = [] public func glucosePointsFromValues(_ glucoseValues: [GlucoseValue]) -> [ChartPoint] { let unitFormatter = QuantityFormatter() unitFormatter.unitStyle = .short unitFormatter.setPreferredNumberFormatter(for: glucoseUnit) let unitString = unitFormatter.string(from: glucoseUnit) let dateFormatter = DateFormatter(timeStyle: .short) return glucoseValues.map { return ChartPoint( x: ChartAxisValueDate(date: $0.startDate, formatter: dateFormatter), y: ChartAxisValueDoubleUnit($0.quantity.doubleValue(for: glucoseUnit), unitString: unitString, formatter: unitFormatter.numberFormatter) ) } } }
mit
bcf51ec88a7daceb6c3b8c3b8f9659b4
31.982456
152
0.629255
5.61194
false
false
false
false
gringoireDM/LNZCollectionLayouts
LNZCollectionLayouts/CollectionViewController.swift
1
3990
// // InfiniteViewController.swift // LNZCollectionLayouts // // Created by Giuseppe Lanza on 18/07/17. // Copyright © 2017 Gilt. All rights reserved. // import UIKit class CollectionViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() collectionView?.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header") collectionView?.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "ReloadData", style: .plain, target: collectionView, action: #selector(UICollectionView.reloadData)) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 15 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) let label = cell.contentView.viewWithTag(10)! as! UILabel cell.layer.borderColor = UIColor.darkGray.cgColor cell.layer.borderWidth = 1 label.text = "\(indexPath.item)" return cell } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: nil, completion: { _ in if let currentFocused = (self.collectionView?.collectionViewLayout as? FocusedContaining)?.currentInFocus { let indexPath = IndexPath(item: currentFocused, section: 0) self.collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: false) } self.collectionView?.collectionViewLayout.invalidateLayout() }) } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true) } } extension CollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSize(width: collectionView.bounds.width, height: 40) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: collectionView.bounds.width, height: 40) } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { var identifier = "header" if kind == UICollectionView.elementKindSectionFooter { identifier = "footer" } let supplementaryView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath) supplementaryView.backgroundColor = UIColor.lightGray let label = supplementaryView.viewWithTag(99) as? UILabel ?? UILabel(frame: supplementaryView.bounds) label.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] label.textAlignment = .center label.text = identifier if label.superview == nil { supplementaryView.addSubview(label) } return supplementaryView } }
mit
ae4841def0268729916b4846df3fac89
46.488095
171
0.72374
6.174923
false
false
false
false
rudkx/swift
test/Generics/concrete_conformances_in_protocol.swift
1
1986
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=verify 2>&1 | %FileCheck %s // rdar://problem/88135912 // XFAIL: * protocol P { associatedtype T } struct S : P { typealias T = S } // CHECK-LABEL: concrete_conformances_in_protocol.(file).R0@ // CHECK-LABEL: Requirement signature: <Self where Self.[R0]A == S> protocol R0 { associatedtype A where A : P, A == S } //// struct G<T> : P {} // CHECK-LABEL: concrete_conformances_in_protocol.(file).R1@ // CHECK-LABEL: Requirement signature: <Self where Self.[R1]B == G<Self.[R1]A>> protocol R1 { associatedtype A associatedtype B where B : P, B == G<A> } // CHECK-LABEL: concrete_conformances_in_protocol.(file).R2@ // CHECK-LABEL: Requirement signature: <Self where Self.[R2]A == G<Self.[R2]B>> protocol R2 { associatedtype A where A : P, A == G<B> associatedtype B } //// protocol PP { associatedtype T : P } struct GG<T : P> : PP {} // CHECK-LABEL: concrete_conformances_in_protocol.(file).RR3@ // CHECK-LABEL: Requirement signature: <Self where Self.[RR3]A : P, Self.[RR3]B == GG<Self.[RR3]A>> protocol RR3 { associatedtype A : P associatedtype B where B : PP, B == GG<A> } // CHECK-LABEL: concrete_conformances_in_protocol.(file).RR4@ // CHECK-LABEL: Requirement signature: <Self where Self.[RR4]A == GG<Self.[RR4]B>, Self.[RR4]B : P> protocol RR4 { associatedtype A where A : PP, A == GG<B> associatedtype B : P } // CHECK-LABEL: concrete_conformances_in_protocol.(file).RR5@ // CHECK-LABEL: Requirement signature: <Self where Self.[RR5]A : PP, Self.[RR5]B == GG<Self.[RR5]A.[PP]T>> protocol RR5 { associatedtype A : PP associatedtype B where B : PP, B == GG<A.T> } // CHECK-LABEL: concrete_conformances_in_protocol.(file).RR6@ // CHECK-LABEL: Requirement signature: <Self where Self.[RR6]A == GG<Self.[RR6]B.[PP]T>, Self.[RR6]B : PP> protocol RR6 { associatedtype A where A : PP, A == GG<B.T> associatedtype B : PP }
apache-2.0
733e5054b7709675c69c57cd12f3a00d
24.461538
139
0.669184
2.964179
false
false
false
false
suncry/MLHybrid
Source/Content/View/MLHybridButton.swift
1
3268
// // MLHybridButton.swift // Pods // // Created by yang cai on 2017/8/18. // // import Foundation class MLHybridButton: UIButton { let margin: CGFloat = 0 var model: Hybrid_naviButtonModel = Hybrid_naviButtonModel() var webView: UIWebView = UIWebView() class func setUp(models: [Hybrid_naviButtonModel], webView: UIWebView) -> [UIBarButtonItem] { let models = models.reversed() var items: [UIBarButtonItem] = [] for model in models { let button = MLHybridButton() button.model = model button.webView = webView let titleWidth = model.value.hybridStringWidthWith(15, height: 20) + 2*button.margin let buttonWidth = titleWidth > 42 ? titleWidth : 42 button.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: 44) button.titleLabel?.font = UIFont.systemFont(ofSize: 15) button.setTitleColor(UIColor(red: 0, green: 122/255.0, blue: 255/255.0, alpha: 1), for: .normal) if model.icon.characters.count > 0 { button.kf.setImage(with: URL(string: model.icon), for: .normal) } else if model.tagname.characters.count > 0 { print("加载图片 \(NaviImageHeader + model.tagname)") print(UIImage(named: NaviImageHeader + model.tagname) ?? "未找到对应图片资源") button.setImage(UIImage(named: NaviImageHeader + model.tagname), for: .normal) } if let _ = UIImage(named: NaviImageHeader + model.tagname) { } else { if model.value.characters.count > 0 { button.setTitle(model.value, for: .normal) } } if model.tagname == "back" { let image = UIImage(named: MLHybrid.shared.backIndicator) button.setImage(image, for: .normal) button.contentHorizontalAlignment = .left } else { button.imageView?.contentMode = .scaleAspectFit button.imageEdgeInsets = UIEdgeInsetsMake(0, 13, 0, 13) } if model.value.characters.count > 0 { button.setTitle(model.value, for: .normal) } button.addTarget(button, action: #selector(MLHybridButton.click), for: .touchUpInside) items.append(UIBarButtonItem(customView: button)) } return items } @objc func click(sender: MLHybridButton) { if sender.model.callback.characters.count == 0 { var nextResponder = sender.webView.next while !(nextResponder is MLHybridViewController) { nextResponder = nextResponder?.next ?? MLHybridViewController() } let vc = nextResponder as? MLHybridViewController if let _ = vc?.presentingViewController { vc?.dismiss(animated: true, completion: nil) } else { vc?.navigationController?.popViewController(animated: true) } } let _ = MLHybridTools().callBack(callback: sender.model.callback, webView: sender.webView) { (str) in } } }
mit
8b594eb64154b1e832860e5dfc7bcfd7
38.536585
111
0.568785
4.658046
false
false
false
false
3drobotics/SwiftIO
Sources/sockaddr_storage+Extensions.swift
1
4368
// // sockaddr_storage.swift // SwiftIO // // Created by Jonathan Wight on 5/5/16. // Copyright © 2016 schwa.io. All rights reserved. // import Darwin /** Convenience extension to construct sockaddr_storage from addr + port. */ public extension sockaddr_storage { /** Create a sockaddr_storage from a POSIX IPV4 address and port. - Parameters: - param: addr POSIX IPV4 in_addr structure - param: port A 16-bit port _in native-endianness_ */ init(addr: in_addr, port: UInt16) { var sockaddr = sockaddr_in() sockaddr.sin_len = __uint8_t(sizeof(sockaddr_in)) sockaddr.sin_family = sa_family_t(AF_INET) sockaddr.sin_port = in_port_t(port.networkEndian) sockaddr.sin_addr = addr self = sockaddr_storage(sockaddr: sockaddr) } /** Create a sockaddr_storage from a POSIX IPV6 address and port. - Parameters: - param: addr POSIX IPV6 in6_addr structure - param: port A 16-bit port _in native-endianness_ */ init(addr: in6_addr, port: UInt16) { var sockaddr = sockaddr_in6() sockaddr.sin6_len = __uint8_t(sizeof(sockaddr_in6)) sockaddr.sin6_family = sa_family_t(AF_INET6) sockaddr.sin6_port = in_port_t(port.networkEndian) sockaddr.sin6_addr = addr self = sockaddr_storage(sockaddr: sockaddr) } } /** Convenience extension to make going from sockaddr_storage to/from other sockaddr structures easy */ public extension sockaddr_storage { init(sockaddr: sockaddr_in) { var copy = sockaddr self = sockaddr_storage() unsafeCopy(destination: &self, source: &copy) } init(sockaddr: sockaddr_in6) { var copy = sockaddr self = sockaddr_storage() unsafeCopy(destination: &self, source: &copy) } init(addr: UnsafePointer <sockaddr>, length: Int) { precondition((addr.memory.sa_family == sa_family_t(AF_INET) && length == sizeof(sockaddr_in)) || (addr.memory.sa_family == sa_family_t(AF_INET6) && length == sizeof(sockaddr_in6))) self = sockaddr_storage() unsafeCopy(destination: &self, source: addr, length: length) } } public extension sockaddr_in { /** Create a sockaddr_in from a sockaddr_storage - Precondition: Family of the sock addr _must_ be AF_INET. */ init(_ addr: sockaddr_storage) { precondition(addr.ss_family == sa_family_t(AF_INET) && addr.ss_len >= __uint8_t(sizeof(sockaddr_in))) var copy = addr self = sockaddr_in() unsafeCopy(destination: &self, source: &copy) } } public extension sockaddr_in6 { /** Create a sockaddr_in6 from a sockaddr_storage - Precondition: Family of the sock addr _must_ be AF_INET6. */ init(_ addr: sockaddr_storage) { precondition(addr.ss_family == sa_family_t(AF_INET6) && addr.ss_len >= __uint8_t(sizeof(sockaddr_in6))) var copy = addr self = sockaddr_in6() unsafeCopy(destination: &self, source: &copy) } } extension sockaddr_storage: CustomStringConvertible { /** Create a sockaddr_storage from a POSIX IPV4 address and port. - Precondition: Family of the sock addr _must_ be AF_INET or AF_INET6. - Warning: This code can fatalError if inet_ntop fails. */ public var description: String { var addrStr = Array <CChar> (count: Int(INET6_ADDRSTRLEN), repeatedValue: 0) do { return try addrStr.withUnsafeMutableBufferPointer() { buffer in switch Int32(ss_family) { case AF_INET: var addr = sockaddr_in(self) let addrString = try inet_ntop(addressFamily: Int32(ss_family), address: &addr.sin_addr) return "\(addrString):\(UInt16(networkEndian: addr.sin_port))" case AF_INET6: var addr = sockaddr_in6(self) let addrString = try inet_ntop(addressFamily: Int32(ss_family), address: &addr.sin6_addr) return "\(addrString):\(UInt16(networkEndian: addr.sin6_port))" default: preconditionFailure() } } } catch let error { fatalError("\(error)") } } }
mit
8460484794c94a33640dea059dd6e45a
30.417266
188
0.599267
3.941336
false
false
false
false
naru-jpn/pencil
PencilTests/UIntSpec.swift
1
6143
// // UIntSpec.swift // Pencil // // Created by naru on 2016/10/17. // Copyright © 2016年 naru. All rights reserved. // import Foundation import Quick import Nimble @testable import Pencil class UIntSpec: QuickSpec { override func spec() { describe("UInt") { context("for some value") { it("can be encode/decode") { let num: UInt = 5 let data: Data = num.data expect(UInt.value(from: data)).to(equal(num)) } } context("for zero") { it("can be encode/decode") { let num: UInt = 0 let data: Data = num.data expect(UInt.value(from: data)).to(equal(num)) } } context("for max") { it("can be encode/decode") { let num: UInt = UInt.max let data: Data = num.data expect(UInt.value(from: data)).to(equal(num)) } } context("for min") { it("can be encode/decode") { let num: UInt = UInt.min let data: Data = num.data expect(UInt.value(from: data)).to(equal(num)) } } } describe("UInt8") { context("for some value") { it("can be encode/decode") { let num: UInt8 = 5 let data: Data = num.data expect(UInt8.value(from: data)).to(equal(num)) } } context("for zero") { it("can be encode/decode") { let num: UInt8 = 0 let data: Data = num.data expect(UInt8.value(from: data)).to(equal(num)) } } context("for max") { it("can be encode/decode") { let num: UInt8 = UInt8.max let data: Data = num.data expect(UInt8.value(from: data)).to(equal(num)) } } context("for min") { it("can be encode/decode") { let num: UInt8 = UInt8.min let data: Data = num.data expect(UInt8.value(from: data)).to(equal(num)) } } } describe("UInt16") { context("for some value") { it("can be encode/decode") { let num: UInt16 = 5 let data: Data = num.data expect(UInt16.value(from: data)).to(equal(num)) } } context("for zero") { it("can be encode/decode") { let num: UInt16 = 0 let data: Data = num.data expect(UInt16.value(from: data)).to(equal(num)) } } context("for max") { it("can be encode/decode") { let num: UInt16 = UInt16.max let data: Data = num.data expect(UInt16.value(from: data)).to(equal(num)) } } context("for min") { it("can be encode/decode") { let num: UInt16 = UInt16.min let data: Data = num.data expect(UInt16.value(from: data)).to(equal(num)) } } } describe("UInt32") { context("for some value") { it("can be encode/decode") { let num: UInt32 = 5 let data: Data = num.data expect(UInt32.value(from: data)).to(equal(num)) } } context("for zero") { it("can be encode/decode") { let num: UInt32 = 0 let data: Data = num.data expect(UInt32.value(from: data)).to(equal(num)) } } context("for max") { it("can be encode/decode") { let num: UInt32 = UInt32.max let data: Data = num.data expect(UInt32.value(from: data)).to(equal(num)) } } context("for min") { it("can be encode/decode") { let num: UInt32 = UInt32.min let data: Data = num.data expect(UInt32.value(from: data)).to(equal(num)) } } } describe("UInt64") { context("for some value") { it("can be encode/decode") { let num: UInt64 = 5 let data: Data = num.data expect(UInt64.value(from: data)).to(equal(num)) } } context("for zero") { it("can be encode/decode") { let num: UInt64 = 0 let data: Data = num.data expect(UInt64.value(from: data)).to(equal(num)) } } context("for max") { it("can be encode/decode") { let num: UInt64 = UInt64.max let data: Data = num.data expect(UInt64.value(from: data)).to(equal(num)) } } context("for min") { it("can be encode/decode") { let num: UInt64 = UInt64.min let data: Data = num.data expect(UInt64.value(from: data)).to(equal(num)) } } } } }
mit
a4da700e947a7b667489de8306350dda
30.649485
67
0.372313
4.853755
false
false
false
false
mrap/SwiftJSONParser
SwiftJSON/SwiftJSONParser.swift
2
2532
// // SwiftJSONParser.swift // SwiftJSONParser // // Created by mrap on 8/27/14. // Copyright (c) 2014 Mike Rapadas. All rights reserved. // import Foundation private typealias _JSON = AnyObject private typealias _JSONDictionary = Dictionary<String, _JSON> private typealias _JSONArray = Array<_JSON> private func jsonDictionary(fromData: NSData?, error: NSErrorPointer) -> _JSONDictionary? { if let data = fromData { var jsonErrorOptional: NSError? if let dict: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &jsonErrorOptional) { return dict as? _JSONDictionary } } return nil } public class JSONParser { private let _json: _JSONDictionary? public let error: NSError? init() { } public init(_ data: NSData?) { if data != nil { self._json = jsonDictionary(data, &self.error) } else { self.error = NSError(domain: "com.mrap.SwiftJSONParser", code: 100, userInfo: [NSLocalizedDescriptionKey: "Parser did not have any data to parse"]) } } public func get(path: String?) -> AnyObject? { return getFinalValue(_json, withPath: JSONPath(path) ) } public func getString(path: String?) -> String? { return self.get(path) as? String } public func getInt(path: String?) -> Int? { return self.get(path) as? Int } public func getDouble(path: String?) -> Double? { return self.get(path) as? Double } public func getArray(path: String?) -> Array<AnyObject>? { return self.get(path) as? Array<AnyObject> } private func getFinalValue(json: _JSON?, withPath path: JSONPath) -> _JSON? { if json == nil { return nil } if let nextKey = path.popNext() { // Handle _JSONArray type here // Get the value from the array and call recursively on the child if let (arrayKey, arrayIndex) = JSONPath.getArrayKeyAndIndex(nextKey) { if arrayKey != nil && arrayIndex != nil { if let array = json![arrayKey!] as? _JSONArray { return getFinalValue(array[arrayIndex!] as _JSON, withPath: path) } } } if let value: AnyObject = json![nextKey] { return getFinalValue(value, withPath: path) } else { return nil } } return json } }
mit
8e693362ecf0efda1f06c65da90d1f50
28.788235
159
0.588863
4.426573
false
false
false
false
XCEssentials/UniFlow
Sources/5_MutationDecriptors/0-AnyUpdateOf.swift
1
1780
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation /// for access to `Date` type //--- public struct AnyUpdateOf<F: SomeFeature>: SomeMutationDecriptor { public let oldState: SomeStateBase public let newState: SomeStateBase public let timestamp: Date public init?( from report: Storage.HistoryElement ) { guard report.feature == F.self, let anyUpdate = AnyUpdate(from: report) else { return nil } //--- self.oldState = anyUpdate.oldState self.newState = anyUpdate.newState self.timestamp = anyUpdate.timestamp } }
mit
d053a28d463c5fb5ddf386fc24b3eee9
28.180328
79
0.703371
4.917127
false
false
false
false
tdquang/CarlWrite
CVCalendar/CVCalendarWeekView.swift
1
7514
// // CVCalendarWeekView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit class CVCalendarWeekView: UIView { // MARK: - Non public properties private var interactiveView: UIView! override var frame: CGRect { didSet { if let calendarView = calendarView { if calendarView.calendarMode == CalendarMode.WeekView { updateInteractiveView() } } } } private var touchController: CVCalendarTouchController { return calendarView.touchController } // MARK: - Public properties weak var monthView: CVCalendarMonthView! var dayViews: [CVCalendarDayView]! var index: Int! var weekdaysIn: [Int : [Int]]? var weekdaysOut: [Int : [Int]]? var utilizable = false /// Recovery service. weak var calendarView: CVCalendarView! { get { var calendarView: CVCalendarView! if let monthView = monthView, let activeCalendarView = monthView.calendarView { calendarView = activeCalendarView } return calendarView } } // MARK: - Initialization init(monthView: CVCalendarMonthView, index: Int) { self.monthView = monthView self.index = index if let size = monthView.calendarView.weekViewSize { super.init(frame: CGRectMake(0, CGFloat(index) * size.height, size.width, size.height)) } else { super.init(frame: CGRectZero) } // Get weekdays in. let weeksIn = self.monthView!.weeksIn! self.weekdaysIn = weeksIn[self.index!] // Get weekdays out. if let weeksOut = self.monthView!.weeksOut { if self.weekdaysIn?.count < 7 { if weeksOut.count > 1 { let daysOut = 7 - self.weekdaysIn!.count var result: [Int : [Int]]? for weekdaysOut in weeksOut { if weekdaysOut.count == daysOut { let manager = calendarView.manager let key = weekdaysOut.keys.first! let value = weekdaysOut[key]![0] if value > 20 { if self.index == 0 { result = weekdaysOut break } } else if value < 10 { if self.index == manager.monthDateRange(self.monthView!.date!).countOfWeeks - 1 { result = weekdaysOut break } } } } self.weekdaysOut = result! } else { self.weekdaysOut = weeksOut[0] } } } self.createDayViews() } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func mapDayViews(body: (DayView) -> ()) { if let dayViews = dayViews { for dayView in dayViews { body(dayView) } } } } // MARK: - Interactive view setup & management extension CVCalendarWeekView { func updateInteractiveView() { safeExecuteBlock({ let mode = self.monthView!.calendarView!.calendarMode! if mode == .WeekView { if let interactiveView = self.interactiveView { interactiveView.frame = self.bounds interactiveView.removeFromSuperview() self.addSubview(interactiveView) } else { self.interactiveView = UIView(frame: self.bounds) self.interactiveView.backgroundColor = .clearColor() let tapRecognizer = UITapGestureRecognizer(target: self, action: "didTouchInteractiveView:") let pressRecognizer = UILongPressGestureRecognizer(target: self, action: "didPressInteractiveView:") pressRecognizer.minimumPressDuration = 0.3 self.interactiveView.addGestureRecognizer(pressRecognizer) self.interactiveView.addGestureRecognizer(tapRecognizer) self.addSubview(self.interactiveView) } } }, collapsingOnNil: false, withObjects: monthView, monthView?.calendarView) } func didPressInteractiveView(recognizer: UILongPressGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) let state: UIGestureRecognizerState = recognizer.state switch state { case .Began: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Started)) case .Changed: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Changed)) case .Ended: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Ended)) default: break } } func didTouchInteractiveView(recognizer: UITapGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Single) } } // MARK: - Content fill & reload extension CVCalendarWeekView { func createDayViews() { dayViews = [CVCalendarDayView]() for i in 1...7 { let dayView = CVCalendarDayView(weekView: self, weekdayIndex: i) safeExecuteBlock({ self.dayViews!.append(dayView) }, collapsingOnNil: true, withObjects: dayViews) addSubview(dayView) } } func reloadDayViews() { if let size = calendarView.dayViewSize, let dayViews = dayViews { let hSpace = calendarView.appearance.spaceBetweenDayViews! for (index, dayView) in dayViews.enumerate() { let hSpace = calendarView.appearance.spaceBetweenDayViews! let x = CGFloat(index) * CGFloat(size.width + hSpace) + hSpace/2 dayView.frame = CGRectMake(x, 0, size.width, size.height) dayView.reloadContent() } } } } // MARK: - Safe execution extension CVCalendarWeekView { func safeExecuteBlock(block: Void -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(object) } must not be nil!") } else { return } } } block() } }
mit
fde3eb57255b5dbb58ae4508baa27293
32.699552
120
0.523556
6.0112
false
false
false
false
TheDarkCode/Example-Swift-Apps
Exercises and Basic Principles/pokedex-exercise/pokedex-exercise/ViewController.swift
1
8186
// // ViewController.swift // pokedex-exercise // // Created by Mark Hamilton on 3/12/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var toggleSoundButton: UIButton! @IBOutlet weak var searchBar: UISearchBar! var pokemon = [Pokemon]() var filteredPokemon = [Pokemon]() var alertController: UIAlertController? var searchActive: Bool = false var bgSound = SoundEffect(fileName: "music", fileType: "mp3", enableSound: true, enableLooping: true, loopTotal: 15, defaultVolume: 1.0) var soundOn: UIImage = UIImage(named: "sound-on")! var soundOff: UIImage = UIImage(named: "sound-off")! override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self searchBar.delegate = self searchBar.returnKeyType = UIReturnKeyType.Done parseCSVResource() setupSoundAndButton() // Check for force touch feature, and add force touch/previewing capability. if traitCollection.forceTouchCapability == .Available { /* Register for `UIViewControllerPreviewingDelegate` to enable "Peek" and "Pop". (see: ViewControllerPreviewing.swift) The view controller will be automatically unregistered when it is deallocated. */ registerForPreviewingWithDelegate(self, sourceView: view) } else { // Create an alert to display to the user. alertController = UIAlertController(title: "3D Touch Not Available", message: "Unsupported device.", preferredStyle: .Alert) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Present the alert if necessary. if let alertController = alertController { alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alertController, animated: true, completion: nil) // Clear the `alertController` to ensure it's not presented multiple times. self.alertController = nil } } // MARK: - Background Music and Toggle func setupSoundAndButton() { bgSound.prepareToPlay() bgSound.play() toggleSoundButton.setImage(soundOn, forState: .Normal) } @IBAction func toggleSound(sender: UIButton!) { if bgSound.playing { bgSound.stop() sender.setImage(soundOff, forState: .Normal) sender.alpha = 0.5 } else { bgSound.play() sender.setImage(soundOn, forState: .Normal) sender.alpha = 1.0 } } // MARK: - CSV Parsing func parseCSVResource() { let csvPath = NSBundle.mainBundle().pathForResource("pokemon", ofType: "csv")! do { let csv = try CSV(contentsOfURL: csvPath) let csvRows = csv.rows for row in csvRows { let id = Int(row["id"]!)! let name: String = row["identifier"]! let pmon = Pokemon(id: id, name: name) pokemon.append(pmon) } } catch let err as NSError { print(err.debugDescription) } } // MARK: - Search Bar func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == nil || searchBar.text == "" { searchActive = false view.endEditing(true) collectionView.reloadData() } else { searchActive = true let lowercase = searchBar.text!.lowercaseString filteredPokemon = pokemon.filter({ // Grab element out of array (of type Pokemon) $0.name.rangeOfString(lowercase) != nil }) collectionView.reloadData() } } func searchBarSearchButtonClicked(searchBar: UISearchBar) { view.endEditing(true) } // MARK: - Collection View Configuration func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(105, 105) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if self.searchActive { return filteredPokemon.count } else { return pokemon.count } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PokemonCell", forIndexPath: indexPath) as? PokemonCell { var cellPokemon = Pokemon(id: 1, name: "") if searchActive == false { if let pokemon: Pokemon = self.pokemon[indexPath.row] { cellPokemon = pokemon } } else { if let pokemon: Pokemon = self.filteredPokemon[indexPath.row] { cellPokemon = pokemon } } cell.configureCell(cellPokemon) return cell } else { return UICollectionViewCell() } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { var cellPokemon = Pokemon(id: 1, name: "") if self.searchActive { if let pokemon: Pokemon = self.filteredPokemon[indexPath.row] { cellPokemon = pokemon } } else { if let pokemon: Pokemon = self.pokemon[indexPath.row] { cellPokemon = pokemon } } self.performSegueWithIdentifier("PokemonDetailVC", sender: cellPokemon) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PokemonDetailVC" { if let detailVC = segue.destinationViewController as? PokemonDetailVC { if let pokemon = sender as? Pokemon { detailVC.pokemon = pokemon } } } } }
mit
6f273666dfa0ef6509da6487b393e15b
25.574675
169
0.502138
6.600806
false
false
false
false
wesj/firefox-ios-1
Client/Application/AppDelegate.swift
1
6590
/* 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 Alamofire import MessageUI import Shared @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow! var profile: Profile! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Setup a web server that serves us static content. Do this early so that it is ready when the UI is presented. setupWebServer() // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() profile = BrowserProfile(localName: "profile") self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window.backgroundColor = UIColor.whiteColor() let controller = BrowserViewController() controller.profile = profile self.window.rootViewController = controller self.window.makeKeyAndVisible() #if MOZ_CHANNEL_AURORA checkForAuroraUpdate() registerFeedbackNotification() #endif return true } #if MOZ_CHANNEL_AURORA var naggedAboutAuroraUpdate = false func applicationDidBecomeActive(application: UIApplication) { if !naggedAboutAuroraUpdate { checkForAuroraUpdate() } } func application(application: UIApplication, applicationWillTerminate app: UIApplication) { unregisterFeedbackNotification() } func applicationWillResignActive(application: UIApplication) { unregisterFeedbackNotification() } private func registerFeedbackNotification() { NSNotificationCenter.defaultCenter().addObserverForName( UIApplicationUserDidTakeScreenshotNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (notification) -> Void in UIGraphicsBeginImageContext(self.window.bounds.size) self.window.drawViewHierarchyInRect(self.window.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.sendFeedbackMailWithImage(image) } } private func unregisterFeedbackNotification() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationUserDidTakeScreenshotNotification, object: nil) } #endif private func setupWebServer() { let server = WebServer.sharedInstance ReaderModeHandlers.register(server) server.start() } } #if MOZ_CHANNEL_AURORA private let AuroraBundleIdentifier = "org.mozilla.ios.FennecAurora" private let AuroraPropertyListURL = "https://pvtbuilds.mozilla.org/ios/FennecAurora.plist" private let AuroraDownloadPageURL = "https://pvtbuilds.mozilla.org/ios/index.html" extension AppDelegate: UIAlertViewDelegate { private func checkForAuroraUpdate() { if isAuroraChannel() { if let localVersion = localVersion() { fetchLatestAuroraVersion() { version in if let remoteVersion = version { if localVersion.compare(remoteVersion, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending { self.naggedAboutAuroraUpdate = true let alert = UIAlertView(title: "New version available", message: "There is a new version available of Firefox Aurora. Tap OK to go to the download page.", delegate: self, cancelButtonTitle: "Not Now", otherButtonTitles: "OK") alert.show() } } } } } } private func isAuroraChannel() -> Bool { return NSBundle.mainBundle().bundleIdentifier == AuroraBundleIdentifier } private func localVersion() -> NSString? { return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey) as? String } private func fetchLatestAuroraVersion(completionHandler: NSString? -> Void) { Alamofire.request(.GET, AuroraPropertyListURL).responsePropertyList({ (_, _, object, _) -> Void in if let plist = object as? NSDictionary { if let items = plist["items"] as? NSArray { if let item = items[0] as? NSDictionary { if let metadata = item["metadata"] as? NSDictionary { if let remoteVersion = metadata["bundle-version"] as? String { completionHandler(remoteVersion) return } } } } } completionHandler(nil) }) } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == 1 { UIApplication.sharedApplication().openURL(NSURL(string: AuroraDownloadPageURL)!) } } } extension AppDelegate: MFMailComposeViewControllerDelegate { func sendFeedbackMailWithImage(image: UIImage) { if (MFMailComposeViewController.canSendMail()) { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as String let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey) as String let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setSubject("Feedback on iOS client version v\(appVersion) (\(buildNumber))") mailComposeViewController.setToRecipients(["[email protected]"]) let imageData = UIImagePNGRepresentation(image) mailComposeViewController.addAttachmentData(imageData, mimeType: "image/png", fileName: "feedback.png") self.window.rootViewController?.presentViewController(mailComposeViewController, animated: true, completion: nil) } } func mailComposeController(mailComposeViewController: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { mailComposeViewController.dismissViewControllerAnimated(true, completion: nil) } } #endif
mpl-2.0
057721ecb34ee48e3d501fe8096aee6e
40.1875
253
0.661912
6.045872
false
false
false
false
jkiley129/Artfull
Artfull/ARTLargeInstagramImageViewController.swift
1
1355
// // ARTLargeInstagramImageViewController.swift // Artfull // // Created by Joseph Kiley on 12/2/15. // Copyright © 2015 Joseph Kiley. All rights reserved. // import UIKit class ARTLargeInstagramImage: UIViewController { var instagramImage : UIImage! @IBOutlet weak var blurView: UIVisualEffectView! @IBOutlet weak var mainImageView: UIImageView! @IBOutlet weak var backgroundImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.mainImageView.image = instagramImage self.backgroundImageView.image = instagramImage self.view.backgroundColor = UIColor(colorLiteralRed: 0.2, green: 0.2, blue: 0.2, alpha: 0.8) let dismissButton = UIButton(frame: self.view.frame) dismissButton.backgroundColor = UIColor.clearColor() dismissButton.addTarget(self, action: "dismissVC", forControlEvents: UIControlEvents.TouchUpInside) self.view.insertSubview(dismissButton, belowSubview: self.mainImageView) self.mainImageView.userInteractionEnabled = false } func dismissVC() { self.dismissViewControllerAnimated(true, completion: nil) } override func prefersStatusBarHidden() -> Bool { return true } }
mit
48da73ce90439144e609f99a9f8d2be3
27.208333
107
0.659527
5.167939
false
false
false
false
nicktoumpelis/HiBeacons
HiBeacons Watch App Extension/NATHiBeaconsInterfaceController.swift
1
6675
// // NATHiBeaconsInterfaceController.swift // HiBeacons Watch App Extension // // Created by Nick Toumpelis on 2015-08-06. // Copyright © 2015 Nick Toumpelis. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import WatchKit import WatchConnectivity import Foundation /// The main class for implementing the watch app interface. class NATHiBeaconsInterfaceController: WKInterfaceController { /// The button for starting/stopping the monitoring operation. @IBOutlet weak var monitoringButton: WKInterfaceButton? /// The button for starting/stopping the advertising operation. @IBOutlet weak var advertisingButton: WKInterfaceButton? /// The button for starting/stopping the ranging operation. @IBOutlet weak var rangingButton: WKInterfaceButton? /// The state of the monitoring operation. var monitoringActive = false /// The state of the advertising operation. var advertisingActive = false /// The state of the ranging operation. var rangingActive = false /// The default Watch Connectivity session. var defaultSession: WCSession? /// The color used for the active state of an operation button. let activeBackgroundColor = UIColor(red: 0.34, green: 0.7, blue: 0.36, alpha: 1.0) /// The color used for the inactive state of an operation button. let inactiveBackgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) /** Helper method that returns the WKInterfaceButton instance associated with a given operation. :param: operation A given operation. :returns: An instance of a WKInterfaceButton. */ func buttonFor(operation: NATOperationType) -> WKInterfaceButton? { switch operation { case .monitoring: return monitoringButton case .advertising: return advertisingButton case .ranging: return rangingButton } } /// Finishes the interface initialization, and activates the default WCSession. override func awake(withContext context: Any?) { super.awake(withContext: context) monitoringButton?.setBackgroundColor(inactiveBackgroundColor) advertisingButton?.setBackgroundColor(inactiveBackgroundColor) rangingButton?.setBackgroundColor(inactiveBackgroundColor) if WCSession.isSupported() { defaultSession = WCSession.default() defaultSession!.delegate = self defaultSession!.activate() } } /** Changes the local state to a given value for the given operation. (The local state should always reflect the "reality" of the operations happening on the phone.) :param: value The new value of the active state for the given operation. :param: operation The operation for which the active state should be changed. */ func setActiveState(_ value: Bool, forOperation operation: NATOperationType) { if defaultSession!.isReachable != true { return } switch operation { case .monitoring: monitoringActive = value case .advertising: advertisingActive = value case .ranging: rangingActive = value } let backgroundColor = value ? activeBackgroundColor : inactiveBackgroundColor buttonFor(operation: operation)?.setBackgroundColor(backgroundColor) } /** Prepares and sends a message to trigger a change to a given state of the given operation on the phone. :param: operation The operation for which the state should be changed. :param: state The new state for the given operation. */ func sendMessageFor(operation: NATOperationType, withState state: Bool) { let payload = [operation.rawValue: state] defaultSession!.sendMessage(payload, replyHandler: nil, errorHandler: nil) } /// Toggles the state of the monitoring operation. @IBAction func toggleMonitoring() { sendMessageFor(operation: NATOperationType.monitoring, withState: !monitoringActive) } /// Toggles the state of the advertising operation. @IBAction func toggleAdvertising() { sendMessageFor(operation: NATOperationType.advertising, withState: !advertisingActive) } /// Toggles the state of the ranging operation. @IBAction func toggleRanging() { sendMessageFor(operation: NATOperationType.ranging, withState: !rangingActive) } } extension NATHiBeaconsInterfaceController: WCSessionDelegate { public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { if error != nil { print("Session failed to activate with error: \(error.debugDescription)") } } /** Called immediately when a message arrives. In this case, it processes each message to change the active state of an operation to reflect the state on the phone. */ func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { if let state = message[NATOperationType.monitoring.rawValue] as? Bool { setActiveState(state, forOperation: NATOperationType.monitoring) } else if let state = message[NATOperationType.advertising.rawValue] as? Bool { setActiveState(state, forOperation: NATOperationType.advertising) } else if let state = message[NATOperationType.ranging.rawValue] as? Bool { setActiveState(state, forOperation: NATOperationType.ranging) } } }
mit
0913f803ff548dd663024ee0a9b57f55
38.258824
109
0.701079
5.098549
false
false
false
false
srn214/Floral
Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/pop/HDAlertWindowView.swift
2
4706
// // HDAlertWindowView.swift // ImageDeal // // Created by darren on 2017/8/1. // Copyright © 2017年 陈亮陈亮. All rights reserved. // import UIKit class HDAlertWindowView: UIView { // 屏幕宽度 @objc let APPH = UIScreen.main.bounds.height // 屏幕高度 @objc let APPW = UIScreen.main.bounds.width @objc lazy var coverView: UIView = { let cover = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) cover.backgroundColor = UIColor(white: 0, alpha: 0.6) return cover }() @objc lazy var nomalView: NomalStyleView = { let bottom = NomalStyleView.show() self.addSubview(bottom) return bottom }() @objc lazy var messageView: MessageStyleView = { let bottom = MessageStyleView.show() self.addSubview(bottom) return bottom }() //MARK: - 展示控制器 fileprivate func showVC() { UIApplication.shared.keyWindow?.addSubview(self.coverView) UIApplication.shared.keyWindow?.addSubview(self) } fileprivate func dismissView() { self.coverView.removeFromSuperview() self.removeFromSuperview() } } //MARK: - 标准样式(标题,内容,左按钮,右按钮) extension HDAlertWindowView{ @objc func alert(title: String!,message: String!,leftTitle: String!,rightTitle: String!,leftHandler: (() -> ())?,rightHandler: (() -> ())?){ // modal showVC() // 调整弹出框的尺寸、位置,赋值 self.nomalView.titleLabel.text = title self.nomalView.contentLabel.text = message self.nomalView.leftBtn.setTitle(leftTitle, for: .normal) self.nomalView.rightBtn.setTitle(rightTitle, for: .normal) // 宽度的设置要在layoutIfNeeded方法之前 // self.nomalView.hd_width = 100 // 赋值后注意重新布局一下,不然如果xib中lable没有设置文字,view的尺寸会不对 self.nomalView.layoutIfNeeded() self.nomalView.frame.size.height = self.nomalView.contentLabel.frame.maxY + self.nomalView.btnsBottomView.frame.height + self.nomalView.contentLableBottomYS.constant self.nomalView.center = self.center self.nomalView.leftHendle = { () in self.dismissView() if leftHandler != nil { leftHandler!() } } self.nomalView.rightHendle = { () in self.dismissView() if rightHandler != nil { rightHandler!() } } } } //MARK: - 一个主标题 (内容,左按钮,右按钮) extension HDAlertWindowView{ @objc func alert(message: String!,leftTitle: String!,rightTitle: String!,leftHandler: (() -> ())?,rightHandler: (() -> ())?){ // modal 控制器 showVC() // 调整弹出框的尺寸、位置,赋值 self.messageView.contentLabel.text = message self.messageView.leftBtn.setTitle(leftTitle, for: .normal) self.messageView.rightBtn.setTitle(rightTitle, for: .normal) // 宽度的设置要在layoutIfNeeded方法之前 // self.messageView.hd_width = 100 // 赋值后注意重新布局一下,不然如果xib中lable没有设置文字,view的尺寸会不对 self.messageView.layoutIfNeeded() self.messageView.frame.size.height = self.messageView.contentLabel.frame.maxY + self.messageView.btnsBottomView.frame.height + self.messageView.contentLableBottomYS.constant self.messageView.center = self.center if leftTitle == "" || rightTitle == ""{ self.messageView.middleBtn.isHidden = false let title = leftTitle == "" ? rightTitle:leftTitle self.messageView.middleBtn.setTitle(title, for: .normal) } self.messageView.middleHendle = { () in self.dismissView() if leftTitle == "" { if rightHandler != nil { rightHandler!() } } if rightTitle == "" { if leftHandler != nil { leftHandler!() } } } self.messageView.leftHendle = { () in self.dismissView() if leftHandler != nil { leftHandler!() } } self.messageView.rightHendle = { () in self.dismissView() if rightHandler != nil { rightHandler!() } } } }
mit
c60bace4c0b06794375c87b1e8b0f79c
31.198529
181
0.570678
4.450203
false
false
false
false
TouchInstinct/LeadKit
TISwiftUtils/Sources/PropertyWrappers/BackingStore.swift
1
2292
// // Copyright (c) 2020 Touch Instinct // // 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. // @propertyWrapper public struct BackingStore<Store, StoreContent> { public typealias InitClosure = (StoreContent) -> Store public typealias GetClosure = (Store) -> StoreContent public typealias SetClosure = (Store, StoreContent) -> Void private let getClosure: GetClosure private let setClosure: SetClosure private let store: Store public init(wrappedValue: StoreContent, storageInitClosure: InitClosure, getClosure: @escaping GetClosure, setClosure: @escaping SetClosure) { self.store = storageInitClosure(wrappedValue) self.getClosure = getClosure self.setClosure = setClosure } public init(store: Store, getClosure: @escaping GetClosure, setClosure: @escaping SetClosure) { self.store = store self.getClosure = getClosure self.setClosure = setClosure } public var wrappedValue: StoreContent { get { getClosure(store) } set { setClosure(store, newValue) } } public var projectedValue: Store { store } }
apache-2.0
04db4c555ffcf3b157b7e42514ea0759
34.261538
81
0.686736
4.845666
false
false
false
false
xwu/swift
libswift/Sources/Optimizer/FunctionPasses/MergeCondFails.swift
2
3439
//===--- MergeCondFail.swift - Merge cond_fail instructions --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL let mergeCondFailsPass = FunctionPass(name: "merge-cond_fails", runMergeCondFails) /// Return true if the operand of the cond_fail instruction looks like /// the overflow bit of an arithmetic instruction. private func hasOverflowConditionOperand(_ cfi: CondFailInst) -> Bool { if let tei = cfi.operand as? TupleExtractInst { return tei.operand is BuiltinInst } return false } /// Merge cond_fail instructions. /// /// We can merge cond_fail instructions if there is no side-effect or memory /// write in between them. /// This pass merges cond_fail instructions by building the disjunction of /// their operands. private func runMergeCondFails(function: Function, context: PassContext) { // Merge cond_fail instructions if there is no side-effect or read in // between them. for block in function.blocks { // Per basic block list of cond_fails to merge. var condFailToMerge = StackList<CondFailInst>(context) for inst in block.instructions { if let cfi = inst as? CondFailInst { // Do not process arithmetic overflow checks. We typically generate more // efficient code with separate jump-on-overflow. if !hasOverflowConditionOperand(cfi) && (condFailToMerge.isEmpty || cfi.message == condFailToMerge.first!.message) { condFailToMerge.push(cfi) } } else if inst.mayHaveSideEffects || inst.mayReadFromMemory { // Stop merging at side-effects or reads from memory. mergeCondFails(&condFailToMerge, context: context) } } // Process any remaining cond_fail instructions in the current basic // block. mergeCondFails(&condFailToMerge, context: context) } } /// Try to merge the cond_fail instructions. Returns true if any could /// be merge. private func mergeCondFails(_ condFailToMerge: inout StackList<CondFailInst>, context: PassContext) { guard let lastCFI = condFailToMerge.last else { return } var mergedCond: Value? = nil var didMerge = false let builder = Builder(at: lastCFI.next!, location: lastCFI.location, context) // Merge conditions and remove the merged cond_fail instructions. for cfi in condFailToMerge { if let prevCond = mergedCond { mergedCond = builder.createBuiltinBinaryFunction(name: "or", operandType: prevCond.type, resultType: prevCond.type, arguments: [prevCond, cfi.operand]) didMerge = true } else { mergedCond = cfi.operand } } if !didMerge { condFailToMerge.removeAll() return } // Create a new cond_fail using the merged condition. _ = builder.createCondFail(condition: mergedCond!, message: lastCFI.message) while let cfi = condFailToMerge.pop() { context.erase(instruction: cfi) } }
apache-2.0
1f42cbd117229bd2621f847e80c488d5
35.585106
87
0.657168
4.710959
false
false
false
false
radex/swift-compiler-crashes
crashes-fuzzing/06633-swift-typechecker-applygenericarguments.swift
11
2213
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A { func a<d where T : e : A.C protocol e = F>(" typealias f = F>(a<H : a { func b<H : b { func c <d where T : A.c { } class A { [] class A { let start = B, leng class A { typealias e : f.a typealias f = B, leng func a extension NSData { func a")) } func a<H : e) } if true {} class A { if true { return " let t: a func c st let t: b { func a class A { class A { st func c <H : A.c { } func a extension NSData { 0.C protocol P { 0.C 0.c { } st [] protocol c : e = b<d { return " protocol c : A { protocol e : e : a { class A { st <d { protocol B : a { 0.a<d { } protocol c { func a")) let t: a(" protocol P { } typealias e : a(a enum b {} var _ = c var _ = b protocol e : f.a") struct B, leng } func b } enum b { func c protocol A { protocol c { protocol A { } func b [] } func b [] protocol e : f.C typealias e : b { func b<d { typealias e = F>(a struct B, leng let start = c } st st func a(") struct B, leng protocol P { struct B, leng var _ = b protocol e = F>(") var _ = F>(a let start = F>(a<d where T : f.c : A.C protocol e = B, leng enum b { func a(a<H : b { func b<d where T : A { func a<H : e { struct B, leng func a func a typealias e : A.a typealias e = b protocol B : b { func a(a(")) 0.c { [] protocol A { protocol c : b { func a func a } protocol A { } protocol e : c { enum B : e : b { func b enum B : f.C [] } struct B, leng if true { 0.c { func a") protocol A { protocol c : f.c : b { func b<d { } [] typealias e { <H : A.C } 0.a var _ = c func b } 0.a<T : b { } } [] extension NSData { extension NSData { 0.c : a { extension NSData { protocol P { class A { protocol e : A { protocol c { extension NSData { func b return " protocol B : a { <d { func a } } func b<H : a<T : e : e : b { } } protocol c : a<T : A.a<T : e : e = c func b struct B, leng } let start = F>(a") } typealias e { class A { protocol c : A.a let start = c <H : A.a func a enum b { st func a class A { typealias e : b { func a 0.c { var _ = B, leng typealias e : A.c { protocol P {} protocol P { return ") class A { func a<d { typealias e : c { 0.c
mit
abc80e0e1f0500f7cea86ed53abb166d
10.897849
87
0.589697
2.415939
false
false
false
false
yonasstephen/swift-of-airbnb
frameworks/airbnb-datepicker/airbnb-datepicker/AirbnbDatePickerViewController.swift
1
26666
// // AirbnbDatePickerViewController.swift // airbnb-datepicker // // Created by Yonas Stephen on 22/2/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit public protocol AirbnbDatePickerDelegate { func datePickerController(_ datePickerController: AirbnbDatePickerViewController, didSaveStartDate startDate: Date?, endDate: Date?) } public class AirbnbDatePickerViewController: UICollectionViewController { let monthHeaderID = "monthHeaderID" let cellID = "cellID" let dateFormatter = DateFormatter() var delegate: AirbnbDatePickerDelegate? var selectedStartDate: Date? { didSet { headerView.selectedStartDate = selectedStartDate footerView.isSaveEnabled = (selectedStartDate == nil || selectedEndDate != nil) } } var startDateIndexPath: IndexPath? var selectedEndDate: Date? { didSet { headerView.selectedEndDate = selectedEndDate footerView.isSaveEnabled = (selectedStartDate == nil || selectedEndDate != nil) } } var endDateIndexPath: IndexPath? var today: Date! var calendar: Calendar { return Utility.calendar } var isLoadingMore = false var initialNumberOfMonths = 24 var subsequentMonthsLoadCount = 12 var lastNthMonthBeforeLoadMore = 12 var months: [Date]! var days: [(days: Int, prepend: Int, append: Int)]! var itemWidth: CGFloat { return floor(view.frame.size.width / 7) } var collectionViewWidthConstraint: NSLayoutConstraint? // MARK: - Initialization convenience init(dateFrom: Date?, dateTo: Date?) { self.init(collectionViewLayout: UICollectionViewFlowLayout()) today = Date() initDates() // put in closure to trigger didSet ({ selectedStartDate = dateFrom })() ({ selectedEndDate = dateTo })() if selectedStartDate != nil && startDateIndexPath == nil { startDateIndexPath = findIndexPath(forDate: selectedStartDate!) if let indexPath = startDateIndexPath { collectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .left) } } if selectedEndDate != nil && endDateIndexPath == nil { endDateIndexPath = findIndexPath(forDate: selectedEndDate!) if let indexPath = endDateIndexPath { collectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .left) } } NotificationCenter.default.addObserver(self, selector: #selector(AirbnbDatePickerViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } func initDates() { let month = calendar.component(.month, from: today) let year = calendar.component(.year, from: today) let dateComp = DateComponents(year: year, month: month, day: 1) var curMonth = calendar.date(from: dateComp) months = [Date]() days = [(days: Int, prepend: Int, append: Int)]() for _ in 0..<initialNumberOfMonths { months.append(curMonth!) let numOfDays = calendar.range(of: .day, in: .month, for: curMonth!)!.count let firstWeekDay = calendar.component(.weekday, from: curMonth!.startOfMonth()) let lastWeekDay = calendar.component(.weekday, from: curMonth!.endOfMonth()) days.append((days: numOfDays, prepend: firstWeekDay - 1, append: 7 - lastWeekDay)) curMonth = calendar.date(byAdding: .month, value: 1, to: curMonth!) } } // MARK: - View Components lazy var dismissButton: UIBarButtonItem = { let btn = UIButton(type: UIButtonType.custom) btn.setImage(UIImage(named: "Delete", in: Bundle(for: AirbnbDatePicker.self), compatibleWith: nil), for: .normal) btn.frame = CGRect(x: 0, y: 0, width: 20, height: 20) btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left btn.addTarget(self, action: #selector(AirbnbDatePickerViewController.handleDismiss), for: .touchUpInside) let barBtn = UIBarButtonItem(customView: btn) return barBtn }() lazy var clearButton: UIBarButtonItem = { let btn = UIButton(type: UIButtonType.custom) btn.setTitle("Clear", for: .normal) btn.frame = CGRect(x: 0, y: 0, width: 100, height: 20) btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right btn.titleLabel?.font = UIFont.systemFont(ofSize: 15) btn.addTarget(self, action: #selector(AirbnbDatePickerViewController.handleClearInput), for: .touchUpInside) let barBtn = UIBarButtonItem(customView: btn) return barBtn }() var headerView: AirbnbDatePickerHeader = { let view = AirbnbDatePickerHeader() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.PRIMARY_COLOR return view }() var headerSeparator: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.SECONDARY_COLOR return view }() lazy var footerView: AirbnbDatePickerFooter = { let view = AirbnbDatePickerFooter() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.PRIMARY_COLOR view.delegate = self return view }() var footerSeparator: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = Theme.SECONDARY_COLOR return view }() // MARK: - View Setups override public func viewDidLoad() { super.viewDidLoad() } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if #available(iOS 11, *) { } else { self.automaticallyAdjustsScrollViewInsets = false } self.view.backgroundColor = Theme.PRIMARY_COLOR setupNavigationBar() setupViews() setupLayout() } @objc func rotated() { collectionView?.collectionViewLayout.invalidateLayout() } func setupNavigationBar() { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.view.backgroundColor = UIColor.clear self.navigationItem.setLeftBarButton(dismissButton, animated: true) self.navigationItem.setRightBarButton(clearButton, animated: true) } func setupViews() { setupHeaderView() setupFooterView() setupCollectionView() } func setupHeaderView() { view.addSubview(headerView) headerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true headerView.topAnchor.constraint(equalTo: view.topAnchor, constant: self.navigationController != nil ? self.navigationController!.navigationBar.frame.size.height : 0).isActive = true headerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true headerView.heightAnchor.constraint(equalToConstant: 150).isActive = true view.addSubview(headerSeparator) headerSeparator.topAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true headerSeparator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true headerSeparator.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true headerSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true } func setupCollectionView() { collectionView?.translatesAutoresizingMaskIntoConstraints = false collectionView?.alwaysBounceVertical = true collectionView?.backgroundColor = Theme.PRIMARY_COLOR collectionView?.showsVerticalScrollIndicator = false collectionView?.allowsMultipleSelection = true collectionView?.register(AirbnbDatePickerCell.self, forCellWithReuseIdentifier: cellID) collectionView?.register(AirbnbDatePickerMonthHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: monthHeaderID) collectionView?.topAnchor.constraint(equalTo: headerSeparator.bottomAnchor).isActive = true collectionView?.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true collectionView?.bottomAnchor.constraint(equalTo: footerSeparator.topAnchor).isActive = true let gap = view.frame.size.width - (itemWidth * 7) collectionViewWidthConstraint = collectionView?.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -gap) collectionViewWidthConstraint?.isActive = true } func setupLayout() { if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout { layout.scrollDirection = .vertical layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets() layout.itemSize = CGSize(width: itemWidth, height: itemWidth) } } func setupFooterView() { view.addSubview(footerView) footerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true footerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true footerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true footerView.heightAnchor.constraint(equalToConstant: 60).isActive = true view.addSubview(footerSeparator) footerSeparator.bottomAnchor.constraint(equalTo: footerView.topAnchor).isActive = true footerSeparator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true footerSeparator.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true footerSeparator.heightAnchor.constraint(equalToConstant: 1).isActive = true } // MARK: - Collection View Delegates override public func numberOfSections(in collectionView: UICollectionView) -> Int { return months.count } override public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return days[section].prepend + days[section].days + days[section].append } override public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { // Load more months on reaching last (n)th month if indexPath.section == (months.count - lastNthMonthBeforeLoadMore) && !isLoadingMore { let originalCount = months.count isLoadingMore = true DispatchQueue.global(qos: .background).async { self.loadMoreMonths(completion: { () in DispatchQueue.main.async { collectionView.performBatchUpdates({ () in let range = originalCount..<originalCount.advanced(by: self.subsequentMonthsLoadCount) let indexSet = IndexSet(integersIn: range) collectionView.insertSections(indexSet) }, completion: { (res) in self.isLoadingMore = false }) } }) } } } override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! AirbnbDatePickerCell configure(cell: cell, withIndexPath: indexPath) return cell } override public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: monthHeaderID, for: indexPath) as! AirbnbDatePickerMonthHeader let monthData = months[indexPath.section] let curYear = calendar.component(.year, from: today) let year = calendar.component(.year, from: monthData) let month = calendar.component(.month, from: monthData) if (curYear == year) { header.monthLabel.text = dateFormatter.monthSymbols[month - 1] } else { header.monthLabel.text = "\(dateFormatter.shortMonthSymbols[month - 1]) \(year)" } return header } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: self.view.frame.width, height: 50) } override public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell cell.type.insert(.Selected) let selectedMonth = months[indexPath.section] let year = calendar.component(.year, from: selectedMonth) let month = calendar.component(.month, from: selectedMonth) let dateComp = DateComponents(year: year, month: month, day: Int(cell.dateLabel.text!)) let selectedDate = calendar.date(from: dateComp)! if selectedStartDate == nil || (selectedEndDate == nil && selectedDate < selectedStartDate!) { if startDateIndexPath != nil, let prevStartCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { prevStartCell.type.remove(.Selected) prevStartCell.configureCell() collectionView.deselectItem(at: startDateIndexPath!, animated: false) } selectedStartDate = selectedDate startDateIndexPath = indexPath } else if selectedEndDate == nil { selectedEndDate = selectedDate endDateIndexPath = indexPath // select start date to trigger cell UI change if let startCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { startCell.type.insert(.SelectedStartDate) startCell.configureCell() } // select end date to trigger cell UI change if let endCell = collectionView.cellForItem(at: endDateIndexPath!) as? AirbnbDatePickerCell { endCell.type.insert(.SelectedEndDate) endCell.configureCell() } // loop through cells in between selected dates and select them selectInBetweenCells() } else { // deselect previously selected cells deselectSelectedCells() selectedStartDate = selectedDate selectedEndDate = nil startDateIndexPath = indexPath endDateIndexPath = nil if let newStartCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { newStartCell.type.insert(.Selected) newStartCell.configureCell() } } cell.configureCell() } override public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell return cell.type.contains(.Date) } override public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell if isInBetween(indexPath: indexPath) { deselectSelectedCells() let selectedMonth = months[indexPath.section] let year = calendar.component(.year, from: selectedMonth) let month = calendar.component(.month, from: selectedMonth) let dateComp = DateComponents(year: year, month: month, day: Int(cell.dateLabel.text!)) let selectedDate = calendar.date(from: dateComp)! selectedStartDate = selectedDate selectedEndDate = nil startDateIndexPath = indexPath endDateIndexPath = nil if let newStartCell = collectionView.cellForItem(at: startDateIndexPath!) as? AirbnbDatePickerCell { newStartCell.type.insert(.Selected) newStartCell.configureCell() collectionView.selectItem(at: startDateIndexPath!, animated: false, scrollPosition: .left) } } } override public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { if selectedEndDate == nil && startDateIndexPath == indexPath { return false } return true } override public func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell cell.type.insert(.Highlighted) cell.configureCell() } override public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell return cell.type.contains(.Date) } override public func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! AirbnbDatePickerCell cell.type.remove(.Highlighted) cell.configureCell() } func configure(cell: AirbnbDatePickerCell, withIndexPath indexPath: IndexPath) { let dateData = days[indexPath.section] let month = calendar.component(.month, from: months[indexPath.section]) let year = calendar.component(.year, from: months[indexPath.section]) if indexPath.item < dateData.prepend || indexPath.item >= (dateData.prepend + dateData.days) { cell.dateLabel.text = "" cell.type = [.Empty] } else { let todayYear = calendar.component(.year, from: today) let todayMonth = calendar.component(.month, from: today) let todayDay = calendar.component(.day, from: today) let curDay = indexPath.item - dateData.prepend + 1 let isPastDate = year == todayYear && month == todayMonth && curDay < todayDay cell.dateLabel.text = String(curDay) cell.dateLabel.textColor = isPastDate ? Theme.SECONDARY_COLOR : UIColor.white cell.type = isPastDate ? [.PastDate] : [.Date] if todayDay == curDay, todayMonth == month, todayYear == year { cell.type.insert(.Today) } } if startDateIndexPath != nil && indexPath == startDateIndexPath { if endDateIndexPath == nil { cell.type.insert(.Selected) } else { cell.type.insert(.SelectedStartDate) } } if endDateIndexPath != nil { if indexPath == endDateIndexPath { cell.type.insert(.SelectedEndDate) } else if isInBetween(indexPath: indexPath) { cell.type.insert(.InBetweenDate) } } cell.configureCell() } func isInBetween(indexPath: IndexPath) -> Bool { if let start = startDateIndexPath, let end = endDateIndexPath { return (indexPath.section > start.section || (indexPath.section == start.section && indexPath.item > start.item)) && (indexPath.section < end.section || (indexPath.section == end.section && indexPath.item < end.item)) } return false } func selectInBetweenCells() { var section = startDateIndexPath!.section var item = startDateIndexPath!.item var indexPathArr = [IndexPath]() while section < months.count, section <= endDateIndexPath!.section { let curIndexPath = IndexPath(item: item, section: section) if let cell = collectionView?.cellForItem(at: curIndexPath) as? AirbnbDatePickerCell { if curIndexPath != startDateIndexPath && curIndexPath != endDateIndexPath { cell.type.insert(.InBetweenDate) cell.configureCell() } indexPathArr.append(curIndexPath) } if section == endDateIndexPath!.section && item >= endDateIndexPath!.item { // stop iterating beyond end date break } else if item >= (collectionView!.numberOfItems(inSection: section) - 1) { // more than num of days in the month section += 1 item = 0 } else { item += 1 } } collectionView?.performBatchUpdates({ self.collectionView?.reloadItems(at: indexPathArr) }, completion: nil) } func deselectSelectedCells() { if let start = startDateIndexPath { var section = start.section var item = start.item + 1 if let cell = collectionView?.cellForItem(at: start) as? AirbnbDatePickerCell { cell.type.remove([.InBetweenDate, .SelectedStartDate, .SelectedEndDate, .Selected]) cell.configureCell() collectionView?.deselectItem(at: start, animated: false) } if let end = endDateIndexPath { let indexPathArr = [IndexPath]() while section < months.count, section <= end.section { let curIndexPath = IndexPath(item: item, section: section) if let cell = collectionView?.cellForItem(at: curIndexPath) as? AirbnbDatePickerCell { cell.type.remove([.InBetweenDate, .SelectedStartDate, .SelectedEndDate, .Selected]) cell.configureCell() collectionView?.deselectItem(at: curIndexPath, animated: false) } if section == end.section && item >= end.item { // stop iterating beyond end date break } else if item >= (collectionView!.numberOfItems(inSection: section) - 1) { // more than num of days in the month section += 1 item = 0 } else { item += 1 } } collectionView?.performBatchUpdates({ self.collectionView?.reloadItems(at: indexPathArr) }, completion: nil) } } } // MARK: - Event Handlers @objc func handleDismiss() { self.navigationController?.dismiss(animated: true, completion: nil) } @objc func handleClearInput() { deselectSelectedCells() selectedStartDate = nil selectedEndDate = nil startDateIndexPath = nil endDateIndexPath = nil } func loadMoreMonths(completion: (() -> Void)?) { let lastDate = months.last! let month = calendar.component(.month, from: lastDate) let year = calendar.component(.year, from: lastDate) let dateComp = DateComponents(year: year, month: month + 1, day: 1) var curMonth = calendar.date(from: dateComp) for _ in 0..<subsequentMonthsLoadCount { months.append(curMonth!) let numOfDays = calendar.range(of: .day, in: .month, for: curMonth!)!.count let firstWeekDay = calendar.component(.weekday, from: curMonth!.startOfMonth()) let lastWeekDay = calendar.component(.weekday, from: curMonth!.endOfMonth()) days.append((days: numOfDays, prepend: firstWeekDay - 1, append: 7 - lastWeekDay)) curMonth = calendar.date(byAdding: .month, value: 1, to: curMonth!) } if let handler = completion { handler() } } // MARK: - Functions func findIndexPath(forDate date: Date) -> IndexPath? { var indexPath: IndexPath? = nil if let section = months.index(where: { calendar.component(.year, from: $0) == calendar.component(.year, from: date) && calendar.component(.month, from: $0) == calendar.component(.month, from: date)}) { let item = days[section].prepend + calendar.component(.day, from: date) - 1 indexPath = IndexPath(item: item, section: section) } return indexPath } } // MARK: - AirbnbDatePickerFooterDelegate extension AirbnbDatePickerViewController: AirbnbDatePickerFooterDelegate { func didSave() { if let del = delegate { del.datePickerController(self, didSaveStartDate: selectedStartDate, endDate: selectedEndDate) self.navigationController?.dismiss(animated: true, completion: nil) } } }
mit
4e77e663f77d7650bee822bfe7045bf6
40.086287
198
0.619539
5.810634
false
false
false
false
lexchou/swallow
stdlib/core/OperatorGreaterEqual.swift
1
834
func >=(lhs: UInt8, rhs: UInt8) -> Bool { return false//TODO } func >=(lhs: Int8, rhs: Int8) -> Bool { return false//TODO } func >=(lhs: UInt16, rhs: UInt16) -> Bool { return false//TODO } func >=(lhs: Int16, rhs: Int16) -> Bool { return false//TODO } func >=(lhs: UInt32, rhs: UInt32) -> Bool { return false//TODO } func >=(lhs: Int32, rhs: Int32) -> Bool { return false//TODO } func >=(lhs: UInt64, rhs: UInt64) -> Bool { return false//TODO } func >=(lhs: Int64, rhs: Int64) -> Bool { return false//TODO } func >=(lhs: UInt, rhs: UInt) -> Bool { return false//TODO } func >=(lhs: Int, rhs: Int) -> Bool { return false//TODO } func >=<T : _Comparable>(lhs: T?, rhs: T?) -> Bool { return false//TODO } func >=<T : _Comparable>(lhs: T, rhs: T) -> Bool { return false//TODO }
bsd-3-clause
cb04a42b580f39b89a38d66d1eb56e22
16.375
52
0.565947
2.875862
false
false
false
false
davbeck/PG.swift
Tests/pgTests/DateCodingTests.swift
1
1353
import Foundation import XCTest @testable import PG func XCTAssertEqualDates(_ expression1: Date?, _ expression2: Date?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { guard let lhs = expression1, let rhs = expression2 else { // check if both are nil XCTAssert(expression1 == expression2, message, file: file, line: line) return } let difference = abs(lhs.timeIntervalSince1970.distance(to: rhs.timeIntervalSince1970)) XCTAssert(difference < 0.01, message, file: file, line: line) } class DateCodingTests: XCTestCase { func testTimestampWithoutTimezone() { XCTAssertEqualDates( Date(pgText: "2017-05-19 16:37:46.39800", type: .timestamp), Date(timeIntervalSince1970: 1495211866.398) ) XCTAssertEqual( Date(timeIntervalSince1970: 1495211866.398).pgText, "2017-05-19 16:37:46.398000" ) XCTAssertEqualDates( Date(pgBinary: Slice<Data>(Data(base64Encoded: "AAHzHRMD4Ic=")!), type: .timestamp), Date(timeIntervalSince1970: 1495465975.333) ) XCTAssertEqual( Date(timeIntervalSince1970: 1495465975.333).pgBinary, Data(base64Encoded: "AAHzHRMD4Ic=") ) } func testTimestampWithTimezone() { XCTAssertEqual( Date(pgText: "2017-05-19 16:37:46.398991-07", type: .timestampWithTimezone), Date(timeIntervalSince1970: 1495237066.398) ) } }
mit
e75be7298b8108d3910807292f00cf2f
27.1875
161
0.72136
3.260241
false
true
false
false
dzt/algonquin
Algonquin/LoginTableViewController.swift
1
3130
// // LoginTableViewController.swift // Algonquin // // Created by Peter Soboyejo on 8/26/17. // Copyright © 2017 Peter Soboyejo. All rights reserved. // import RealmSwift import UIKit import SVProgressHUD class LoginTableViewController: UITableViewController{ var lastY: CGFloat = 0.0 @IBOutlet weak var userid: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.statusBarStyle = .lightContent SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.light) SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tap) loginButton.addTarget(self, action: #selector(LoginTableViewController.login(sender:)), for: .touchUpInside) } func login(sender: UIButton) { SVProgressHUD.show() if userid.text == "" || password.text == "" { let alert = UIAlertController(title: "Whoops", message: "You cannot leave any of the fields empty.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in print("Ok was clicked") })) self.present(alert, animated: true, completion: nil) return } Client.shared.parser.getSummary(userid: userid.text!, password: password.text!) { summary, error in guard let summary = summary else { print("Error while Logging In") SVProgressHUD.showError(withStatus: "Error Occured while Logging you in, please check your credentials and try again.") return } DispatchQueue.main.async { SVProgressHUD.dismiss() let account = Account() account.userid = self.userid.text! account.password = self.password.text! let realm = try! Realm() try! realm.write { realm.add(account) } self.performSegue(withIdentifier: "afterLogin", sender: nil) } } } func dismissKeyboard() { view.endEditing(true) } func scrollViewDidScroll(scrollView: UIScrollView) { let currentY = scrollView.contentOffset.y let currentBottomY = scrollView.frame.size.height + currentY if currentY > lastY { //"scrolling down" tableView.bounces = true } else { //"scrolling up" // Check that we are not in bottom bounce if currentBottomY < scrollView.contentSize.height + scrollView.contentInset.bottom { tableView.bounces = false } } lastY = scrollView.contentOffset.y } }
mit
cfc352a06d5af140d5a48c69bfe492d9
31.59375
136
0.591563
5.376289
false
false
false
false
shorlander/firefox-ios
Shared/Functions.swift
3
6618
/* 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 SwiftyJSON // Pipelining. precedencegroup PipelinePrecedence { associativity: left } infix operator |> : PipelinePrecedence public func |> <T, U>(x: T, f: (T) -> U) -> U { return f(x) } // Basic currying. public func curry<A, B>(_ f: @escaping (A) -> B) -> (A) -> B { return { a in return f(a) } } public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C { return { a in return { b in return f(a, b) } } } public func curry<A, B, C, D>(_ f: @escaping (A, B, C) -> D) -> (A) -> (B) -> (C) -> D { return { a in return { b in return { c in return f(a, b, c) } } } } public func curry<A, B, C, D, E>(_ f: @escaping (A, B, C, D) -> E) -> (A, B, C) -> (D) -> E { return { (a, b, c) in return { d in return f(a, b, c, d) } } } // Function composition. infix operator • public func •<T, U, V>(f: @escaping (T) -> U, g: @escaping (U) -> V) -> (T) -> V { return { t in return g(f(t)) } } public func •<T, V>(f: @escaping (T) -> Void, g: @escaping () -> V) -> (T) -> V { return { t in f(t) return g() } } public func •<V>(f: @escaping () -> Void, g: @escaping () -> V) -> () -> V { return { f() return g() } } // Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse. // This is enough to catch arrays, which Swift will delegate to element-==. public func optArrayEqual<T: Equatable>(_ lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: // This delegates to Swift's own array '==', which calls T's == on each element. return lhs! == rhs! } } /** * Given an array, return an array of slices of size `by` (possibly excepting the last slice). * * If `by` is longer than the input, returns a single chunk. * If `by` is less than 1, acts as if `by` is 1. * If the length of the array isn't a multiple of `by`, the final slice will * be smaller than `by`, but never empty. * * If the input array is empty, returns an empty array. */ public func chunk<T>(_ arr: [T], by: Int) -> [ArraySlice<T>] { var result = [ArraySlice<T>]() var chunk = -1 let size = max(1, by) for (index, elem) in arr.enumerated() { if index % size == 0 { result.append(ArraySlice<T>()) chunk += 1 } result[chunk].append(elem) } return result } public func chunkCollection<E, X, T: Collection>(_ items: T, by: Int, f: ([E]) -> [X]) -> [X] where T.Iterator.Element == E { assert(by >= 0) let max = by > 0 ? by : 1 var i = 0 var acc: [E] = [] var results: [X] = [] var iter = items.makeIterator() while let item = iter.next() { if i >= max { results.append(contentsOf: f(acc)) acc = [] i = 0 } acc.append(item) i += 1 } if !acc.isEmpty { results.append(contentsOf: f(acc)) } return results } public extension Sequence { // [T] -> (T -> K) -> [K: [T]] // As opposed to `groupWith` (to follow Haskell's naming), which would be // [T] -> (T -> K) -> [[T]] func groupBy<Key, Value>(_ selector: (Self.Iterator.Element) -> Key, transformer: (Self.Iterator.Element) -> Value) -> [Key: [Value]] { var acc: [Key: [Value]] = [:] for x in self { let k = selector(x) var a = acc[k] ?? [] a.append(transformer(x)) acc[k] = a } return acc } func zip<S: Sequence>(_ elems: S) -> [(Self.Iterator.Element, S.Iterator.Element)] { var rights = elems.makeIterator() return self.flatMap { lhs in guard let rhs = rights.next() else { return nil } return (lhs, rhs) } } } public func optDictionaryEqual<K: Equatable, V: Equatable>(_ lhs: [K: V]?, rhs: [K: V]?) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case (.none, _): return false case (_, .none): return false default: return lhs! == rhs! } } /** * Return members of `a` that aren't nil, changing the type of the sequence accordingly. */ public func optFilter<T>(_ a: [T?]) -> [T] { return a.flatMap { $0 } } /** * Return a new map with only key-value pairs that have a non-nil value. */ public func optFilter<K, V>(_ source: [K: V?]) -> [K: V] { var m = [K: V]() for (k, v) in source { if let v = v { m[k] = v } } return m } /** * Map a function over the values of a map. */ public func mapValues<K, T, U>(_ source: [K: T], f: ((T) -> U)) -> [K: U] { var m = [K: U]() for (k, v) in source { m[k] = f(v) } return m } public func findOneValue<K, V>(_ map: [K: V], f: (V) -> Bool) -> V? { for v in map.values { if f(v) { return v } } return nil } /** * Take a JSON array, returning the String elements as an array. * It's usually convenient for this to accept an optional. */ public func jsonsToStrings(_ arr: [JSON]?) -> [String]? { return arr?.flatMap { $0.stringValue } } // Encapsulate a callback in a way that we can use it with NSTimer. private class Callback { private let handler:() -> Void init(handler:@escaping () -> Void) { self.handler = handler } @objc func go() { handler() } } /** * Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call * Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires. **/ public func debounce(_ delay: TimeInterval, action:@escaping () -> Void) -> () -> Void { let callback = Callback(handler: action) var timer: Timer? return { // If calling again, invalidate the last timer. if let timer = timer { timer.invalidate() } timer = Timer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false) RunLoop.current.add(timer!, forMode: RunLoopMode.defaultRunLoopMode) } }
mpl-2.0
863a1e86a34d804e1dead6ebc85944b5
25.126482
139
0.530862
3.372449
false
false
false
false
incoming-inc/ios-template-app
Swift/PVNSampleSwift/AppDelegate.swift
1
6419
// // AppDelegate.swift // PVNSampleSwift // // Created by Sebastien Ardon on 6/02/2015. // Copyright (c) 2015 Incoming Inc. All rights reserved. // import UIKit import UserNotifications import IncomingPVN @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // ISDK method forward ISDKAppDelegateHelper.application(application, didFinishLaunchingWithOptions:launchOptions) // Register for remote notifications. The Incoming PVN uses silent remote notifications for content updates. // You must call this method at some stage for the push video service to operate correctly. ISDKAppDelegateHelper.registerForRemoteNotifications() // This will pop-up the OS permission dialog, feel free to // integrate them differently in your workflow, e.g. after prompting the user if they'd agree to do so ISDKAppDelegateHelper.registerForNotifications() // set UNNUserNotificationCenter delegate if #available(iOS 10.0, *) { let notificationCenter = UNUserNotificationCenter.current() notificationCenter.delegate = self } // the two following calls are optional. They enable location and motion data collection // which improves the timing prediction of Push Video Notifications. // Calling these methods may result in the OS permission dialog being presented // to the user. ISDKAppDelegateHelper.registerForLocationUpdates() ISDKAppDelegateHelper.registerForMotionActivity() // <insert your app initialization code here> return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { // ISDK method forward if (ISDKAppDelegateHelper.handleOpen(url, sourceApplication: sourceApplication!, annotation: annotation) == false) { // perform handling of your app URL here } return true } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // ISDK method forward ISDKAppDelegateHelper.application(application, performFetchWithCompletionHandler:completionHandler) } func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { // ISDK method forward ISDKAppDelegateHelper.application(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler) } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // ISDK method forward ISDKAppDelegateHelper.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { // ISDK method forward ISDKAppDelegateHelper.application(application, didFailToRegisterForRemoteNotificationsWithError:error) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { // ISDK method forward if ISDKAppDelegateHelper.application(application, didReceiveRemoteNotification: userInfo) == false { // process your app's remote notification here } } func application(_ application: UIApplication, didReceive notification: UILocalNotification) { // ISDK method forward if (ISDKAppDelegateHelper.application(application, didReceive: notification) == false) { // process your app local notification here } } func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) { // ISDK method forward if (ISDKAppDelegateHelper.application(application, handleActionWithIdentifier: identifier, for: notification, completionHandler: completionHandler) == false) { // process your app local notification here // when done, call the OS completion block completionHandler(); } } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // forward to ISDK ISDKAppDelegateHelper.userNotificationCenter(center, didReceive: response) { (processed: Bool) -> Void in if !processed { // this notification is not ISDK, handle your app notification response here as needed } // when done, call the OS completion block completionHandler() } } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { ISDKAppDelegateHelper.userNotificationCenter(center, willPresent: notification) { (processed: Bool) -> Void in if !processed { // this notification is not ISDK // process your app notification here // and call the completion handler if needed .. } } } }
apache-2.0
1bcf2596e20bfabebcff8ca558bcdcad
38.140244
207
0.680947
6.686458
false
false
false
false
CharlinFeng/TextField-InputView
UITextField+InputView/OneModelVC.swift
1
1118
// // One+Original.swift // TextField+InputView // // Created by 成林 on 15/8/24. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit class CityModel: PickerDataModel { var spell: String! init(title: String, spell: String){ super.init(title: title, modelObj: nil) self.spell = spell } } class OneModelVC: UIViewController { @IBOutlet weak var tf: OneColTF! override func viewDidLoad() { super.viewDidLoad() let city1 = CityModel(title: "成都市", spell: "ChengDu") let city2 = CityModel(title: "南充市", spell: "NanChong") let city3 = CityModel(title: "南部县", spell: "NanBu") self.tf.emptyDataClickClosure = { print("正在模拟下载数据,请稍等5秒") } dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in /** 一句代码安装 */ self.tf.addOneColPickerViewWithModels([city1,city2,city3]) }) } }
mit
634c43d8d11bb69d4e6268aa0446946e
21.340426
131
0.57619
3.465347
false
false
false
false
IvanVorobei/RateApp
SPRateApp - project/SPRateApp/sparrow/extension/SPUIButtonExtenshion.swift
1
2952
// 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 extension UIButton { func showText(_ text: String, withComplection completion: (() -> Void)! = {}) { let baseText = self.titleLabel?.text ?? " " SPAnimation.animate(0.2, animations: { self.titleLabel?.alpha = 0 }, withComplection: { finished in self.setTitle(text, for: .normal) SPAnimation.animate(0.2, animations: { self.titleLabel?.alpha = 1 }, withComplection: { finished in SPAnimation.animate(0.2, animations: { self.titleLabel?.alpha = 0 }, delay: 0.35, withComplection: { finished in self.setTitle(baseText, for: .normal) SPAnimation.animate(0.2, animations: { self.titleLabel?.alpha = 1 }, withComplection: { finished in completion() }) }) }) }) } func setAnimatableText(_ text: String, withComplection completion: (() -> Void)! = {}) { SPAnimation.animate(0.2, animations: { self.titleLabel?.alpha = 0 }, withComplection: { finished in self.setTitle(text, for: .normal) SPAnimation.animate(0.2, animations: { self.titleLabel?.alpha = 1 }, withComplection: { finished in completion() }) }) } }
mit
328004bac2045980714c1692169cffe8
36.833333
92
0.545239
5.375228
false
false
false
false
22377832/ccyswift
LocationDemo/LocationDemo/ViewController.swift
1
4616
// // ViewController.swift // LocationDemo // // Created by sks on 17/2/9. // Copyright © 2017年 chen. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { var locationManager: CLLocationManager! var mapView: MKMapView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) mapView = MKMapView() } func setCenterOfMapToLocation(location: CLLocationCoordinate2D){ let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) } func addPanToMapView(){ if locationManager == nil { return } if locationManager.location == nil { return } let coordinate = locationManager.location?.coordinate if coordinate == nil { return } // let location = CLLocationCoordinate2D(latitude: 58.592737,longitude: 16.185898) let annotation = MyAnnotation(coordinate: coordinate!, title: "Title", subTitle: "Subtitle") mapView.addAnnotation(annotation) setCenterOfMapToLocation(location: coordinate!) } func displayAlertWithTitle(title: String, message: String){ let controller = UIAlertController(title: title, message: message, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(controller, animated: true, completion: nil) } func createLocationManager(startImmediately: Bool){ locationManager = CLLocationManager() if let manager = locationManager { print("Successfully created the loaction manager") manager.delegate = self if startImmediately{ manager.startUpdatingLocation() } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. mapView.mapType = .standard mapView.frame = view.frame mapView.delegate = self view.addSubview(mapView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if CLLocationManager.locationServicesEnabled(){ switch CLLocationManager.authorizationStatus() { case .authorizedWhenInUse, .authorizedAlways: createLocationManager(startImmediately: true) case .denied: displayAlertWithTitle(title: "Not Determined", message: "Location serviced are not allowed for this app") case .notDetermined: createLocationManager(startImmediately: true) if let manager = self.locationManager { manager.requestWhenInUseAuthorization() } case .restricted: displayAlertWithTitle(title: "Restricted", message: "Location serviced are not allowed for this app") } } else { print("Location services are not enabled") } addPanToMapView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("The authorization status of location services is changed to:") switch CLLocationManager.authorizationStatus() { case .authorizedAlways: print("authorizedAlways") case .authorizedWhenInUse: print("authorizedWhenInUse") case .denied: print("denied") case .notDetermined: print("notDetermined") case .restricted: print("restricted") } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Location manager failed with error = \(error)") } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations[0] print(location.coordinate.latitude) print(location.coordinate.longitude) } }
mit
0dfbc78d1a6dfdd07f9e36b49f4bfb04
30.59589
121
0.612617
5.883929
false
false
false
false
TCA-Team/iOS
TUM Campus App/CafeteriaConstants.swift
1
6536
// // CafeteriaConstants.swift // Campus // // Created by Mathias Quintero on 10/19/17. // Copyright © 2017 LS1 TUM. All rights reserved. // import Foundation enum CafeteriaConstants { static let priceList: [String : Price] = [ "Tagesgericht 1" : .service(student: 1.00, employee: 1.90, guest: 2.40), "Tagesgericht 2" : .service(student: 1.55, employee: 2.25, guest: 2.75), "Tagesgericht 3" : .service(student: 1.90, employee: 2.60, guest: 3.10), "Tagesgericht 4" : .service(student: 2.40, employee: 2.95, guest: 3.45), "Aktionsessen 1" : .service(student: 1.55, employee: 2.25, guest: 2.75), "Aktionsessen 2" : .service(student: 1.90, employee: 2.60, guest: 3.10), "Aktionsessen 3" : .service(student: 2.40, employee: 2.95, guest: 3.45), "Aktionsessen 4" : .service(student: 2.60, employee: 3.30, guest: 3.80), "Aktionsessen 5" : .service(student: 2.80, employee: 3.65, guest: 4.15), "Aktionsessen 6" : .service(student: 3.00, employee: 4.00, guest: 4.50), "Aktionsessen 7" : .service(student: 3.20, employee: 4.35, guest: 4.85), "Aktionsessen 8" : .service(student: 3.50, employee: 4.70, guest: 4.85), "Aktionsessen 9" : .service(student: 4.00, employee: 5.05, guest: 5.55), "Aktionsessen 10" : .service(student: 4.50, employee: 5.40, guest: 5.90), "Biogericht 1" : .service(student: 1.55, employee: 2.25, guest: 2.75), "Biogericht 2" : .service(student: 1.90, employee: 2.60, guest: 3.10), "Biogericht 3" : .service(student: 2.40, employee: 2.95, guest: 3.45), "Biogericht 4" : .service(student: 2.60, employee: 3.30, guest: 3.80), "Biogericht 5" : .service(student: 2.80, employee: 3.65, guest: 4.15), "Biogericht 6" : .service(student: 3.00, employee: 4.00, guest: 4.50), "Biogericht 7" : .service(student: 3.20, employee: 4.35, guest: 4.85), "Biogericht 8" : .service(student: 3.50, employee: 4.70, guest: 5.20), "Biogericht 9" : .service(student: 4.00, employee: 5.05, guest: 5.55), "Biogericht 10" : .service(student: 4.50, employee: 5.40, guest: 5.90), "Self-Service" : .selfService ] static let mensaAnnotationsEmoji = [ "v" : "🌱", "f" : "🥕", "Kr" : "🦀", "99" : "🍷", "S" : "🐖", "R" : "🐄", "Fi" : "🐟", "En" : "🥜", "Gl" : "🌾" ] static let mensaAnnotationsDescription = [ "1" : "mit Farbstoff", "2" : "mit Konservierungsstoff", "3" : "mit Antioxidationsmittel", "4" : "mit Geschmacksverstärker", "5" : "geschwefelt", "6" : "geschwärzt (Oliven)", "7" : "unbekannt", "8" : "mit Phosphat", "9" : "mit Süßungsmitteln", "10" : "enthält eine Phenylalaninquelle", "11" : "mit einer Zuckerart und Süßungsmitteln", "99" : "mit Alkohol", "f" : "fleischloses Gericht", "v" : "veganes Gericht", "GQB" : "Geprüfte Qualität - Bayern", "S" : "mit Schweinefleisch", "R" : "mit Rindfleisch", "K" : "mit Kalbfleisch", "MSC" : "Marine Stewardship Council", "Kn" : "Knoblauch", "13" : "kakaohaltige Fettglasur", "14" : "Gelatine", "Ei" : "Hühnerei", "En" : "Erdnuss", "Fi" : "Fisch", "Gl" : "Glutenhaltiges Getreide", "GlW" : "Weizen", "GlR" : "Roggen", "GlG" : "Gerste", "GlH" : "Hafer", "GlD" : "Dinkel", "Kr" : "Krebstiere", "Lu" : "Lupinen", "Mi" : "Milch und Laktose", "Sc" : "Schalenfrüchte", "ScM" : "Mandeln", "ScH" : "Haselnüsse", "ScW" : "Walnüsse", "ScC" : "Cashewnüssen", "ScP" : "Pistazien", "Se" : "Sesamsamen", "Sf" : "Senf", "Sl" : "Sellerie", "So" : "Soja", "Sw" : "Schwefeloxid und Sulfite", "Wt" : "Weichtiere" ] static func parseMensaMenu(_ name: String) -> MenuDetail { let pattern = "(?:(?<=\\((?:[[a-z][A-Z][0-9]]{1,3},)?)|(?<=,(?:[[a-z][A-Z][0-9]]{1,3},)?))([[a-z][A-Z][0-9]]{1,3})(?=(?:,[[a-z][A-Z][0-9]]{1,3})*\\))" var notMatchedEmoji: [String] = [] var matchedAnnotations: [String] = [] var matchedEmoji: [String] = [] var matchedDescriptions: [String] = [] let output = NSMutableString(string: name) var startPoint = output.length var withoutAnnotations = String(output) var withEmojiWithoutAnnotations = String(output) if let regex = try? NSRegularExpression(pattern: pattern, options: []) { let matches = regex.matches(in: output as String, options: [], range: NSMakeRange(0, output.length)) matchedAnnotations = matches.compactMap { output.substring(with: $0.range) } for match in matches { let matchedString = output.substring(with: match.range) startPoint = min(max(match.range.location - 1,0), startPoint) if let emoji = mensaAnnotationsEmoji[matchedString] { matchedEmoji.append(emoji) } else { notMatchedEmoji.append("(\(matchedString))") } if let matchedDescription = mensaAnnotationsDescription[matchedString] { matchedDescriptions.append(matchedDescription) } } regex.replaceMatches(in: output, options: [], range: NSMakeRange(0, output.length), withTemplate: "") let range = NSMakeRange(startPoint, output.length - startPoint) output.deleteCharacters(in: range) withoutAnnotations = String(output) matchedEmoji.forEach({output.append($0)}) withEmojiWithoutAnnotations = String(output) notMatchedEmoji.forEach({output.append($0)}) } return MenuDetail(name: String(output), nameWithoutAnnotations: withoutAnnotations, nameWithEmojiWithoutAnnotations: withEmojiWithoutAnnotations, annotations: matchedAnnotations, annotationDescriptions: matchedDescriptions) } }
gpl-3.0
9a0e90d238ec914014168bb46cfe6b4e
40.363057
158
0.528642
3.434162
false
false
false
false
ocrickard/Theodolite
Theodolite/UI/Text/TextKitAttributes.swift
1
1210
// // TextKitAttributes.swift // Theodolite // // Created by Oliver Rickard on 10/29/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import UIKit /** All NSObject values in this struct should be copied when passed into the TextComponent. */ public struct TextKitAttributes: Equatable, Hashable { /** The string to be drawn. CKTextKit will not augment this string with default colors, etc. so this must be complete. */ let attributedString: NSAttributedString /** The line-break mode to apply to the text. Since this also impacts how TextKit will attempt to truncate the text in your string, we only support NSLineBreakByWordWrapping and NSLineBreakByCharWrapping. */ let lineBreakMode: NSLineBreakMode /** The maximum number of lines to draw in the drawable region. Leave blank or set to 0 to define no maximum. */ let maximumNumberOfLines: Int init(attributedString: NSAttributedString, lineBreakMode: NSLineBreakMode = NSLineBreakMode.byTruncatingTail, maximumNumberOfLines: Int = 1) { self.attributedString = attributedString self.lineBreakMode = lineBreakMode self.maximumNumberOfLines = maximumNumberOfLines } };
mit
161ce3c6b8b07946a7c2a2a29ee3aa2c
32.583333
118
0.746071
4.816733
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/Other/ReconstructBinaryTree/ReconstructBinaryTreeNode.swift
1
797
// // Node.swift // WhiteBoardCodingChallenges // // Created by William Boles on 29/05/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit class ReconstructBinaryTreeNode: NSObject { // MARK: Properties var parent: ReconstructBinaryTreeNode? var left: ReconstructBinaryTreeNode? var right: ReconstructBinaryTreeNode? var value: Int // MARK: Init init(value: Int) { self.value = value super.init() } // MARK: Nodes func addNodeAsChild(node: ReconstructBinaryTreeNode) { if left == nil { left = node } else { right = node } node.parent = self } }
mit
3e760315f30e1762faea4a51ee62738a
15.93617
58
0.523869
4.975
false
false
false
false
xedin/swift
test/SILOptimizer/access_enforcement_noescape_error.swift
5
3061
// RUN: %target-swift-frontend -module-name access_enforcement_noescape -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s // REQUIRES: asserts // This is the subset of tests from access_enforcement_noescape.swift // that cause compile-time errors. All the tests are organized in one // place so it's easy to see that coverage of all the combinations of // access paterns is exhaustive. But the ones that cause compile time // errors are commented out in the original file and compiled here // instead with the '-verify' option. // Helper func doOne(_ f: () -> ()) { f() } // Helper func doOneInout(_: ()->(), _: inout Int) {} // Error: noescape read + write inout. func readWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ _ = x }, &x) } // Error: noescape read + write inout of an inout. func inoutReadWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ _ = x }, &x) } // Error: on noescape write + write inout. func writeWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ x = 42 }, &x) } // Error: on noescape write + write inout. func inoutWriteWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doOneInout({ x = 42 }, &x) } // Helper func doBlockInout(_: @convention(block) ()->(), _: inout Int) {} func readBlockWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [read] [static] // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doBlockInout({ _ = x }, &x) } // Test AccessSummaryAnalysis. // // The captured @inout_aliasable argument to `doOne` is re-partially applied, // then stored is a box before passing it to doBlockInout. func noEscapeBlock() { var x = 3 doOne { // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} doBlockInout({ _ = x }, &x) } }
apache-2.0
1a66ecb5d1e3dd7d2f4f1886e0eba815
37.2625
163
0.693891
3.82625
false
false
false
false
xedin/swift
test/Sanitizers/tsan-libdispatch.swift
1
1004
// RUN: %target-swiftc_driver %s -g -sanitize=thread %import-libdispatch -o %t_tsan-binary // RUN: %target-codesign %t_tsan-binary // RUN: not env %env-TSAN_OPTIONS=abort_on_error=0 %target-run %t_tsan-binary 2>&1 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: tsan_runtime // UNSUPPORTED: OS=tvos // FIXME: This should be covered by "tsan_runtime"; older versions of Apple OSs // don't support TSan. // UNSUPPORTED: remote_run // rdar://51730684 // REQUIRES: disable // Test ThreadSanitizer execution end-to-end with libdispatch. import Dispatch let sync1 = DispatchSemaphore(value: 0) let sync2 = DispatchSemaphore(value: 0) let finish = DispatchSemaphore(value: 0) let q = DispatchQueue(label: "q", attributes: .concurrent) var racy = 1 q.async { sync1.wait() sync2.signal() racy = 2 finish.signal() } q.async { sync1.signal() sync2.wait() racy = 3 finish.signal() } finish.wait() finish.wait() print("Done!") // CHECK: ThreadSanitizer: data race // CHECK: Done!
apache-2.0
b750d23ddcf6e30efac2eca8049ec2c8
20.826087
98
0.701195
3.157233
false
false
false
false
rafaelcpalmeida/UFP-iOS
UFP/UFP/Carthage/Checkouts/Alamofire/Tests/ResultTests.swift
12
13895
// // ResultTests.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @testable import Alamofire import Foundation import XCTest class ResultTestCase: BaseTestCase { let error = AFError.responseValidationFailed(reason: .unacceptableStatusCode(code: 404)) // MARK: - Is Success Tests func testThatIsSuccessPropertyReturnsTrueForSuccessCase() { // Given, When let result = Result<String>.success("success") // Then XCTAssertTrue(result.isSuccess, "result is success should be true for success case") } func testThatIsSuccessPropertyReturnsFalseForFailureCase() { // Given, When let result = Result<String>.failure(error) // Then XCTAssertFalse(result.isSuccess, "result is success should be true for failure case") } // MARK: - Is Failure Tests func testThatIsFailurePropertyReturnsFalseForSuccessCase() { // Given, When let result = Result<String>.success("success") // Then XCTAssertFalse(result.isFailure, "result is failure should be false for success case") } func testThatIsFailurePropertyReturnsTrueForFailureCase() { // Given, When let result = Result<String>.failure(error) // Then XCTAssertTrue(result.isFailure, "result is failure should be true for failure case") } // MARK: - Value Tests func testThatValuePropertyReturnsValueForSuccessCase() { // Given, When let result = Result<String>.success("success") // Then XCTAssertEqual(result.value ?? "", "success", "result value should match expected value") } func testThatValuePropertyReturnsNilForFailureCase() { // Given, When let result = Result<String>.failure(error) // Then XCTAssertNil(result.value, "result value should be nil for failure case") } // MARK: - Error Tests func testThatErrorPropertyReturnsNilForSuccessCase() { // Given, When let result = Result<String>.success("success") // Then XCTAssertTrue(result.error == nil, "result error should be nil for success case") } func testThatErrorPropertyReturnsErrorForFailureCase() { // Given, When let result = Result<String>.failure(error) // Then XCTAssertTrue(result.error != nil, "result error should not be nil for failure case") } // MARK: - Description Tests func testThatDescriptionStringMatchesExpectedValueForSuccessCase() { // Given, When let result = Result<String>.success("success") // Then XCTAssertEqual(result.description, "SUCCESS", "result description should match expected value for success case") } func testThatDescriptionStringMatchesExpectedValueForFailureCase() { // Given, When let result = Result<String>.failure(error) // Then XCTAssertEqual(result.description, "FAILURE", "result description should match expected value for failure case") } // MARK: - Debug Description Tests func testThatDebugDescriptionStringMatchesExpectedValueForSuccessCase() { // Given, When let result = Result<String>.success("success value") // Then XCTAssertEqual( result.debugDescription, "SUCCESS: success value", "result debug description should match expected value for success case" ) } func testThatDebugDescriptionStringMatchesExpectedValueForFailureCase() { // Given, When let result = Result<String>.failure(error) // Then XCTAssertEqual( result.debugDescription, "FAILURE: \(error)", "result debug description should match expected value for failure case" ) } // MARK: - Initializer Tests func testThatInitializerFromThrowingClosureStoresResultAsASuccess() { // Given let value = "success value" // When let result1 = Result(value: { value }) let result2 = Result { value } // Then for result in [result1, result2] { XCTAssertTrue(result.isSuccess) XCTAssertEqual(result.value, value) } } func testThatInitializerFromThrowingClosureCatchesErrorAsAFailure() { // Given struct ResultError: Error {} // When let result1 = Result(value: { throw ResultError() }) let result2 = Result { throw ResultError() } // Then for result in [result1, result2] { XCTAssertTrue(result.isFailure) XCTAssertTrue(result.error! is ResultError) } } // MARK: - Unwrap Tests func testThatUnwrapReturnsSuccessValue() { // Given let result = Result<String>.success("success value") // When let unwrappedValue = try? result.unwrap() // Then XCTAssertEqual(unwrappedValue, "success value") } func testThatUnwrapThrowsFailureError() { // Given struct ResultError: Error {} // When let result = Result<String>.failure(ResultError()) // Then do { _ = try result.unwrap() XCTFail("result unwrapping should throw the failure error") } catch { XCTAssertTrue(error is ResultError) } } // MARK: - Map Tests func testThatMapTransformsSuccessValue() { // Given let result = Result<String>.success("success value") // When let mappedResult = result.map { $0.characters.count } // Then XCTAssertEqual(mappedResult.value, 13) } func testThatMapPreservesFailureError() { // Given struct ResultError: Error {} let result = Result<String>.failure(ResultError()) // When let mappedResult = result.map { $0.characters.count } // Then if let error = mappedResult.error { XCTAssertTrue(error is ResultError) } else { XCTFail("map should preserve the failure error") } } // MARK: - FlatMap Tests func testThatFlatMapTransformsSuccessValue() { // Given let result = Result<String>.success("success value") // When let mappedResult = result.flatMap { $0.characters.count } // Then XCTAssertEqual(mappedResult.value, 13) } func testThatFlatMapCatchesTransformationError() { // Given struct TransformError: Error {} let result = Result<String>.success("success value") // When let mappedResult = result.flatMap { _ in throw TransformError() } // Then if let error = mappedResult.error { XCTAssertTrue(error is TransformError) } else { XCTFail("flatMap should catch the transformation error") } } func testThatFlatMapPreservesFailureError() { // Given struct ResultError: Error {} struct TransformError: Error {} let result = Result<String>.failure(ResultError()) // When let mappedResult = result.flatMap { _ in throw TransformError() } // Then if let error = mappedResult.error { XCTAssertTrue(error is ResultError) } else { XCTFail("flatMap should preserve the failure error") } } // MARK: - Error Mapping Tests func testMapErrorTransformsErrorValue() { // Given struct ResultError: Error {} struct OtherError: Error { let error: Error } let result: Result<String> = .failure(ResultError()) // When let mappedResult = result.mapError { OtherError(error: $0) } // Then if let error = mappedResult.error { XCTAssertTrue(error is OtherError) } else { XCTFail("mapError should transform error value") } } func testMapErrorPreservesSuccessError() { // Given struct ResultError: Error {} struct OtherError: Error { let error: Error } let result: Result<String> = .success("success") // When let mappedResult = result.mapError { OtherError(error: $0) } // Then XCTAssertEqual(mappedResult.value, "success") } func testFlatMapErrorTransformsErrorValue() { // Given struct ResultError: Error {} struct OtherError: Error { let error: Error } let result: Result<String> = .failure(ResultError()) // When let mappedResult = result.flatMapError { OtherError(error: $0) } // Then if let error = mappedResult.error { XCTAssertTrue(error is OtherError) } else { XCTFail("mapError should transform error value") } } func testFlatMapErrorCapturesThrownError() { // Given struct ResultError: Error {} struct OtherError: Error { let error: Error init(error: Error) throws { throw ThrownError() } } struct ThrownError: Error {} let result: Result<String> = .failure(ResultError()) // When let mappedResult = result.flatMapError { try OtherError(error: $0) } // Then if let error = mappedResult.error { XCTAssertTrue(error is ThrownError) } else { XCTFail("mapError should capture thrown error value") } } // MARK: - With Value or Error Tests func testWithValueExecutesWhenSuccess() { // Given let result: Result<String> = .success("success") var string = "failure" // When result.withValue { string = $0 } // Then XCTAssertEqual(string, "success") } func testWithValueDoesNotExecutesWhenFailure() { // Given struct ResultError: Error {} let result: Result<String> = .failure(ResultError()) var string = "failure" // When result.withValue { string = $0 } // Then XCTAssertEqual(string, "failure") } func testWithErrorExecutesWhenFailure() { // Given struct ResultError: Error {} let result: Result<String> = .failure(ResultError()) var string = "success" // When result.withError { string = "\(type(of: $0))" } // Then #if swift(>=3.2) XCTAssertEqual(string, "ResultError #1") #else XCTAssertEqual(string, "(ResultError #1)") #endif } func testWithErrorDoesNotExecuteWhenSuccess() { // Given let result: Result<String> = .success("success") var string = "success" // When result.withError { string = "\(type(of: $0))" } // Then XCTAssertEqual(string, "success") } // MARK: - If Success or Failure Tests func testIfSuccessExecutesWhenSuccess() { // Given let result: Result<String> = .success("success") var string = "failure" // When result.ifSuccess { string = "success" } // Then XCTAssertEqual(string, "success") } func testIfSuccessDoesNotExecutesWhenFailure() { // Given struct ResultError: Error {} let result: Result<String> = .failure(ResultError()) var string = "failure" // When result.ifSuccess { string = "success" } // Then XCTAssertEqual(string, "failure") } func testIfFailureExecutesWhenFailure() { // Given struct ResultError: Error {} let result: Result<String> = .failure(ResultError()) var string = "success" // When result.ifFailure { string = "failure" } // Then XCTAssertEqual(string, "failure") } func testIfFailureDoesNotExecuteWhenSuccess() { // Given let result: Result<String> = .success("success") var string = "success" // When result.ifFailure { string = "failure" } // Then XCTAssertEqual(string, "success") } // MARK: - Functional Chaining Tests func testFunctionalMethodsCanBeChained() { // Given struct ResultError: Error {} let result: Result<String> = .success("first") var string = "first" var success = false // When let endResult = result .map { _ in "second" } .flatMap { _ in "third" } .withValue { if $0 == "third" { string = "fourth" } } .ifSuccess { success = true } // Then XCTAssertEqual(endResult.value, "third") XCTAssertEqual(string, "fourth") XCTAssertTrue(success) } }
mit
9a0a1f83eb11b86672296857b3aa9ec0
27.768116
120
0.607197
4.971377
false
true
false
false
Brightify/ReactantUI
Sources/reactant-ui/XSD/XSDComplexType.swift
1
1287
// // XSDComplexType.swift // ReactantUIPackageDescription // // Created by Matouš Hýbl on 21/03/2018. // import Foundation import Tokenizer struct XSDComplexChoiceType { let name: String var elements: Set<XSDElement> } extension XSDComplexChoiceType: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(name) } static func ==(lhs: XSDComplexChoiceType, rhs: XSDComplexChoiceType) -> Bool { return lhs.name == rhs.name } } extension XSDComplexChoiceType: XMLElementSerializable { func serialize(context: DataContext) -> XMLSerializableElement { let elements = self.elements.map { $0.serialize(context: context) } let choice = XMLSerializableElement(name: "xs:choice", attributes: [XMLSerializableAttribute(name: "maxOccurs", value: "unbounded"), XMLSerializableAttribute(name: "minOccurs", value: "0")], children: elements) return XMLSerializableElement(name: "xs:complexType", attributes: [XMLSerializableAttribute(name: "name", value: name)], children: [choice]) } }
mit
0a5b5ed8d075fa1e7988f6a965e0f548
31.948718
121
0.59144
5.079051
false
false
false
false
publickanai/PLMScrollMenu
Example/PLScrollMenuBar.swift
1
28945
// // PLMScrollMenuBar.swift // PLMScrollMenu // // Created by Tatsuhiro Kanai on 2016/03/14. // Copyright © 2016年 Adways Inc. All rights reserved. // import UIKit // MARK: - ScrollView /** MenuBarScrollView */ public class PLMScrollMenuBarScrollView:UIScrollView { // タッチ領域の拡張 override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { //print("PLMScrollMenuBarScrollView hitTestwithEvent :\(event) \(event?.type) \(event?.subtype)") if let view : UIView = super.hitTest(point, withEvent: event) { return view }else{ var view:UIView? = nil for subview in self.subviews { let covertedPoint = self.convertPoint(point, toView: subview) if CGRectContainsPoint(subview.bounds, covertedPoint) { view = subview } } return view } } } // MARK: - MenuBar /** MenuBar Style */ public enum PLMScrollMenuBarStyle: UInt { case Normal case InfinitePaging } /** MenuBar Direction */ public enum PLMScrollMenuBarDirection: Int { case None case Left case Right } /** MenuBar Protocol */ protocol PLMScrollMenuBarDelegate { func menuBar(menuBar:PLMScrollMenuBar, didSelectItem:PLMScrollMenuBarItem , direction: PLMScrollMenuBarDirection ) } /** MenuBar */ public class PLMScrollMenuBar: UIView , UIScrollViewDelegate { /** Constant */ static let kPLMScrollMenuBarDefaultBarHeight:CGFloat = 36.0 /** Delegate */ internal var delegate : PLMScrollMenuBarDelegate? /** UI */ private var _scrollView : PLMScrollMenuBarScrollView! private var _indicatorView : UIView! private var _border : UIView! private var _bg : UIView! /** MenuBar Style */ private var _style:PLMScrollMenuBarStyle = PLMScrollMenuBarStyle.Normal public var style:PLMScrollMenuBarStyle { set { self.setStyle(newValue)} get { return _style } } internal func setStyle(style:PLMScrollMenuBarStyle) { _style = style if let items = _items where items.count > 0 { self.setItems(items , animated: true) } } /** MenuBar ItemInsets */ private var _itemInsets : UIEdgeInsets = UIEdgeInsetsZero public var itemInsets : UIEdgeInsets { set{ _itemInsets = newValue // reset menubar if let items = _items where items.count > 0{ // Clear all of menu items for view in _scrollView.subviews { if view.isKindOfClass(PLMScrollMenuBarButton) { view.removeFromSuperview() } } // Apply Style if( _style == PLMScrollMenuBarStyle.Normal ) { self.setupMenuBarButtonsForNormalStyle(false) } else if( _style == PLMScrollMenuBarStyle.InfinitePaging ){ self.setupMenuBarButtonsForInfinitePagingStyle(false) } } } get{ return _itemInsets } } /** flags */ private var _showsIndicator:Bool! private var _showsSeparatorLine:Bool! /** BarHeight */ private var _barHeight : CGFloat? /** Indicator Color */ private var _indicatorColor:UIColor! public func setIndicatorColor(color: UIColor) { _indicatorColor = color if let indicator = _indicatorView { indicator.backgroundColor = _indicatorColor } } /** Border Color */ private var _borderColor:UIColor = UIColor(white: 0.698, alpha: 1.000) public var setBorderColor:UIColor { set{_borderColor = newValue if let border = _border{ border.backgroundColor = _borderColor } } get{ return _borderColor } } /** Selected Item */ private var _selectedItem: PLMScrollMenuBarItem? public var selectedItem:PLMScrollMenuBarItem? { set { self.setSelectedItem(newValue!, animated: true) } get { return _selectedItem } } public func setSelectedItem(item : PLMScrollMenuBarItem ,animated:Bool) { //print("setSelectedItem") //print("setSelectedItem _scrollView.contentOffset:\(_scrollView.contentOffset)") if ( _selectedItem == item ) { return } self.userInteractionEnabled = false if _selectedItem != nil { _selectedItem!.selected = false } var direction : PLMScrollMenuBarDirection = PLMScrollMenuBarDirection.None // InfinitePaging Direction if(_style == PLMScrollMenuBarStyle.InfinitePaging) { var lastIndex = -1 if let selectedItem = _selectedItem { lastIndex = _items!.indexOfObject(selectedItem) } let nextIndex = _items!.indexOfObject(item) if nextIndex - lastIndex > 0 { if (nextIndex - lastIndex) < _items!.count/2 { direction = PLMScrollMenuBarDirection.Right } else { direction = PLMScrollMenuBarDirection.Left } } else { if ( (lastIndex - nextIndex) < _items!.count/2 ) { direction = PLMScrollMenuBarDirection.Left } else { direction = PLMScrollMenuBarDirection.Right } } } // New Position _selectedItem = item _selectedItem!.selected = true // Selected item want to be displayed to center as possible. var offset : CGPoint = CGPointZero var newPosition : CGPoint = CGPointZero if _style == PLMScrollMenuBarStyle.Normal { if _selectedItem!.button().center.x > _scrollView!.bounds.size.width*0.5 && NSInteger(_scrollView.contentSize.width - _selectedItem!.button().center.x) >= NSInteger(_scrollView.bounds.size.width*0.5) { offset = CGPointMake( _selectedItem!.button().center.x - _scrollView!.frame.size.width * 0.5 , 0 ) } else if ( _selectedItem!.button().center.x < _scrollView.bounds.size.width*0.5) { offset = CGPointMake(0, 0) } else if ( NSInteger( _scrollView.contentSize.width - _selectedItem!.button().center.x ) < NSInteger(_scrollView.bounds.size.width*0.5)) { offset = CGPointMake(_scrollView.contentSize.width-_scrollView.bounds.size.width, 0) } _scrollView.setContentOffset(offset, animated: animated) newPosition = _scrollView.convertPoint(CGPointZero, fromCoordinateSpace: _selectedItem!.button()) } else if _style == PLMScrollMenuBarStyle.InfinitePaging { let margin : CGFloat = (_infinitePagingBoundsWidth! - _selectedItem!.width) * 0.5 offset = CGPointMake(_selectedItem!.button().frame.origin.x - margin, 0.0) newPosition.x = _infinitePagingOffsetX! + itemInsets.left } // Indicator set NewPosition if(_indicatorView.frame.origin.x == 0.0 && _indicatorView.frame.size.width == 0.0) { var f = _indicatorView.frame f.origin.x = newPosition.x - 3 f.size.width = _selectedItem!.button().frame.size.width + 6 _indicatorView.frame = f //print("setSelectedItem 0 indicatorView.frame: \(_indicatorView.frame)") } else if(_style == PLMScrollMenuBarStyle.Normal) { //print("setSelectedItem Normal") var dur:NSTimeInterval = NSTimeInterval(fabs(newPosition.x - _indicatorView!.frame.origin.x)) / 160.0 * 0.4 * 0.8 if(dur < 0.38){ dur = 0.1; } else if (dur > 0.6){ dur = 0.2; } UIView.animateWithDuration(dur, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self] () -> Void in if let weakSelf = self { var f : CGRect = weakSelf._indicatorView!.frame; f.origin.x = newPosition.x - 3; f.size.width = weakSelf._selectedItem!.button().frame.size.width + 6; weakSelf._indicatorView!.frame = f; } }, completion: { [weak self] (finished) -> Void in if let weakSelf = self { weakSelf.userInteractionEnabled = true; weakSelf.delegate!.menuBar(weakSelf, didSelectItem: weakSelf._selectedItem! , direction: direction) } }) }else if(_style == PLMScrollMenuBarStyle.InfinitePaging) { // Move Indicator //print("setSelectedItem InfinitePaging") let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue(), { self.reorderItemsForInfinitePaging() // Indicator Position var f : CGRect = self._indicatorView.frame f.origin.x = self._selectedItem!.button().frame.origin.x - 3 f.size.width = self._selectedItem!.button().frame.size.width + 6 self._indicatorView.frame = f self.userInteractionEnabled = true // PLMScrollMenuBar Delegate Method if let delegate = self.delegate { delegate.menuBar(self, didSelectItem: self._selectedItem! , direction: direction) } self._infinitePagingIsTappedItem = false }) } } /** OffsetX for ScrollView */ public var scrollOffsetX : CGFloat! { get{ if let v = _scrollView { return v.contentOffset.x } return nil } } /** Scroll with Ratio */ public func scrollByRatio(ratio:CGFloat, from:CGFloat) { //print("scrollByRatio ratio:\(ratio) from:\(from)") if _style == PLMScrollMenuBarStyle.Normal { let index = _items!.indexOfObject(_selectedItem!) let ignoreCount = NSInteger(_scrollView.frame.size.width*0.5/(_scrollView.contentSize.width/CGFloat(_items!.count))) for(var i = 0; i < ignoreCount; i++) { if (index == i) { return } else if (index == _items!.count-1-i) { return } } if(index == ignoreCount && ratio < 0.0) { return } else if(index == _items!.count-1-ignoreCount && ratio > 0.0) { return } } _scrollView.contentOffset = CGPointMake(from + _scrollView.contentSize.width/CGFloat(_items!.count) * ratio, 0) } /** items */ private var _items : NSArray! public var items: NSArray! { set{ self.setItems(newValue) } get{ return _items} } // setItems public func setItems(items:NSArray! , animated:Bool = false) { //print("k1 \(items) ") _selectedItem = nil //print("k2 \(items) ") _items = items //print("k3 \(_items) ") // Clear all of menu items for view in _scrollView.subviews { if view.isKindOfClass(PLMScrollMenuBarButton) { view.removeFromSuperview() } } //print("k3 \(_items) ") // Abort if let itm = items where itm.count == 0 { return } //print("k4 _style:\(_style) \(_items) ") // Apply Style if( _style == PLMScrollMenuBarStyle.Normal ) { self.setupMenuBarButtonsForNormalStyle(animated) } else if( _style == PLMScrollMenuBarStyle.InfinitePaging ) { self.setupMenuBarButtonsForInfinitePagingStyle(animated) } } /** Infinite Paging */ private var _infinitePagingBoundsWidth : CGFloat? private var _infinitePagingOffsetX : CGFloat? private var _infinitePagingOrder : NSMutableArray? private var _infinitePagingIsTappedItem : Bool? private var _infinitePagingLastContentOffsetX : CGFloat? // MARK: - // MARK: - hitTest override public func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { if(!self.userInteractionEnabled) { return nil } // Expands ScrollView's tachable area var view : UIView? = _scrollView.hitTest( self.convertPoint(point, toView: _scrollView) , withEvent: event ) if view == nil && CGRectContainsPoint(self.bounds,point) { view = self._scrollView } return view } // MARK: - // MARK: - init override init (frame : CGRect) { super.init(frame : frame) self.initialize() } convenience init () { self.init(frame:CGRectZero) } // from nib required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } // initialize private func initialize() { // flag _showsIndicator = true _showsSeparatorLine = true // _items = NSArray() _barHeight = PLMScrollMenuBar.kPLMScrollMenuBarDefaultBarHeight; _indicatorColor = UIColor(red: 0.988, green: 0.224, blue: 0.129, alpha: 1.000) // BG self.backgroundColor = UIColor.clearColor() // ScrollView _scrollView = PLMScrollMenuBarScrollView(frame: self.bounds ) _scrollView.showsVerticalScrollIndicator = false _scrollView.showsHorizontalScrollIndicator = false _scrollView.contentOffset = CGPointZero _scrollView.scrollsToTop = false self.addSubview(_scrollView) // Indicator let indicator = UIView(frame: CGRectMake(0, self.bounds.size.height - 4, 0, 4) ) _indicatorView = indicator; _indicatorView.backgroundColor = _indicatorColor _scrollView.addSubview(_indicatorView) // _border = UIView(frame:CGRectMake(0, self.bounds.size.height - 0.25, self.bounds.size.width, 0.25) ) _border.backgroundColor = _borderColor self.addSubview(_border) } // MARK: - // MARK: - Setup /** NormalStyle */ private func setupMenuBarButtonsForNormalStyle( animated:Bool ) { print("Setup as Normal") // scroll view var f : CGRect _scrollView.pagingEnabled = false _scrollView.decelerationRate = UIScrollViewDecelerationRateNormal _scrollView.clipsToBounds = true _scrollView.delegate = nil // setup menu button frame var offset : CGFloat = itemInsets.left var c : Int = 0 for item in _items! as! [PLMScrollMenuBarItem] { let b : PLMScrollMenuBarButton = item.button() f = CGRectMake(offset, itemInsets.top, item.width, _scrollView.bounds.size.height - itemInsets.top + itemInsets.bottom ) offset += f.size.width + itemInsets.right + itemInsets.left b.frame = f b.alpha = 0.0 b.tag = c c++ _scrollView.addSubview(b) b.addTarget(self, action: "didTapMenuButton:", forControlEvents: UIControlEvents.TouchUpInside) } // content size var contentWidth = offset - itemInsets.left // case contentsWidth is smaller than width if contentWidth < _scrollView.bounds.size.width { // Align items to center if number of items is less // (_scrollView.bounds.size.width - contentWidth) == Insets.left + Insets.right offset = (_scrollView.bounds.size.width - contentWidth) * 0.5 contentWidth = _scrollView.bounds.size.width // Align items for v in _scrollView.subviews { if v.isKindOfClass(PLMScrollMenuBarButton) { f = v.frame f.origin.x += offset // adding inset.left v.frame = f } } } // Set scrollView's contentsSize _scrollView.contentSize = CGSizeMake( contentWidth , _scrollView.bounds.size.height ) // Animate to Display Button Items if !animated { //Without Animate for v in _scrollView.subviews { if v.isKindOfClass(PLMScrollMenuBarButton) { v.alpha = 1.0 } } } else { // With Animate var i = 0 for v in _scrollView.subviews { if v.isKindOfClass(PLMScrollMenuBarButton) { self.animateButton(v, atIndex: i) i++ } } } // SelectedItem if _selectedItem == nil && _items!.count > 0 { self.selectedItem = _items![0] as? PLMScrollMenuBarItem } } /** InfinitePagingStyle */ private func setupMenuBarButtonsForInfinitePagingStyle( animated:Bool ) { //print("Setup as InfinitePaging") var f :CGRect _scrollView.pagingEnabled = true _scrollView.decelerationRate = UIScrollViewDecelerationRateFast _scrollView.clipsToBounds = false _scrollView.delegate = self // Get max width var maxWidth : CGFloat = 0.0 var totalWidth : CGFloat = 0.0 for item in _items as! [PLMScrollMenuBarItem] { if maxWidth < item.width { maxWidth = item.width } totalWidth += item.width + itemInsets.right + itemInsets.left //print("setup InfinitePaging item.width: \(item.width) totalWidth:\(totalWidth) ") } //maxWidth = maxWidth + 0.5 // comment off this line //print("setup InfinitePaging maxWidth:\(maxWidth) totalWidth:\(totalWidth) _scrollView.bounds.size.width:\(_scrollView.bounds.size.width)") // Display normal style if can show all items if totalWidth < _scrollView.bounds.size.width { //print("Can not infinite paging, because the number of items is too small") _style = PLMScrollMenuBarStyle.Normal self.setupMenuBarButtonsForNormalStyle(animated) return } // Set up menu button _infinitePagingOrder = NSMutableArray() var offset:CGFloat = itemInsets.left let totalCount = _items!.count let halfCount = totalCount/2 let evenFactor = totalCount%2 > 0 ? 0 : 1 var firstItemOriginX : CGFloat = 0.0 // _items[0] In Center ex) -3 -2 -1 0 1 2 3 for( var i = -( halfCount - evenFactor); i <= halfCount ; i++ ) { // CountIndex to Real Index of Array let index = (totalCount + i) % totalCount let item : PLMScrollMenuBarItem = _items![index] as! PLMScrollMenuBarItem if let b : PLMScrollMenuBarButton = item.button() { let diffWidth = maxWidth - item.width //print("create button index \(index)\toffset:\(offset)\tbuttonX:\(offset + diffWidth*0.5)\tmaxWidth:\(maxWidth)\titem.width:\(item.width)\tdiffWidth:\(diffWidth)\tdiffWidth*0.5:\(diffWidth*0.5)") f = CGRectMake(offset + diffWidth*0.5, itemInsets.top, item.width, _scrollView.bounds.size.height - itemInsets.top + itemInsets.bottom) offset += diffWidth*0.5 + f.size.width + diffWidth*0.5 + _itemInsets.right + _itemInsets.left b.frame = f b.alpha = 0.0 _scrollView.addSubview(b) b.addTarget(self, action: "didTapMenuButton:", forControlEvents: UIControlEvents.TouchUpInside) if index == 0 { // OffsetX for Center Item firstItemOriginX = f.origin.x - (itemInsets.left + diffWidth*0.5) } _infinitePagingOrder?.addObject(NSValue(nonretainedObject: item)) } } // BoundsWidth for a Menu Button _infinitePagingBoundsWidth = itemInsets.left + maxWidth + itemInsets.right // Scroll view size same as one button bounds _scrollView.frame = CGRectMake( (_scrollView.frame.size.width - _infinitePagingBoundsWidth!)*0.5, 0, _infinitePagingBoundsWidth!, _scrollView.frame.size.height) let contentWidth : CGFloat = offset - itemInsets.left // remove _itemInsets.left of Next Item _scrollView.contentSize = CGSizeMake(contentWidth,_scrollView.bounds.size.height) _scrollView.contentOffset = CGPointMake(firstItemOriginX, 0) // set value _infinitePagingOffsetX = firstItemOriginX _infinitePagingLastContentOffsetX = firstItemOriginX // remove this line //_scrollView.setNeedsLayout() // Display Buttons if animated { // with Animate for (var i = 0; i <= halfCount ; i++ ) { let index1 = (totalCount + i) % totalCount let item1 : PLMScrollMenuBarItem = _items![index1] as! PLMScrollMenuBarItem if let view1 : PLMScrollMenuBarButton = item1.button() where view1.isKindOfClass(PLMScrollMenuBarButton) { self.animateButton(view1, atIndex: i) } let index2 : NSInteger = (totalCount-1) % totalCount if index1 == index2 { continue } let item2 : PLMScrollMenuBarItem = items![index2] as! PLMScrollMenuBarItem let view2 : PLMScrollMenuBarButton = item2.button() if view2.isKindOfClass(PLMScrollMenuBarButton) { self.animateButton(view2, atIndex: i) } } } else { // Without Animate for view in (_scrollView.subviews) { if view.isKindOfClass(PLMScrollMenuBarButton) { view.alpha = 1.0; } } } // set SelectedItem if _selectedItem != nil { dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in if let weakSelf = self { //print("setupMenuBarButtonsForInfinitePagingStyle - > setSelectedItem ") weakSelf.setSelectedItem(weakSelf._items[0] as! PLMScrollMenuBarItem ,animated: false) } }) } } // MARK: - // MARK: - ReOrder Button's Order private func reorderItemsForInfinitePaging() { //print("ReOrder Button's Order") let diffX : CGFloat = _scrollView.contentOffset.x - _infinitePagingOffsetX! let moveCount : NSInteger = NSInteger( fabs(diffX)/_infinitePagingBoundsWidth! ) if( diffX > 0 ) { //Right Item if (_infinitePagingOrder!.count > 0 ) { for(var i = 0 ; i < moveCount ; i++ ) { let firstObj = _infinitePagingOrder![0] _infinitePagingOrder!.addObject(firstObj) _infinitePagingOrder!.removeObjectAtIndex(0) } } } else if (diffX < 0 ) { //Left Item if (_infinitePagingOrder!.count > 0 ) { for(var i = 0 ; i < moveCount ; i++ ) { let lastObj = _infinitePagingOrder!.lastObject _infinitePagingOrder!.insertObject(lastObj!, atIndex: 0) _infinitePagingOrder!.removeObjectAtIndex( _infinitePagingOrder!.count - 1 ) } } } var index : NSInteger = 0 var f : CGRect for val in _infinitePagingOrder! { let item = val.nonretainedObjectValue as! PLMScrollMenuBarItem f = item.button().frame f.origin.x = CGFloat(index) * _infinitePagingBoundsWidth! + itemInsets.left item.button().frame = f index++ } // Content Offset _scrollView.contentOffset = CGPointMake(_selectedItem!.button().frame.origin.x - (_infinitePagingBoundsWidth! - _selectedItem!.width) * 0.5, 0) } // MARK: - // MARK: - Animate with UIView and Button Index private func animateButton(view:UIView, atIndex index : NSInteger ) { view.transform = CGAffineTransformMakeScale(1.4, 1.4) UIView.animateWithDuration(0.24, delay:0.06 + 0.10 * Double(index), options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in view.alpha = 1 view.transform = CGAffineTransformMakeScale(1.0, 1.0) }) { (finished) -> Void in //print("animate Button finished:\(finished)") } } // MARK: - // MARK: - Button Tapped private func didTapMenuButton(sender:AnyObject) { // Set SelectedItem for item in _items! as! [PLMScrollMenuBarItem] { if sender as! PLMScrollMenuBarButton == item.button() && item != _selectedItem { _infinitePagingIsTappedItem = true self.selectedItem = item break } } } // MARK: - // MARK: - UIScrollView Delegate Method For InfinitePaging @objc public func scrollViewDidEndDecelerating( scrollView: UIScrollView ) { if(_infinitePagingLastContentOffsetX == scrollView.contentOffset.x) { return } if _infinitePagingIsTappedItem == nil || _infinitePagingIsTappedItem! == false { // Reset items Order self.reorderItemsForInfinitePaging() // Reset ContentOffset _scrollView.contentOffset = CGPointMake(_infinitePagingLastContentOffsetX!, 0) var index : NSInteger = 0; var selectedItem: PLMScrollMenuBarItem? = nil for val in _infinitePagingOrder! { let item = val.nonretainedObjectValue as! PLMScrollMenuBarItem if( NSInteger(item.button().frame.origin.x) == NSInteger(_infinitePagingOffsetX! + itemInsets.left) ) { selectedItem = item } index++ } if let selectedItem = selectedItem where selectedItem != _selectedItem { //print("scrollViewDidEndDecelerating -> _selectedItem") self.setSelectedItem(selectedItem, animated: true) } } _infinitePagingLastContentOffsetX = scrollView.contentOffset.x; } }
mit
be772dcbdea9adc7360ae5567a12eba6
33.313167
212
0.529835
5.431093
false
false
false
false
practicalswift/swift
test/Parse/operator_decl.swift
14
3609
// RUN: %target-typecheck-verify-swift prefix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{20-23=}} postfix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{21-24=}} infix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{19-22=}} infix operator +++* { // expected-error {{operator should no longer be declared with body; use a precedence group instead}} {{none}} associativity right } infix operator +++*+ : A { } // expected-error {{operator should no longer be declared with body}} {{25-29=}} prefix operator +++** : A { } // expected-error@-1 {{only infix operators may declare a precedence}} {{23-27=}} // expected-error@-2 {{operator should no longer be declared with body}} {{26-30=}} prefix operator ++*++ : A // expected-error@-1 {{only infix operators may declare a precedence}} {{23-26=}} postfix operator ++*+* : A { } // expected-error@-1 {{only infix operators may declare a precedence}} {{24-28=}} // expected-error@-2 {{operator should no longer be declared with body}} {{27-31=}} postfix operator ++**+ : A // expected-error@-1 {{only infix operators may declare a precedence}} {{24-27=}} operator ++*** : A // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} operator +*+++ { } // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} // expected-error@-2 {{operator should no longer be declared with body}} {{15-19=}} operator +*++* : A { } // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} // expected-error@-2 {{operator should no longer be declared with body}} {{19-23=}} prefix operator // expected-error {{expected operator name in operator declaration}} ; prefix operator %%+ prefix operator ?? postfix operator ?? // expected-error {{expected operator name in operator declaration}} prefix operator !! postfix operator !! // expected-error {{expected operator name in operator declaration}} infix operator +++= infix operator *** : A infix operator --- : ; precedencegroup { // expected-error {{expected identifier after 'precedencegroup'}} associativity: right } precedencegroup A { associativity right // expected-error {{expected colon after attribute name in precedence group}} } precedencegroup B { precedence 123 // expected-error {{'precedence' is not a valid precedence group attribute}} } precedencegroup C { associativity: sinister // expected-error {{expected 'none', 'left', or 'right' after 'associativity'}} } precedencegroup D { assignment: no // expected-error {{expected 'true' or 'false' after 'assignment'}} } precedencegroup E { higherThan: } // expected-error {{expected name of related precedence group after 'higherThan'}} precedencegroup F { higherThan: A, B, C } precedencegroup BangBangBang { associativity: none associativity: left // expected-error{{'associativity' attribute for precedence group declared multiple times}} } precedencegroup CaretCaretCaret { assignment: true assignment: false // expected-error{{'assignment' attribute for precedence group declared multiple times}} } class Foo { infix operator ||| // expected-error{{'operator' may only be declared at file scope}} } infix operator **<< : UndeclaredPrecedenceGroup // expected-error@-1 {{unknown precedence group 'UndeclaredPrecedenceGroup'}} protocol Proto {} infix operator *<*< : F, Proto // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{expected expression}}
apache-2.0
ce658074f61e676bbbc520f38ac71eab
36.989474
132
0.705181
4.225995
false
false
false
false
imclean/JLDishWashers
JLDishwasher/Media.swift
1
1783
// // Media.swift // JLDishwasher // // Created by Iain McLean on 21/12/2016. // Copyright © 2016 Iain McLean. All rights reserved. // import Foundation public class Media { public var images : Images? public var threeSixtyImages : ThreeSixtyimages? /** Returns an array of models based on given dictionary. Sample usage: let media_list = Media.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of Media Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [Media] { var models:[Media] = [] for item in array { models.append(Media(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let media = Media(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: Media Instance. */ required public init?(dictionary: NSDictionary) { if (dictionary["images"] != nil) { images = Images(dictionary: dictionary["images"] as! NSDictionary) } if (dictionary["360images"] != nil) { threeSixtyImages = ThreeSixtyimages(dictionary: dictionary["360images"] as! NSDictionary) } } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.images?.dictionaryRepresentation(), forKey: "images") dictionary.setValue(self.threeSixtyImages?.dictionaryRepresentation(), forKey: "360images") return dictionary } }
gpl-3.0
4398e4051e0e9877639e505a821b7488
26.415385
131
0.666667
4.61658
false
false
false
false
PekanMmd/Pokemon-XD-Code
Objects/struct tables/TypesTable.swift
1
1572
// // TypesTable.swift // GoD Tool // // Created by Stars Momodu on 26/03/2021. // import Foundation #if GAME_XD let typeMatchups = (0 ..< 18).map { (i) -> GoDStructProperties in return .short(name: "Effectiveness against Type \(i)", description: "", type: .typeEffectiveness) } let typeStruct = GoDStruct(name: "Type", format: [ .byte(name: "Category", description: "Physical or Special", type: .moveCategory), .short(name: "Large Icon Image ID", description: "", type: .indexOfEntryInTable(table: texturesTable, nameProperty: nil)), .short(name: "Small Icon Image ID", description: "", type: .indexOfEntryInTable(table: texturesTable, nameProperty: nil)), .word(name: "Name ID", description: "", type: .msgID(file: .common_rel)) ] + typeMatchups) let typesTable = CommonStructTable(index: .Types, properties: typeStruct, documentByIndex: false) #else let typeMatchups = (0 ..< 18).map { (i) -> GoDStructProperties in return .short(name: "Effectiveness against Type \(i)", description: "", type: .typeEffectiveness) } let typeStruct = GoDStruct(name: "Type", format: [ .byte(name: "Category", description: "Physical or Special", type: .moveCategory), .short(name: "Icon Image ID", description: "", type: .indexOfEntryInTable(table: texturesTable, nameProperty: nil)), .word(name: "Name ID", description: "", type: .msgID(file: .common_rel)) ] + typeMatchups) let typesTable = GoDStructTable(file: .dol, properties: typeStruct, documentByIndex: false) { (_) -> Int in return kFirstTypeOffset } numberOfEntriesInFile: { (_) -> Int in return 18 } #endif
gpl-2.0
ad8544aecad31c1869100d39711294cf
39.307692
123
0.706743
3.351812
false
false
false
false
huonw/swift
test/Compatibility/conditional_compilation_expr.swift
1
5914
// RUN: %target-typecheck-verify-swift -D FOO -swift-version 3 // --------------------------------------------------------------------------- // Invalid binary operation #if FOO = false // expected-warning @-1 {{ignoring invalid conditional compilation expression, which will be rejected in future version of Swift}} undefinedFunc() // expected-error {{use of unresolved identifier 'undefinedFunc'}} #else undefinedFunc() // ignored. #endif #if false #elseif !FOO ? false : true // expected-warning @-1 {{ignoring invalid conditional compilation expression, which will be rejected in future version of Swift}} undefinedFunc() // ignored. #else undefinedFunc() // expected-error {{use of unresolved identifier 'undefinedFunc'}} #endif // --------------------------------------------------------------------------- // SR-3663: The precedence and associativity of '||' and '&&'. // See test/Parse/ConditionalCompilation/sequence.swift for Swift 4 behavior. // expected-warning @+1 {{future version of Swift have different rule for evaluating condition; add parentheses to make the condition compatible with Swift4}} {{14-14=(}} {{27-27=)}} #if false || true && false undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else undefinedElse() #endif // expected-warning @+1 {{future version of Swift have different rule for evaluating condition; add parentheses to make the condition compatible with Swift4}} {{5-5=(}} {{18-18=)}} #if false && true || true undefinedIf() #else undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}} #endif // expected-warning @+1 {{future version of Swift have different rule for evaluating condition; add parentheses to make the condition compatible with Swift4}} {{14-14=(}} {{27-27=)}} #if false || true && false || false undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else undefinedElse() #endif // expected-warning @+1 {{future version of Swift have different rule for evaluating condition; add parentheses to make the condition compatible with Swift4}} {{5-5=(}} {{18-18=)}} {{22-22=(}} {{42-42=)}} #if true && false || true && true && true undefinedIf() #else undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}} #endif // Accepted in Swift3. *source breaking* #if false || true && try! Swift // expected-error @-1 {{invalid conditional compilation expression}} // expected-warning @-2 {{future version of Swift have different rule for evaluating condition; add parentheses to make the condition compatible with Swift4}} {{14-14=(}} {{32-32=)}} undefinedIf() #endif // --------------------------------------------------------------------------- // SR-4032: "skip parsing" in non-active branch for version checks. // See test/Parse/ConditionalCompilation/sequence_version.swift for Swift 4 behavior. #if !swift(>=2.2) // There should be no error here. foo bar #else let _: Int = 1 #endif #if !compiler(>=4.1) // There should be no error here. foo bar #else let _: Int = 1 #endif #if (swift(>=2.2)) let _: Int = 1 #else // There should be no error here. foo bar #endif #if (compiler(>=4.1)) let _: Int = 1 #else // There should be no error here. foo bar #endif #if swift(>=99.0) || swift(>=88.1.1) // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #else undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}} #endif #if compiler(>=99.0) || compiler(>=88.1.1) // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #else undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}} #endif #if swift(>=99.0) || FOO undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else undefinedElse() #endif #if compiler(>=99.0) || FOO undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else undefinedElse() #endif #if swift(>=99.0) && FOO // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #else undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}} #endif #if compiler(>=99.0) && FOO // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #else undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}} #endif #if FOO && swift(>=2.2) undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #endif #if FOO && compiler(>=4.0) undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #endif #if swift(>=2.2) && swift(>=1) undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #endif #if compiler(>=4.1) && compiler(>=4) undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}} #else // There should be no error here. foo bar baz // expected-error 2 {{consecutive statements}} #endif // --------------------------------------------------------------------------- // SR-4031: Compound name in compilation condition // See test/Parse/ConditionalCompilation/compoundName_swift4.swift for Swfit 4 behavior #if BAR(_:) // expected-warning {{ignoring parentheses in compound name, which will be rejected in future version of Swift}} {{8-12=}} #elseif os(x:)(macOS) // expected-warning {{ignoring parentheses in compound name, which will be rejected in future version of Swift}} {{11-15=}} #elseif os(Linux(foo:bar:)) // expected-warning {{ignoring parentheses in compound name, which will be rejected in future version of Swift}} {{17-27=}} #endif
apache-2.0
bac26b1e5e1faf6d713ba80b03d06269
34.202381
204
0.681096
4.092734
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/ObjectMapper/Sources/EnumOperators.swift
18
3752
// // EnumOperators.swift // ObjectMapper // // Created by Tristan Himmelman on 2016-09-26. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK:- Raw Representable types /// Object of Raw Representable type public func <- <T: RawRepresentable>(left: inout T, right: Map) { left <- (right, EnumTransform()) } public func >>> <T: RawRepresentable>(left: T, right: Map) { left >>> (right, EnumTransform()) } /// Optional Object of Raw Representable type public func <- <T: RawRepresentable>(left: inout T?, right: Map) { left <- (right, EnumTransform()) } public func >>> <T: RawRepresentable>(left: T?, right: Map) { left >>> (right, EnumTransform()) } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Implicitly Unwrapped Optional Object of Raw Representable type public func <- <T: RawRepresentable>(left: inout T!, right: Map) { left <- (right, EnumTransform()) } #endif // MARK:- Arrays of Raw Representable type /// Array of Raw Representable object public func <- <T: RawRepresentable>(left: inout [T], right: Map) { left <- (right, EnumTransform()) } public func >>> <T: RawRepresentable>(left: [T], right: Map) { left >>> (right, EnumTransform()) } /// Array of Raw Representable object public func <- <T: RawRepresentable>(left: inout [T]?, right: Map) { left <- (right, EnumTransform()) } public func >>> <T: RawRepresentable>(left: [T]?, right: Map) { left >>> (right, EnumTransform()) } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Array of Raw Representable object public func <- <T: RawRepresentable>(left: inout [T]!, right: Map) { left <- (right, EnumTransform()) } #endif // MARK:- Dictionaries of Raw Representable type /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(left: inout [String: T], right: Map) { left <- (right, EnumTransform()) } public func >>> <T: RawRepresentable>(left: [String: T], right: Map) { left >>> (right, EnumTransform()) } /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(left: inout [String: T]?, right: Map) { left <- (right, EnumTransform()) } public func >>> <T: RawRepresentable>(left: [String: T]?, right: Map) { left >>> (right, EnumTransform()) } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(left: inout [String: T]!, right: Map) { left <- (right, EnumTransform()) } #endif
mit
53c5585d785a25a011040ebd8bf105c2
30.266667
81
0.685501
3.722222
false
false
false
false
maxdisney/urlsession_loss
LongCompletion/SampleDownloader.swift
1
4150
// // SampleDownloader.swift // LongCompletion // // Created by Max Goedjen on 11/10/15. // Copyright © 2015 Disney. All rights reserved. // import UIKit class SampleDownloader: NSObject { // Yeah I know, a singleton, but it's just a sample project. static let sharedDownloader = SampleDownloader() var session: NSURLSession? var backgroundCompletionHandler: (Void -> Void)? = nil var runningDownloads: [NSURLSessionDownloadTask] = [] private let transformerQueue = dispatch_queue_create("sampledownloader.transformer", nil) override init() { // This init requirement really sucks in this case session = NSURLSession() super.init() let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("SampleDownloader") config.allowsCellularAccess = false config.requestCachePolicy = .ReloadIgnoringLocalCacheData session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) discoverDetached() } func download(url: NSURL) { guard let task = session?.downloadTaskWithURL(url) else { return } runningDownloads.append(task) task.resume() } func discoverDetached() { session?.getTasksWithCompletionHandler { _, _, tasks in self.runningDownloads = tasks UILocalNotification.debugMessage("Discovered", downloader: self) } } var downloadedPath: String { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] return (documentsPath as NSString).stringByAppendingPathComponent("Downloads") } } extension SampleDownloader: NSURLSessionDelegate, NSURLSessionDownloadDelegate { func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { UILocalNotification.debugMessage("Finished \(downloadTask.currentRequest!.URL!.lastPathComponent)", downloader: self) _ = try? NSFileManager.defaultManager().moveItemAtPath(location.path!, toPath: downloadedPath) // Here be dragons /* Without this sleep, all's great, but any long running task in here (eg, unzipping a zip file) will block the delegate queue. That part's expected behavior. If the queue gets blocked, subesquent didFinishDownloadingToURL: messages won't get sent (again, expected). Eventually, the app will time out (again, we're in the background, so expected behavior, I totally get how you don't want someone to start a bg task and then have indefinite bg time) Here's where it gets weird: If the messages DON'T get sent, the temp files (located a `location` passed in) still get deleted. There appears to be no way to recover those tasks or temp files if this happens. Basically, the bug is: If `didFinishDownloadingToURL` doesn't get called, the temp files shouldn't get purged, or those tasks should still be marked as pending (ie, discoverable via getTasksWithCompletionHandler) */ // If you comment this sleep out, all will be good 🌈 sleep(600) // We'll time out long before this executes UILocalNotification.debugMessage("Sync sleep complete", downloader: nil) } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { print("Write \(totalBytesWritten)/\(totalBytesExpectedToWrite)") } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { } func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { dispatch_async(dispatch_get_main_queue()) { UILocalNotification.debugMessage("URLSessionFinished", downloader: nil) self.backgroundCompletionHandler?() self.backgroundCompletionHandler = nil } } }
mit
ae6107ff50b527d5bb104c5d9b272894
42.652632
214
0.694645
5.542781
false
true
false
false
cornerstonecollege/402
Younseo/CustomViews/CustomViews/FirstCustomView.swift
1
1758
// // FirstCustomView.swift // CustomViews // // Created by hoconey on 2016/10/13. // Copyright © 2016年 younseo. All rights reserved. // import UIKit class FirstCustomView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.red // default background color let label = UILabel() label.text = "Name" label.sizeToFit() label.center = CGPoint(x: self.frame.size.width/2, y:10) self.addSubview(label) let txtFrame = CGRect(x: ((self.frame.size.width) - 40)/2, y: 50, width: 40, height: 20) let textView = UITextField(frame: txtFrame) textView.backgroundColor = UIColor.white self.addSubview(textView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("began") } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { print("moved") if touches.first != nil { self.center = touches.first!.location(in: self.superview) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { print("end") } }
gpl-3.0
edda18d949e48620fb87f7563e73cd87
29.258621
100
0.531054
4.782016
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift
4
1856
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // Cipher-block chaining (CBC) // struct CBCModeWorker: BlockModeWorker { let cipherOperation: CipherOperationOnBlock private let iv: ArraySlice<UInt8> private var prev: ArraySlice<UInt8>? init(iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) { self.iv = iv self.cipherOperation = cipherOperation } mutating func encrypt(_ plaintext: ArraySlice<UInt8>) -> Array<UInt8> { guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { return Array(plaintext) } prev = ciphertext.slice return ciphertext } mutating func decrypt(_ ciphertext: ArraySlice<UInt8>) -> Array<UInt8> { guard let plaintext = cipherOperation(ciphertext) else { return Array(ciphertext) } let result: Array<UInt8> = xor(prev ?? iv, plaintext) prev = ciphertext return result } }
mit
ce0a1043c9ee12f3e8e4b2563de6e746
40.222222
217
0.70566
4.6375
false
false
false
false
Caiflower/SwiftWeiBo
花菜微博/花菜微博/Classes/Tools(工具)/Other/CFEmoticon/View/CFEmoticonToolbar.swift
1
2679
// // CFEmoticonToolbar.swift // CFEmoticonInputView // // Created by 花菜 on 2017/1/14. // Copyright © 2017年 花菜. All rights reserved. // import UIKit class CFEmoticonToolbar: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // 布局子控件 let w: CGFloat = bounds.width / CGFloat(CFEmoticonHelper.sharedHelper.packages.count) let h: CGFloat = 40 let rect = CGRect(x: 0, y: 0, width: w, height: h) for (i, btn) in subviews.enumerated() { btn.frame = rect.offsetBy(dx: CGFloat(i) * w, dy: 0) } } } // MARK: - 设置 UI 界面 fileprivate extension CFEmoticonToolbar { /// 添加子控件 func setupUI() { // 遍历表情包数组,添加表情包对应的按钮 for p in CFEmoticonHelper.sharedHelper.packages { // 创建按钮 let btn = UIButton(type: .custom) // 添加父控件 addSubview(btn) // 设置标题 btn.setTitle(p.groupName, for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.setTitleColor(UIColor.darkGray, for: .selected) btn.setTitleColor(UIColor.darkGray, for: .highlighted) btn.titleLabel?.font = UIFont.systemFont(ofSize: 14) // 设置背景图片 // 获取图片名 if let bgImageName = p.bgImageName { let imageName = "compose_emotion_table_\(bgImageName)_normal" let highlightImageName = "compose_emotion_table_\(bgImageName)_selected" if var image = UIImage(named: imageName, in: CFEmoticonBundle, compatibleWith: nil), var highlightImage = UIImage(named: highlightImageName, in: CFEmoticonBundle, compatibleWith: nil) { let insets = UIEdgeInsets(top: image.size.height * 0.5, left: image.size.width * 0.5, bottom: image.size.height * 0.5, right: image.size.width * 0.5) // 拉伸图片 image = image.resizableImage(withCapInsets: insets) highlightImage = highlightImage.resizableImage(withCapInsets: insets) btn.setBackgroundImage(image, for: .normal) btn.setBackgroundImage(highlightImage, for: .selected) btn.setBackgroundImage(highlightImage, for: .highlighted) } } } } }
apache-2.0
6c2f0ec6417e34ad9828c6e88b0dc0fd
34.887324
169
0.581633
4.470175
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Login/SLV_633_SNSAccountController.swift
1
4323
// // SLV_633_SNSAccountController.swift // selluv-ios // // Created by 조백근 on 2016. 12. 9.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import Foundation import UIKit import SnapKit import SwiftyUserDefaults class SLV_633_SNSAccountController: SLVBaseStatusHiddenController { var snsHistoryList: [AnyObject] = [] @IBOutlet weak var leftButton: UIBarButtonItem! @IBOutlet weak var snsAccountCollectionView: UICollectionView! // func dismiss() { // modalDelegate?.modalViewControllerDismiss(callbackData: nil) // } func dismissLogin() { tabController.closePresent() { } } override func viewDidLoad() { super.viewDidLoad() //login_account_edit_frame@3x self.setupNavigation() self.settingSnsLoginHistoryDatasource() } func setupNavigation() { self.navigationBar?.isHidden = false } @IBAction func touchBack(_ sender: Any) { // self.navigationController?.dismiss(animated: true, completion: nil) let parent = self.navigationController as! SLVBaseNavigationController parent.dismiss() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func settingSnsLoginHistoryDatasource() { self.snsHistoryList.removeAll() let model = LoginInfoModel.shared let isSnsLogin = model.isSNSProfile() if isSnsLogin{ let login = model.myLoginInfo(nil, .none) if (login?.fb_login)! { let thumb = login?.fb_thumnail let nick = login?.fb_nickname let myId = login?.fb_id self.snsHistoryList.append(["facebook", thumb, myId, nick] as AnyObject) } if (login?.ka_login)! { let thumb = login?.ka_thumnail let nick = login?.ka_nickname let myId = login?.ka_id self.snsHistoryList.append(["kakao", thumb, myId, nick] as AnyObject) } if (login?.nav_login)! { let thumb = login?.nav_thumnail let nick = login?.nav_nickname let myId = login?.nav_id self.snsHistoryList.append(["naver", thumb, myId, nick] as AnyObject) } if (login?.password_login)! { let nick = login?.password_nick let email = login?.password_email let thumb = "bt-sns-login-mail.png" self.snsHistoryList.append(["email", thumb, email, nick] as AnyObject) } } } } extension SLV_633_SNSAccountController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.snsHistoryList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SnsLoginAccountListInfoCell", for: indexPath) as! SnsLoginAccountListInfoCell let item = self.snsHistoryList[indexPath.row] as! [String] cell.binding(item: item) cell.onRemoveAccountBlock { (type) in if type == .facebook { let myId = item[2] as! String LoginInfoModel.shared.fbResetMyInfo(fb_id: myId) LoginInfoModel.shared.fbLogout() } else if type == .kakao { let myId = item[2] as! String LoginInfoModel.shared.kakaoResetMyInfo(ka_id: myId) LoginInfoModel.shared.kakaoLogout() } else if type == .naver { let myId = item[2] as! String LoginInfoModel.shared.naverResetMyInfo(nav_id: myId) LoginInfoModel.shared.naverLogout() } else if type == .email { // Defaults[.isAppAccessedServerKey] = false // Defaults[.appTokenKey] = "" // Defaults[.appUserNameKey] = "" // BBAuthToken.shared.clearToken() LoginInfoModel.shared.logoutUser(block: { (success) in }) } } return cell } }
mit
46de2a53fa795d1726e4a34ca2a75b46
34.652893
153
0.587854
4.820112
false
false
false
false
fgengine/quickly
Quickly/Compositions/Standart/Placeholders/QPlaceholderImageTitleShapeComposition.swift
1
6326
// // Quickly // open class QPlaceholderImageTitleShapeComposable : QComposable { public var imageStyle: QImageViewStyleSheet public var imageWidth: CGFloat public var imageSpacing: CGFloat public var titleStyle: QPlaceholderStyleSheet public var titleHeight: CGFloat public var shapeModel: QShapeView.Model public var shapeWidth: CGFloat public var shapeSpacing: CGFloat public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, imageStyle: QImageViewStyleSheet, imageWidth: CGFloat = 96, imageSpacing: CGFloat = 4, titleStyle: QPlaceholderStyleSheet, titleHeight: CGFloat, shapeModel: QShapeView.Model, shapeWidth: CGFloat = 16, shapeSpacing: CGFloat = 4 ) { self.imageStyle = imageStyle self.imageWidth = imageWidth self.imageSpacing = imageSpacing self.titleStyle = titleStyle self.titleHeight = titleHeight self.shapeModel = shapeModel self.shapeWidth = shapeWidth self.shapeSpacing = shapeSpacing super.init(edgeInsets: edgeInsets) } } open class QPlaceholderImageTitleShapeComposition< Composable: QPlaceholderImageTitleShapeComposable >: QComposition< Composable > { public private(set) lazy var imageView: QImageView = { let view = QImageView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var titleView: QPlaceholderView = { let view = QPlaceholderView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var shapeView: QShapeView = { let view = QShapeView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _imageWidth: CGFloat? private var _imageSpacing: CGFloat? private var _titleHeight: CGFloat? private var _shapeWidth: CGFloat? private var _shapeSpacing: CGFloat? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } private var _imageConstraints: [NSLayoutConstraint] = [] { willSet { self.imageView.removeConstraints(self._imageConstraints) } didSet { self.imageView.addConstraints(self._imageConstraints) } } private var _titleConstraints: [NSLayoutConstraint] = [] { willSet { self.titleView.removeConstraints(self._titleConstraints) } didSet { self.titleView.addConstraints(self._titleConstraints) } } private var _shapeConstraints: [NSLayoutConstraint] = [] { willSet { self.shapeView.removeConstraints(self._shapeConstraints) } didSet { self.shapeView.addConstraints(self._shapeConstraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right) let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth)) let shapeSize = composable.shapeModel.size return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + max(imageSize.height, composable.titleHeight, shapeSize.height) + composable.edgeInsets.bottom ) } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._shapeSpacing != composable.shapeSpacing { self._edgeInsets = composable.edgeInsets self._imageSpacing = composable.imageSpacing self._shapeSpacing = composable.shapeSpacing self._constraints = [ self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.imageView.trailingLayout == self.titleView.leadingLayout.offset(-composable.imageSpacing), self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.titleView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.shapeView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.shapeView.leadingLayout == self.titleView.trailingLayout.offset(composable.shapeSpacing), self.shapeView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.shapeView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom) ] } if self._imageWidth != composable.imageWidth { self._imageWidth = composable.imageWidth self._imageConstraints = [ self.imageView.widthLayout == composable.imageWidth ] } if self._titleHeight != composable.titleHeight { self._titleHeight = composable.titleHeight self._titleConstraints = [ self.titleView.heightLayout == composable.titleHeight ] } if self._shapeWidth != composable.shapeWidth { self._shapeWidth = composable.shapeWidth self._shapeConstraints = [ self.shapeView.widthLayout == composable.shapeWidth ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.imageView.apply(composable.imageStyle) self.titleView.apply(composable.titleStyle) self.shapeView.model = composable.shapeModel } }
mit
f583a3aefec76e8f3c07d6043a084b2a
43.549296
152
0.683528
5.553995
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/Instrumentation/NetworkStatus/Reachability/Reachability.swift
1
15271
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 SystemConfiguration import Foundation enum ReachabilityError: Error { case failedToCreateWithAddress(sockaddr, Int32) case failedToCreateWithHostname(String, Int32) case unableToSetCallback(Int32) case unableToSetDispatchQueue(Int32) case unableToGetFlags(Int32) } @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged") let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") extension Notification.Name { static let reachabilityChanged = Notification.Name("reachabilityChanged") } class Reachability { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () @available(*, unavailable, renamed: "Connection") public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public enum Connection: CustomStringConvertible { case unavailable, wifi, cellular public var description: String { switch self { case .cellular: return "Cellular" case .wifi: return "WiFi" case .unavailable: return "No Connection" } } @available(*, deprecated, renamed: "unavailable") public static let none: Connection = .unavailable } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? @available(*, deprecated, renamed: "allowsCellularConnection") public let reachableOnWWAN: Bool = true /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default @available(*, deprecated, renamed: "connection.description") public var currentReachabilityString: String { return "\(connection)" } @available(*, unavailable, renamed: "connection") public var currentReachabilityStatus: Connection { return connection } public var connection: Connection { if flags == nil { try? setReachabilityFlags() } switch flags?.connection { case .unavailable?, nil: return .unavailable case .cellular?: return allowsCellularConnection ? .cellular : .unavailable case .wifi?: return .wifi } } fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() fileprivate(set) var notifierRunning = false fileprivate let reachabilityRef: SCNetworkReachability fileprivate let reachabilitySerialQueue: DispatchQueue fileprivate let notificationQueue: DispatchQueue? fileprivate(set) var flags: SCNetworkReachabilityFlags? { didSet { guard flags != oldValue else { return } notifyReachabilityChanged() } } required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil, notificationQueue: DispatchQueue? = .main) { self.allowsCellularConnection = true self.reachabilityRef = reachabilityRef self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue) self.notificationQueue = notificationQueue } public convenience init(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil, notificationQueue: DispatchQueue? = .main) throws { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { throw ReachabilityError.failedToCreateWithHostname(hostname, SCError()) } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue, notificationQueue: notificationQueue) } public convenience init(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil, notificationQueue: DispatchQueue? = .main) throws { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { throw ReachabilityError.failedToCreateWithAddress(zeroAddress, SCError()) } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue, notificationQueue: notificationQueue) } deinit { stopNotifier() } } extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard !notifierRunning else { return } let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in guard let info = info else { return } // `weakifiedReachability` is guaranteed to exist by virtue of our // retain/release callbacks which we provided to the `SCNetworkReachabilityContext`. let weakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info).takeUnretainedValue() // The weak `reachability` _may_ no longer exist if the `Reachability` // object has since been deallocated but a callback was already in flight. weakifiedReachability.reachability?.flags = flags } let weakifiedReachability = ReachabilityWeakifier(reachability: self) let opaqueWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.passUnretained(weakifiedReachability).toOpaque() var context = SCNetworkReachabilityContext( version: 0, info: UnsafeMutableRawPointer(opaqueWeakifiedReachability), retain: { (info: UnsafeRawPointer) -> UnsafeRawPointer in let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info) _ = unmanagedWeakifiedReachability.retain() return UnsafeRawPointer(unmanagedWeakifiedReachability.toOpaque()) }, release: { (info: UnsafeRawPointer) -> Void in let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info) unmanagedWeakifiedReachability.release() }, copyDescription: { (info: UnsafeRawPointer) -> Unmanaged<CFString> in let unmanagedWeakifiedReachability = Unmanaged<ReachabilityWeakifier>.fromOpaque(info) let weakifiedReachability = unmanagedWeakifiedReachability.takeUnretainedValue() let description = weakifiedReachability.reachability?.description ?? "nil" return Unmanaged.passRetained(description as CFString) } ) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.unableToSetCallback(SCError()) } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.unableToSetDispatchQueue(SCError()) } // Perform an initial check try setReachabilityFlags() notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** @available(*, deprecated, message: "Please use `connection != .none`") var isReachable: Bool { return connection != .unavailable } @available(*, deprecated, message: "Please use `connection == .cellular`") var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return connection == .cellular } @available(*, deprecated, message: "Please use `connection == .wifi`") var isReachableViaWiFi: Bool { return connection == .wifi } var description: String { return flags?.description ?? "unavailable flags" } } fileprivate extension Reachability { func setReachabilityFlags() throws { try reachabilitySerialQueue.sync { [unowned self] in var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) { self.stopNotifier() throw ReachabilityError.unableToGetFlags(SCError()) } self.flags = flags } } func notifyReachabilityChanged() { let notify = { [weak self] in guard let self = self else { return } self.connection != .unavailable ? self.whenReachable?(self) : self.whenUnreachable?(self) self.notificationCenter.post(name: .reachabilityChanged, object: self) } // notify on the configured `notificationQueue`, or the caller's (i.e. `reachabilitySerialQueue`) notificationQueue?.async(execute: notify) ?? notify() } } extension SCNetworkReachabilityFlags { typealias Connection = Reachability.Connection var connection: Connection { guard isReachableFlagSet else { return .unavailable } // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi #if targetEnvironment(simulator) return .wifi #else var connection = Connection.unavailable if !isConnectionRequiredFlagSet { connection = .wifi } if isConnectionOnTrafficOrDemandFlagSet { if !isInterventionRequiredFlagSet { connection = .wifi } } if isOnWWANFlagSet { connection = .cellular } return connection #endif } var isOnWWANFlagSet: Bool { #if os(iOS) return contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return contains(.isLocalAddress) } var isDirectFlagSet: Bool { return contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } var description: String { let W = isOnWWANFlagSet ? "W" : "-" let R = isReachableFlagSet ? "R" : "-" let c = isConnectionRequiredFlagSet ? "c" : "-" let t = isTransientConnectionFlagSet ? "t" : "-" let i = isInterventionRequiredFlagSet ? "i" : "-" let C = isConnectionOnTrafficFlagSet ? "C" : "-" let D = isConnectionOnDemandFlagSet ? "D" : "-" let l = isLocalAddressFlagSet ? "l" : "-" let d = isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } /** `ReachabilityWeakifier` weakly wraps the `Reachability` class in order to break retain cycles when interacting with CoreFoundation. CoreFoundation callbacks expect a pair of retain/release whenever an opaque `info` parameter is provided. These callbacks exist to guard against memory management race conditions when invoking the callbacks. #### Race Condition If we passed `SCNetworkReachabilitySetCallback` a direct reference to our `Reachability` class without also providing corresponding retain/release callbacks, then a race condition can lead to crashes when: - `Reachability` is deallocated on thread X - A `SCNetworkReachability` callback(s) is already in flight on thread Y #### Retain Cycle If we pass `Reachability` to CoreFoundtion while also providing retain/ release callbacks, we would create a retain cycle once CoreFoundation retains our `Reachability` class. This fixes the crashes and his how CoreFoundation expects the API to be used, but doesn't play nicely with Swift/ARC. This cycle would only be broken after manually calling `stopNotifier()` — `deinit` would never be called. #### ReachabilityWeakifier By providing both retain/release callbacks and wrapping `Reachability` in a weak wrapper, we: - interact correctly with CoreFoundation, thereby avoiding a crash. See "Memory Management Programming Guide for Core Foundation". - don't alter the public API of `Reachability.swift` in any way - still allow for automatic stopping of the notifier on `deinit`. */ private class ReachabilityWeakifier { weak var reachability: Reachability? init(reachability: Reachability) { self.reachability = reachability } }
apache-2.0
0180846847082cbfab5825650c1f108c
36.701235
129
0.678302
5.712308
false
false
false
false
ohadh123/MuscleUp-
Pods/MaterialMotion/src/interactions/Spring.swift
1
5777
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import CoreGraphics import IndefiniteObservable /** The default tension configuration. */ public let defaultSpringTension: CGFloat = 342 /** The default friction configuration. */ public let defaultSpringFriction: CGFloat = 30 /** The default mass configuration. */ public let defaultSpringMass: CGFloat = 1 /** A spring pulls a value from an initial position to a destination using a physical simulation of a dampened oscillator. A spring can be associated with many properties. Each property receives its own distinct simulator that reads the property as the initial value and pulls the value towards the destination. Configuration values are shared across all running instances. **Constraints** T-value constraints may be applied to this interaction. */ public class Spring<T>: Interaction, Togglable, Stateful where T: Zeroable, T: Subtractable { /** Creates a spring with a given threshold and system. - parameter threshold: The threshold of movement defining the completion of the spring simulation. This parameter is not used by the Core Animation system and can be left as a default value. - parameter system: The system that should be used to drive this spring. */ public init(threshold: CGFloat = 1, system: @escaping SpringToStream<T> = coreAnimation) { self.threshold = createProperty(withInitialValue: threshold) self.system = system } /** The initial velocity of the spring. Applied to the physical simulation only when it starts. */ public let initialVelocity = createProperty(withInitialValue: T.zero() as! T) /** The destination value of the spring represented as a property. Changing this property will immediately affect the spring simulation. */ public let destination = createProperty(withInitialValue: T.zero() as! T) /** Tension defines how quickly the spring's value moves towards its destination. Higher tension means higher initial velocity and more overshoot. */ public let tension = createProperty(withInitialValue: defaultSpringTension) /** Tension defines how quickly the spring's velocity slows down. Higher friction means quicker deceleration and less overshoot. */ public let friction = createProperty(withInitialValue: defaultSpringFriction) /** The mass affects the value's acceleration. Higher mass means slower acceleration and deceleration. */ public let mass = createProperty(withInitialValue: defaultSpringMass) /** The suggested duration of the spring represented as a property. This property may not be supported by all animation systems. A value of 0 means this property will be ignored. */ public let suggestedDuration = createProperty(withInitialValue: 0) /** The value used when determining completion of the spring simulation. */ public let threshold: ReactiveProperty<CGFloat> /** Whether or not the spring is currently taking effect. Enabling a previously disabled spring will restart the animation from the current initial value. */ public let enabled = createProperty(withInitialValue: true) /** The current state of the spring animation. */ public var state: MotionObservable<MotionState> { return aggregateState.asStream() } public func add(to property: ReactiveProperty<T>, withRuntime runtime: MotionRuntime, constraints applyConstraints: ConstraintApplicator<T>? = nil) { let shadow = SpringShadow(of: self, initialValue: property) aggregateState.observe(state: shadow.state, withRuntime: runtime) var stream = system(shadow) if let applyConstraints = applyConstraints { stream = applyConstraints(stream) } runtime.connect(stream, to: property) } fileprivate let system: SpringToStream<T> private let aggregateState = AggregateMotionState() private var activeSprings = Set<SpringShadow<T>>() } public struct SpringShadow<T>: Hashable where T: Zeroable, T: Subtractable { public let enabled: ReactiveProperty<Bool> public let state = createProperty(withInitialValue: MotionState.atRest) public let initialValue: ReactiveProperty<T> public let initialVelocity: ReactiveProperty<T> public let destination: ReactiveProperty<T> public let tension: ReactiveProperty<CGFloat> public let friction: ReactiveProperty<CGFloat> public let mass: ReactiveProperty<CGFloat> public let suggestedDuration: ReactiveProperty<CGFloat> public let threshold: ReactiveProperty<CGFloat> init(of spring: Spring<T>, initialValue: ReactiveProperty<T>) { self.enabled = spring.enabled self.initialValue = initialValue self.initialVelocity = spring.initialVelocity self.destination = spring.destination self.tension = spring.tension self.friction = spring.friction self.mass = spring.mass self.suggestedDuration = spring.suggestedDuration self.threshold = spring.threshold } private let uuid = NSUUID().uuidString public var hashValue: Int { return uuid.hashValue } public static func ==(lhs: SpringShadow<T>, rhs: SpringShadow<T>) -> Bool { return lhs.uuid == rhs.uuid } }
apache-2.0
65c00d7e43b91047394695e0926da5e8
32.393064
193
0.751774
4.912415
false
false
false
false
codefellows/sea-b19-ios
Projects/burgermenu/burgermenu/ViewController.swift
1
1865
// // ViewController.swift // burgermenu // // Created by Bradley Johnson on 9/4/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillShowNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (note) -> Void in UIView.animateWithDuration(0.4, animations: { () -> Void in self.view.center = CGPoint(x: self.view.center.x, y: self.view.center.y - 222.0) }) println("Keyboard is showing") } NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillHideNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (note) -> Void in UIView.animateWithDuration(0.4, animations: { () -> Void in self.view.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: UIScreen.mainScreen().bounds.size) }) println("Keyboard is hiding") } } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { for control in self.view.subviews { if let textField = control as? UITextField { textField.endEditing(true) } } let asapQueue = NSNotificationQueue(notificationCenter: NSNotificationCenter.defaultCenter()) let asapNotification = NSNotification(name: "HeyThere", object: nil, userInfo: nil) asapQueue.enqueueNotification(asapNotification, postingStyle: NSPostingStyle.PostASAP) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
d36add8db075e5cc3e6bfd0efa236bcf
34.188679
147
0.627882
5.026954
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Other/Extensions.swift
1
11586
// // Extensions.swift // JenkinsiOS // // Created by Robert on 25.09.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation import UIKit extension URL { /// Get the current url, replacing its scheme with a given scheme and its port with a given port /// /// - parameter scheme: The url scheme that should be used (i.e. https) /// - parameter port: The port that should be used (i.e. 443) /// /// - returns: The given url, with port and scheme replaced func using(scheme: String, at port: Int? = nil) -> URL? { var components = URLComponents(url: self, resolvingAgainstBaseURL: false) components?.port = port components?.scheme = scheme return components?.url } } extension Optional { /// Return a nicer version of an optional value string /// /// - returns: A string describing the optional: either "nil" or its actual value func textify() -> String { switch self { case .none: return "Unknown" default: return "\(self!)" } } } extension Bool { var humanReadableString: String { return self ? "Yes" : "No" } } extension Double { /// Return a string indicating the number of gigabytes from a Double indicating a number of bytes /// /// - parameter numberFormatter: The numberformatter that should be used /// /// - returns: The string indicating the number of gigabytes func bytesToGigabytesString(numberFormatter: NumberFormatter) -> String { return NSNumber(value: self).bytesToGigabytesString(numberFormatter: numberFormatter) } } extension Int { /// Return a string indicating the number of gigabytes from an Int64 indicating a number of bytes /// /// - parameter numberFormatter: The numberformatter that should be used /// /// - returns: The string indicating the number of gigabytes func bytesToGigabytesString(numberFormatter: NumberFormatter) -> String { return NSNumber(value: self).bytesToGigabytesString(numberFormatter: numberFormatter) } } extension NSNumber { func bytesToGigabytesString(numberFormatter: NumberFormatter) -> String { func numberString(from number: Double) -> String? { guard number >= 0.0, let str = numberFormatter.string(from: NSNumber(value: number)) else { return nil } return str } func numberString(str: String?, with suffix: String) -> String { guard let str = str else { return "? B" } return "\(str) \(suffix)" } if Double(int64Value / (1024 * 1024 * 1024)) > 0.5 { return numberString(str: numberString(from: Double(int64Value / (1024 * 1024 * 1024))), with: "GB") } else if Double(int64Value / (1024 * 1024)) > 0.5 { return numberString(str: numberString(from: Double(int64Value / (1024 * 1024))), with: "MB") } else if Double(int64Value / 1024) > 0.5 { return numberString(str: numberString(from: Double(int64Value / 1024)), with: "KB") } else { return numberString(str: numberString(from: doubleValue), with: "B") } } } extension Dictionary { /// Instantiate a Dictionary from an array of tuples /// /// - parameter elements: The array of tuples that the Dictionary should be initialised from /// /// - returns: An initialised Dictionary object init(elements: [(Key, Value)]) { self.init() for (key, value) in elements { self[key] = value } } } extension TimeInterval { /// Convert a TimeInterval to a string describing it /// /// - returns: A string describing the TimeInterval in the form: xx hours /// yy minutes zz seconds func toString() -> String { let seconds = (self / 1000).truncatingRemainder(dividingBy: 60) let minutes = (self / 60000).truncatingRemainder(dividingBy: 60) let hours = self / 3_600_000 var returnString = "" if Int(hours) > 0 { returnString += "\(Int(hours)) hours " } if Int(minutes) > 0 { returnString += "\(Int(minutes)) minutes " } if Int(seconds) > 0 && !(Int(hours) > 0 && Int(minutes) > 0) { returnString += "\(Int(seconds)) seconds" } return returnString.isEmpty ? "Unknown" : returnString } } extension UIViewController { /// Display an error with given title, message, textfields and alert actions /// /// - parameter title: The title of the error /// - parameter message: The error message /// - parameter textFields: The text fields that should be displayed /// - parameter actions: The actions that should be displayed func displayError(title: String, message: String?, textFieldConfigurations: [(UITextField) -> Void], actions: [UIAlertAction]) { // Is the view controller currently visible? guard isViewLoaded && view.window != nil else { return } let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) actions.forEach { action in alertController.addAction(action) } textFieldConfigurations.forEach { textFieldConfiguration in alertController.addTextField(configurationHandler: textFieldConfiguration) } present(alertController, animated: true, completion: nil) } /// Display an error based on a given error /// /// - parameter error: The error that should be displayed accordingly /// - parameter completion: The completion that is called if the error is a 403 NetworkManagerError.HTTPResponseNoSuccess error func displayNetworkError(error: Error, onReturnWithTextFields completion: (([String: String?]) -> Void)?) { if let networkManagerError = error as? NetworkManagerError { switch networkManagerError { case let .HTTPResponseNoSuccess(code, _): if code == 403 || code == 401 { var userNameTextField: UITextField! var passwordTextField: UITextField! let textFieldConfigurations: [(UITextField) -> Void] = [ { (textField) -> Void in textField.placeholder = "Username" userNameTextField = textField }, { (textField) -> Void in textField.placeholder = "Password" passwordTextField = textField }, ] let doneAction = UIAlertAction(title: "Save", style: .default) { (_) -> Void in completion?(["username": userNameTextField.text, "password": passwordTextField.text]) } let cancelAction = UIAlertAction(title: "Discard", style: .cancel, handler: nil) let message = "Please provide username and password" displayError(title: "Error", message: message, textFieldConfigurations: textFieldConfigurations, actions: [cancelAction, doneAction]) } else { let message = "An error occured \(code)" let cancelAction = UIAlertAction(title: "Alright", style: .cancel, handler: nil) displayError(title: "Error", message: message, textFieldConfigurations: [], actions: [cancelAction]) } case let .dataTaskError(error): let doneAction = UIAlertAction(title: "Alright", style: .cancel, handler: nil) displayError(title: "Error", message: error.localizedDescription, textFieldConfigurations: [], actions: [doneAction]) default: let doneAction = UIAlertAction(title: "Alright", style: .cancel, handler: nil) displayError(title: "Error", message: "An error occurred", textFieldConfigurations: [], actions: [doneAction]) } } else { let doneAction = UIAlertAction(title: "Alright", style: .cancel, handler: nil) displayError(title: "Error", message: error.localizedDescription, textFieldConfigurations: [], actions: [doneAction]) } } func alertWithImage(image: UIImage?, title: String, message: String, height: CGFloat, widthInset: CGFloat = 50) -> UIAlertController { let alert = UIAlertController(title: title, message: message + "\n\n\n\n\n\n", preferredStyle: .alert) let imageView = UIImageView(image: image) imageView.translatesAutoresizingMaskIntoConstraints = false alert.view.addSubview(imageView) imageView.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor).isActive = true imageView.widthAnchor.constraint(equalTo: alert.view.widthAnchor, constant: -2 * widthInset).isActive = true imageView.centerYAnchor.constraint(equalTo: alert.view.centerYAnchor).isActive = true imageView.heightAnchor.constraint(equalToConstant: height).isActive = true return alert } } extension UITableViewController { /// Update the bottom content inset for devices that do not have safe area insets func setBottomContentInsetForOlderDevices() { if #available(iOS 11.0, *) {} else { tableView.contentInset.bottom = tabBarController?.tabBar.frame.height ?? tableView.contentInset.bottom } } } extension UIImageView { /// Set an image view's image to an image, resized by a scale factor /// /// - parameter image: The image that should be resized and set as the view's image /// - parameter size: The size the image should be resized to func withResized(image: UIImage, size: CGSize) { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.image = newImage } } extension UILabel { @objc func updateFontName(to name: String) { let fontName = font.isBold ? (name + "-Bold") : name + "-Regular" font = UIFont(name: fontName, size: font.pointSize) } } extension UIView { func setCornerRounding(radius: CGFloat, corners: UIRectCorner) { let path = UIBezierPath(roundedRect: layer.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer(layer: layer) mask.path = path.cgPath layer.masksToBounds = true layer.mask = mask } } extension UIButton { func centerButtonImageAndTitle() { guard let image = self.imageView?.image, let label = self.titleLabel, let text = label.text else { return } let offset: CGFloat = 4.0 let textSize = (text as NSString).size(withAttributes: [NSAttributedString.Key.font: label.font]) titleEdgeInsets = UIEdgeInsets(top: offset, left: (-image.size.width - textSize.width) / 2, bottom: -image.size.height, right: 0.0) imageEdgeInsets = UIEdgeInsets(top: -(textSize.height + offset), left: 0, bottom: 0, right: (-image.size.width - textSize.width) / 2) } } extension UIFont { var isBold: Bool { return fontDescriptor.symbolicTraits.contains(.traitBold) } }
mit
79ab8d15d6fe7c039486e2649e83c4f4
39.649123
153
0.622788
4.890249
false
false
false
false
jameshuynh/JHDownloadManager
Pod/Classes/JHDownloadTask.swift
1
7983
// // JHDownloadTask.swift // JHDownloadManager // // Created by James Huynh on 20/2/16. // Copyright © 2016 jameshuynh. All rights reserved. // import UIKit import FileMD5Hash public class JHDownloadTask: NSObject { public var completed: Bool = false public var cachedProgress: Float = 0 internal var totalBytesWritten: Int64 = 0 internal var totalBytesExpectedToWrite: Int64 = 0 internal var isDownloading = false public var url: NSURL? public var urlString: String? public var destination: String? public var fileName: String? public var checksum: String? public var downloadError: NSError? public var lastErrorMessage: String? public var identifier: String? public var position: Int = -1 private var fileHashAlgorithm: FileHashAlgorithm? init(urlString: String, destination:String, totalBytesExpectedToWrite:Int64, checksum:String?, fileHashAltgorithm:FileHashAlgorithm) { super.init() self.url = NSURL(string: urlString) self.commonInit(urlString: urlString, destination: destination, totalBytesExpectedToWriteInput: totalBytesExpectedToWrite, checksum: checksum, fileHashAlgorithm: fileHashAltgorithm) } init(url: NSURL, destination:String, totalBytesExpectedToWrite:Int64, checksum:String?, fileHashAltgorithm:FileHashAlgorithm) { super.init() self.url = url self.commonInit(urlString: url.absoluteString, destination: destination, totalBytesExpectedToWriteInput: totalBytesExpectedToWrite, checksum: checksum, fileHashAlgorithm: fileHashAltgorithm) } func getURL() -> NSURL { return self.url! } func commonInit(urlString urlString: String, destination:String, totalBytesExpectedToWriteInput:Int64, checksum:String?, fileHashAlgorithm:FileHashAlgorithm) { self.urlString = urlString self.completed = false self.totalBytesWritten = 0 self.totalBytesExpectedToWrite = totalBytesExpectedToWriteInput self.checksum = checksum self.fileHashAlgorithm = fileHashAlgorithm self.destination = destination self.fileName = (destination as NSString).lastPathComponent self.prepareFolderForDestination() } func downloadingProgress() -> Float { if self.completed { return 1 }//end if if self.totalBytesExpectedToWrite > 0 { return Float(self.totalBytesWritten) / Float(self.totalBytesExpectedToWrite) } else { return 0 } } func verifyDownload() -> Bool { let fileManager = NSFileManager.defaultManager() let absoluteDestinationPath = self.absoluteDestinationPath() if fileManager.fileExistsAtPath(absoluteDestinationPath) == false { return false } var isVerified = false if let unwrappedChecksum = self.checksum { let calculatedChecksum = self.retrieveChecksumDownnloadedFile() isVerified = calculatedChecksum == unwrappedChecksum } else { do { let fileAttributes = try fileManager.attributesOfItemAtPath(absoluteDestinationPath) let fileSize = (fileAttributes[NSFileSize] as! NSNumber).longLongValue isVerified = fileSize == self.totalBytesExpectedToWrite } catch let error as NSError { print("Error Received \(error.localizedDescription)") } catch { print("Error Received") } }//end else if isVerified { self.completed = true self.cachedProgress = 1 } else { self.totalBytesWritten = self.totalBytesExpectedToWrite }//end else return isVerified } func retrieveChecksumDownnloadedFile() -> String { let absolutePath = self.absoluteDestinationPath() if fileHashAlgorithm == FileHashAlgorithm.MD5 { return FileHash.md5HashOfFileAtPath(absolutePath) } else if fileHashAlgorithm == FileHashAlgorithm.SHA1 { return FileHash.sha1HashOfFileAtPath(absolutePath) } else if fileHashAlgorithm == FileHashAlgorithm.SHA512 { return FileHash.sha512HashOfFileAtPath(absolutePath) }//end else return "-1" } func prepareFolderForDestination() { let absoluteDestinationPath = self.absoluteDestinationPath() let containerFolderPath = (absoluteDestinationPath as NSString).stringByDeletingLastPathComponent let fileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(containerFolderPath) == false { do { try fileManager.createDirectoryAtPath(containerFolderPath, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { print("Create Directory Error: \(error.localizedDescription)") } catch { print("Create Directory Error - Something went wrong") } } if fileManager.fileExistsAtPath(absoluteDestinationPath) { if self.verifyDownload() { self.cachedProgress = 1 // retain file - this task has been completed } else { self.cleanUp() } } else { self.cleanUp() } } func cleanUp() { self.completed = false self.downloadError = nil self.totalBytesWritten = 0 self.cachedProgress = 0 self.deleteDestinationFile() } func cleanUpWithResumableData(data: NSData) { self.completed = false self.totalBytesWritten = Int64(data.length) self.deleteDestinationFile() self.downloadError = nil } func deleteDestinationFile() { let fileManager = NSFileManager.defaultManager() let absoluteDestinationPath = self.absoluteDestinationPath() if fileManager.fileExistsAtPath(absoluteDestinationPath) { do { try fileManager.removeItemAtPath(absoluteDestinationPath) } catch let error as NSError { print("Removing Existing File Error: \(error.localizedDescription)") } } } func absoluteDestinationPath() -> String { let documentDictionary = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first return "\(documentDictionary!)/\(self.destination!)" } func isHittingErrorBecauseOffline() -> Bool { if let _ = self.downloadError, unwrappedLastErrorMessage = self.lastErrorMessage { return unwrappedLastErrorMessage.containsString("(Code \(NSURLError.NotConnectedToInternet))") || unwrappedLastErrorMessage.containsString("(Code \(NSURLError.NetworkConnectionLost))") } else { return false } } func isHittingErrorConnectingToServer() -> Bool { if let unwrappedLastErrorMessage = self.lastErrorMessage { return unwrappedLastErrorMessage.containsString("(Code \(NSURLError.RedirectToNonExistentLocation))") || unwrappedLastErrorMessage.containsString("(Code \(NSURLError.BadServerResponse))") || unwrappedLastErrorMessage.containsString("(Code \(NSURLError.ZeroByteResource))") || unwrappedLastErrorMessage.containsString("(Code \(NSURLError.TimedOut))") } else { return false } } func captureReceivedError(error:NSError) { self.downloadError = error } func fullErrorDescription() -> String { if let unwrappedError = self.downloadError { let errorCode = unwrappedError.code return "Downloading URL %@ failed because of error: \(self.urlString) (Code \(errorCode))" } else { return "No Error" } } }
mit
f22318a686e5d4c12a354c5ec9f7d8bc
37.560386
202
0.649587
5.873436
false
false
false
false
drewag/Swiftlier
Sources/Swiftlier/FileSystem/FileSystem+iOSDirectories.swift
1
1058
// // UIImage+Editing.swift // Swiftlier // // Created by Andrew J Wagner on 5/25/16. // Copyright © 2016 Drewag LLC. All rights reserved. // #if os(iOS) import UIKit extension FileSystem { public var documentsDirectory: DirectoryPath { let url = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let path = self.path(from: url) return try! path.directory ?? path.createDirectory() } public var cachesDirectory: DirectoryPath { let url = try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let path = self.path(from: url) return try! path.directory ?? path.createDirectory() } public var libraryDirectory: DirectoryPath { let url = try! FileManager.default.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let path = self.path(from: url) return try! path.directory ?? path.createDirectory() } } #endif
mit
0deab288502a368af3118ec0e7c6a26f
33.096774
127
0.679281
4.081081
false
false
false
false