repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
fjbelchi/CodeTest-BoardingPass-Swift
BoardingCardsTests/Models/BoardingBusPassTests.swift
1
2231
// // BoardingPassTests.swift // // Copyright (c) 2015 Francisco J. Belchi. All rights reserved. import UIKit import XCTest import BoardingCards class BoardingBusPassTests: XCTestCase { func testBoardingPassConstructor_Success() { let madrid = City(name: "Madrid") let barcelona = City(name: "Barcelona") let boardingPass = BoardingBusPass(boardingId: "test", cityFrom: madrid, cityTo: barcelona, bus: "bus", seat: "seat") if let pass = boardingPass { XCTAssertEqual(pass.boardingId, "test") XCTAssertEqual(pass.cityFrom.name, madrid.name) XCTAssertEqual(pass.cityTo.name, barcelona.name) XCTAssertEqual(pass.busName, "bus") XCTAssertEqual(pass.seatNumber, "seat") } else { XCTFail("BoardingPass has Not to be Nil") } } func testBoardingPassConstructor_Fail() { let madrid = City(name: "Madrid") let barcelona = City(name: "Barcelona") let boardingPass = BoardingBusPass(boardingId: "", cityFrom: madrid, cityTo: barcelona, bus: "bus", seat: "seat") if let _ = boardingPass { XCTFail("BoardingPass has to be Nil") } } func testBoardingPassEquatable_Success() { let madrid = City(name: "Madrid") let barcelona = City(name: "Barcelona") let boardingPass1 = BoardingBusPass(boardingId: "test", cityFrom: madrid, cityTo: barcelona, bus: "bus", seat: "seat") let boardingPass2 = BoardingBusPass(boardingId: "test", cityFrom: madrid, cityTo: barcelona, bus: "bus", seat: "seat") XCTAssertEqual(boardingPass1!, boardingPass2!, "both has to be equal") } func testBoardingPassNotEquatable_Success() { let madrid = City(name: "Madrid") let barcelona = City(name: "Barcelona") let boardingPass1 = BoardingBusPass(boardingId: "1", cityFrom: madrid, cityTo: barcelona, bus: "bus", seat: "seat") let boardingPass2 = BoardingBusPass(boardingId: "2", cityFrom: madrid, cityTo: barcelona, bus: "bus", seat: "seat") XCTAssertNotEqual(boardingPass1!, boardingPass2!, "both has not to be equal") } }
mit
exoplatform/exo-ios
Pods/Kingfisher/Sources/Image/ImageProcessor.swift
1
36902
// // ImageProcessor.swift // Kingfisher // // Created by Wei Wang on 2016/08/26. // // Copyright (c) 2019 Wei Wang <onevcat@gmail.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 import CoreGraphics #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit #endif /// Represents an item which could be processed by an `ImageProcessor`. /// /// - image: Input image. The processor should provide a way to apply /// processing on this `image` and return the result image. /// - data: Input data. The processor should provide a way to apply /// processing on this `image` and return the result image. public enum ImageProcessItem { /// Input image. The processor should provide a way to apply /// processing on this `image` and return the result image. case image(KFCrossPlatformImage) /// Input data. The processor should provide a way to apply /// processing on this `image` and return the result image. case data(Data) } /// An `ImageProcessor` would be used to convert some downloaded data to an image. public protocol ImageProcessor { /// Identifier of the processor. It will be used to identify the processor when /// caching and retrieving an image. You might want to make sure that processors with /// same properties/functionality have the same identifiers, so correct processed images /// could be retrieved with proper key. /// /// - Note: Do not supply an empty string for a customized processor, which is already reserved by /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of /// your own for the identifier. var identifier: String { get } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: The parsed options when processing the item. /// - Returns: The processed image. /// /// - Note: The return value should be `nil` if processing failed while converting an input item to image. /// If `nil` received by the processing caller, an error will be reported and the process flow stops. /// If the processing flow is not critical for your flow, then when the input item is already an image /// (`.image` case) and there is any errors in the processing, you could return the input image itself /// to keep the processing pipeline continuing. /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing /// a filter, the input image will be returned directly on watchOS. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? } extension ImageProcessor { /// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor` /// will be "\(self.identifier)|>\(another.identifier)". /// /// - Parameter another: An `ImageProcessor` you want to append to `self`. /// - Returns: The new `ImageProcessor` will process the image in the order /// of the two processors concatenated. public func append(another: ImageProcessor) -> ImageProcessor { let newIdentifier = identifier.appending("|>\(another.identifier)") return GeneralProcessor(identifier: newIdentifier) { item, options in if let image = self.process(item: item, options: options) { return another.process(item: .image(image), options: options) } else { return nil } } } } func ==(left: ImageProcessor, right: ImageProcessor) -> Bool { return left.identifier == right.identifier } func !=(left: ImageProcessor, right: ImageProcessor) -> Bool { return !(left == right) } typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?) struct GeneralProcessor: ImageProcessor { let identifier: String let p: ProcessorImp func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return p(item, options) } } /// The default processor. It converts the input data to a valid image. /// Images of .PNG, .JPEG and .GIF format are supported. /// If an image item is given as `.image` case, `DefaultImageProcessor` will /// do nothing on it and return the associated image. public struct DefaultImageProcessor: ImageProcessor { /// A default `DefaultImageProcessor` could be used across. public static let `default` = DefaultImageProcessor() /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "" /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance, /// if you do not have a good reason to create your own `DefaultImageProcessor`. public init() {} /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) case .data(let data): return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) } } } /// Represents the rect corner setting when processing a round corner image. public struct RectCorner: OptionSet { /// Raw value of the rect corner. public let rawValue: Int /// Represents the top left corner. public static let topLeft = RectCorner(rawValue: 1 << 0) /// Represents the top right corner. public static let topRight = RectCorner(rawValue: 1 << 1) /// Represents the bottom left corner. public static let bottomLeft = RectCorner(rawValue: 1 << 2) /// Represents the bottom right corner. public static let bottomRight = RectCorner(rawValue: 1 << 3) /// Represents all corners. public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight] /// Creates a `RectCorner` option set with a given value. /// /// - Parameter rawValue: The value represents a certain corner option. public init(rawValue: Int) { self.rawValue = rawValue } var cornerIdentifier: String { if self == .all { return "" } return "_corner(\(rawValue))" } } #if !os(macOS) /// Processor for adding an blend mode to images. Only CG-based images are supported. public struct BlendImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blend Mode will be used to blend the input image. public let blendMode: CGBlendMode /// Alpha will be used when blend image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: KFCrossPlatformColor? /// Creates a `BlendImageProcessor`. /// /// - Parameters: /// - blendMode: Blend Mode will be used to blend the input image. /// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image, /// 0.0 means transparent image (not visible at all). Default is 1.0. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { self.blendMode = blendMode self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } #endif #if os(macOS) /// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS. public struct CompositingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Compositing operation will be used to the input image. public let compositingOperation: NSCompositingOperation /// Alpha will be used when compositing image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: KFCrossPlatformColor? /// Creates a `CompositingImageProcessor` /// /// - Parameters: /// - compositingOperation: Compositing operation will be used to the input image. /// - alpha: Alpha will be used when compositing image. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image. /// Default is 1.0. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init(compositingOperation: NSCompositingOperation, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { self.compositingOperation = compositingOperation self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image( withCompositingOperation: compositingOperation, alpha: alpha, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } #endif /// Processor for making round corner images. Only CG-based images are supported in macOS, /// if a non-CG image passed in, the processor will do nothing. /// /// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain /// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order /// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That /// means the alpha channel will be removed for these images. When you load the processed image from cache again, you /// will lose transparent corner. /// /// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this /// case. /// public struct RoundCornerImageProcessor: ImageProcessor { /// Represents a radius specified in a `RoundCornerImageProcessor`. public enum Radius { /// The radius should be calculated as a fraction of the image width. Typically the associated value should be /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width. case widthFraction(CGFloat) /// The radius should be calculated as a fraction of the image height. Typically the associated value should be /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height. case heightFraction(CGFloat) /// Use a fixed point value as the round corner radius. case point(CGFloat) var radiusIdentifier: String { switch self { case .widthFraction(let f): return "w_frac_\(f)" case .heightFraction(let f): return "h_frac_\(f)" case .point(let p): return p.description } } } /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. public let radius: Radius /// The target corners which will be applied rounding. public let roundingCorners: RectCorner /// Target size of output image should be. If `nil`, the image will keep its original size after processing. public let targetSize: CGSize? /// Background color of the output image. If `nil`, it will use a transparent background. public let backgroundColor: KFCrossPlatformColor? /// Creates a `RoundCornerImageProcessor`. /// /// - Parameters: /// - cornerRadius: Corner radius in point will be applied in processing. /// - targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// - corners: The target corners which will be applied rounding. Default is `.all`. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. /// /// - Note: /// /// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still /// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a /// fraction of one dimension of the target image, use the `Radius` version instead. /// public init( cornerRadius: CGFloat, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: KFCrossPlatformColor? = nil ) { let radius = Radius.point(cornerRadius) self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor) } /// Creates a `RoundCornerImageProcessor`. /// /// - Parameters: /// - radius: The radius will be applied in processing. /// - targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// - corners: The target corners which will be applied rounding. Default is `.all`. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init( radius: Radius, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: KFCrossPlatformColor? = nil ) { self.radius = radius self.targetSize = targetSize self.roundingCorners = corners self.backgroundColor = backgroundColor self.identifier = { var identifier = "" if let size = targetSize { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + "(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))" } else { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + "(\(radius.radiusIdentifier)\(corners.cornerIdentifier))" } if let backgroundColor = backgroundColor { identifier += "_\(backgroundColor)" } return identifier }() } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): let size = targetSize ?? image.kf.size let cornerRadius: CGFloat switch radius { case .point(let point): cornerRadius = point case .widthFraction(let widthFraction): cornerRadius = size.width * widthFraction case .heightFraction(let heightFraction): cornerRadius = size.height * heightFraction } return image.kf.scaled(to: options.scaleFactor) .kf.image( withRoundRadius: cornerRadius, fit: size, roundingCorners: roundingCorners, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Represents how a size adjusts itself to fit a target size. /// /// - none: Not scale the content. /// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio. /// - aspectFill: Scales the content to fill the size of the view. public enum ContentMode { /// Not scale the content. case none /// Scales the content to fit the size of the view by maintaining the aspect ratio. case aspectFit /// Scales the content to fill the size of the view. case aspectFill } /// Processor for resizing images. /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor` /// instead, which is more efficient and uses less memory. public struct ResizingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// The reference size for resizing operation in point. public let referenceSize: CGSize /// Target content mode of output image should be. /// Default is `.none`. public let targetContentMode: ContentMode /// Creates a `ResizingImageProcessor`. /// /// - Parameters: /// - referenceSize: The reference size for resizing operation in point. /// - mode: Target content mode of output image should be. /// /// - Note: /// The instance of `ResizingImageProcessor` will follow its `mode` property /// and try to resizing the input images to fit or fill the `referenceSize`. /// That means if you are using a `mode` besides of `.none`, you may get an /// image with its size not be the same as the `referenceSize`. /// /// **Example**: With input image size: {100, 200}, /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`, /// you will get an output image with size of {50, 100}, which "fit"s /// the `referenceSize`. /// /// If you need an output image exactly to be a specified size, append or use /// a `CroppingImageProcessor`. public init(referenceSize: CGSize, mode: ContentMode = .none) { self.referenceSize = referenceSize self.targetContentMode = mode if mode == .none { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))" } else { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))" } } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.resize(to: referenceSize, for: targetContentMode) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for /// a better performance. A simulated Gaussian blur with specified blur radius will be applied. public struct BlurImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blur radius for the simulated Gaussian blur. public let blurRadius: CGFloat /// Creates a `BlurImageProcessor` /// /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. public init(blurRadius: CGFloat) { self.blurRadius = blurRadius self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): let radius = blurRadius * options.scaleFactor return image.kf.scaled(to: options.scaleFactor) .kf.blurred(withRadius: radius) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for adding an overlay to images. Only CG-based images are supported in macOS. public struct OverlayImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Overlay color will be used to overlay the input image. public let overlay: KFCrossPlatformColor /// Fraction will be used when overlay the color to image. public let fraction: CGFloat /// Creates an `OverlayImageProcessor` /// /// - parameter overlay: Overlay color will be used to overlay the input image. /// - parameter fraction: Fraction will be used when overlay the color to image. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) { self.overlay = overlay self.fraction = fraction self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.overlaying(with: overlay, fraction: fraction) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for tint images with color. Only CG-based images are supported. public struct TintImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Tint color will be used to tint the input image. public let tint: KFCrossPlatformColor /// Creates a `TintImageProcessor` /// /// - parameter tint: Tint color will be used to tint the input image. public init(tint: KFCrossPlatformColor) { self.tint = tint self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.tinted(with: tint) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for applying some color control to images. Only CG-based images are supported. /// watchOS is not supported. public struct ColorControlsProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Brightness changing to image. public let brightness: CGFloat /// Contrast changing to image. public let contrast: CGFloat /// Saturation changing to image. public let saturation: CGFloat /// InputEV changing to image. public let inputEV: CGFloat /// Creates a `ColorControlsProcessor` /// /// - Parameters: /// - brightness: Brightness changing to image. /// - contrast: Contrast changing to image. /// - saturation: Saturation changing to image. /// - inputEV: InputEV changing to image. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { self.brightness = brightness self.contrast = contrast self.saturation = saturation self.inputEV = inputEV self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for applying black and white effect to images. Only CG-based images are supported. /// watchOS is not supported. public struct BlackWhiteProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" /// Creates a `BlackWhiteProcessor` public init() {} /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) .process(item: item, options: options) } } /// Processor for cropping an image. Only CG-based images are supported. /// watchOS is not supported. public struct CroppingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Target size of output image should be. public let size: CGSize /// Anchor point from which the output size should be calculate. /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image. /// See `CroppingImageProcessor.init(size:anchor:)` for more. public let anchor: CGPoint /// Creates a `CroppingImageProcessor`. /// /// - Parameters: /// - size: Target size of output image should be. /// - anchor: The anchor point from which the size should be calculated. /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image. /// - Note: /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner. /// The `size` property of `CroppingImageProcessor` will be used along with /// `anchor` to calculate a target rectangle in the size of image. /// /// The target size will be automatically calculated with a reasonable behavior. /// For example, when you have an image size of `CGSize(width: 100, height: 100)`, /// and a target size of `CGSize(width: 20, height: 20)`: /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`; /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}` /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}` public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) { self.size = size self.anchor = anchor self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.crop(to: size, anchorOn: anchor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor /// does not render the images to resize. Instead, it downsamples the input data directly to an /// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible /// as you can than the `ResizingImageProcessor`. /// /// Only CG-based images are supported. Animated images (like GIF) is not supported. public struct DownsamplingImageProcessor: ImageProcessor { /// Target size of output image should be. It should be smaller than the size of /// input image. If it is larger, the result image will be the same size of input /// data without downsampling. public let size: CGSize /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Creates a `DownsamplingImageProcessor`. /// /// - Parameter size: The target size of the downsample operation. public init(size: CGSize) { self.size = size self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): guard let data = image.kf.data(format: .unknown) else { return nil } return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) case .data(let data): return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) } } } infix operator |>: AdditionPrecedence public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { return left.append(another: right) } extension KFCrossPlatformColor { var hex: String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 #if os(macOS) (usingColorSpace(.sRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a) #else getRed(&r, green: &g, blue: &b, alpha: &a) #endif let rInt = Int(r * 255) << 24 let gInt = Int(g * 255) << 16 let bInt = Int(b * 255) << 8 let aInt = Int(a * 255) let rgba = rInt | gInt | bInt | aInt return String(format:"#%08x", rgba) } }
lgpl-3.0
emilstahl/swift
validation-test/compiler_crashers_fixed/1406-swift-nominaltypedecl-computetype.swift
13
317
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f: ExtensibleCollectionType>(a)) -> d.join() protocol a { typealias A { " typealias e : A.e = b,
apache-2.0
emilstahl/swift
validation-test/compiler_crashers_fixed/1047-no-stacktrace.swift
13
356
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing -> { typealias e == b, V, T { } } func c<e: A { struct e where d enum A { private let t.<3] { } extension NSSet { public var e?) { } } } e {
apache-2.0
ThryvInc/subway-ios
SubwayMap/PredictionViewModel.swift
2
1895
// // PredictionViewModel.swift // SubwayMap // // Created by Elliot Schrock on 8/1/15. // Copyright (c) 2015 Thryv. All rights reserved. // import UIKit import SubwayStations // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } class PredictionViewModel: NSObject { var routeId: String! var direction: Direction! var prediction: Prediction! var onDeckPrediction: Prediction? var inTheHolePrediction: Prediction? var visits: [Visit]? init(routeId: String!, direction: Direction!) { self.routeId = routeId self.direction = direction } func setupWithPredictions(_ predictions: [Prediction]!){ var relevantPredictions = predictions.filter({(prediction) -> Bool in return prediction.direction!.rawValue == self.direction!.rawValue && prediction.route!.objectId == self.routeId }) relevantPredictions.sort { $0.secondsToArrival < $1.secondsToArrival } if relevantPredictions.count > 0 { prediction = relevantPredictions[0] } if relevantPredictions.count > 1 { onDeckPrediction = relevantPredictions[1] } if relevantPredictions.count > 2 { inTheHolePrediction = relevantPredictions[2] } } override func isEqual(_ object: Any?) -> Bool { if let predictionVM = object as? PredictionViewModel { return self.routeId == predictionVM.routeId && self.direction == predictionVM.direction }else{ return false } } }
mit
pebble8888/PBKit
PBKit/Float+PBMath.swift
1
292
// // Float+PBMath.swift // PBKit // // Created by pebble8888 on 2017/01/21. // Copyright © 2017年 pebble8888. All rights reserved. // import Foundation public func isNealyInteger<T : BinaryFloatingPoint>(val: T) -> Bool { return val.truncatingRemainder(dividingBy: 1.0) == 0.0 }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/27464-swift-typebase-isequal.swift
1
485
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A{enum a{ class B<f where g:A{class B<k{ class A{enum a{class a let a{ class b:A
apache-2.0
rnystrom/GitHawk
Classes/Section Controllers/SearchBar/SearchBarCell.swift
1
1772
// // SearchBarCell.swift // Freetime // // Created by Ryan Nystrom on 5/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit protocol SearchBarCellDelegate: class { func didChangeSearchText(cell: SearchBarCell, query: String) } final class SearchBarCell: UICollectionViewCell, UISearchBarDelegate { weak var delegate: SearchBarCellDelegate? private let searchBar = UISearchBar(frame: .zero) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white searchBar.returnKeyType = .search searchBar.enablesReturnKeyAutomatically = false searchBar.searchBarStyle = .minimal searchBar.delegate = self contentView.addSubview(searchBar) searchBar.snp.makeConstraints { make in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.centerY.equalTo(contentView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentView() } // MARK: Public API func configure(query: String, placeholder: String) { searchBar.text = query searchBar.placeholder = placeholder } // MARK: Private API func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { delegate?.didChangeSearchText(cell: self, query: searchText) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
mit
myteeNatanwit/webview1
webview1UITests/webview1UITests.swift
1
1248
// // webview1UITests.swift // webview1UITests // // Created by Michael Tran on 10/11/2015. // Copyright © 2015 intcloud. All rights reserved. // import XCTest class webview1UITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
rnystrom/GitHawk
Pods/GitHawkRoutes/GitHawkRoutes/BookmarkShortcutRoute.swift
1
524
// // BookmarkShortcutRoute.swift // Freetime // // Created by Ryan Nystrom on 10/7/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import Foundation public struct BookmarkShortcutRoute: Routable { public init() {} public static func from(params: [String: String]) -> BookmarkShortcutRoute? { return BookmarkShortcutRoute() } public var encoded: [String: String] { return [:] } public static var path: String { return "com.githawk.shortcut.bookmark" } }
mit
TryFetch/Downpour
Sources/DownpourType.swift
1
240
// // DownpourType.swift // Downpour // // Created by Stephen Radford on 18/05/2016. // Copyright © 2015 Stephen Radford. All rights reserved. // public enum DownpourType { case tv case movie case music case unknown }
gpl-3.0
passt0r/MaliDeck
MaliDeck/CardViewController.swift
1
12532
// // CardViewController.swift // MaliDeck // // Created by Dmytro Pasinchuk on 06.11.16. // Copyright © 2016 Dmytro Pasinchuk. All rights reserved. // import UIKit class CardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var choosedMember: BandMembersTableViewCell! var bandMembers = [Stats]() //members in band var bandWounds = [Int]() let factions = [Fraction.guilde.rawValue, Fraction.arcanists.rawValue, Fraction.resurrectionists.rawValue, Fraction.neverborn.rawValue, Fraction.outcasts.rawValue, Fraction.tenThunders.rawValue, Fraction.gremlins.rawValue] //factions list, need for Picker View var selectedFaction: Fraction? = nil @IBOutlet weak var factionChoosingPicker: UIPickerView! //choosing game format @IBOutlet weak var choosedGameFormat: UISegmentedControl! var gameFormat = [35, 50, 75] @IBOutlet weak var chooseFractionTitleView: UIVisualEffectView! @IBOutlet weak var bandNameTitleView: UIVisualEffectView! func visualEffectForTitle(titleView: UIVisualEffectView) { /* let bilImageView = UIImageView(image: UIImage(named: "bil")) bilImageView.frame = titleView.bounds bilImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleView.insertSubview(bilImageView, at: 0)*/ titleView.layer.cornerRadius = 20 titleView.clipsToBounds = true titleView.backgroundColor = UIColor(colorLiteralRed: 0.1, green: 0.8, blue: 0.1, alpha: 0.6) } @IBOutlet weak var bandMembersTableView: UITableView! //overriding setEditing property for parent ViewController to add setEditing property to bandMemberTableView override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if editing == true { navigationItem.rightBarButtonItem?.isEnabled = false } else { navigationItem.rightBarButtonItem?.isEnabled = true } bandMembersTableView.setEditing(editing, animated: animated) } override func viewDidLoad() { super.viewDidLoad() let editButton = editButtonItem navigationItem.leftBarButtonItem = editButton // addSamples() //implement at first launch of DB, need for test visualEffectForTitle(titleView: chooseFractionTitleView) visualEffectForTitle(titleView: bandNameTitleView) bandMembersTableView.delegate = self bandMembersTableView.dataSource = self factionChoosingPicker.dataSource = self factionChoosingPicker.delegate = self selectedFaction = Fraction(rawValue: factions[0]) let bilImageView = UIImageView(image: UIImage(named: "bil")) bilImageView.frame = UIScreen.main.bounds bandMembersTableView.backgroundColor = UIColor.clear bandMembersTableView.insertSubview(bilImageView, at: 0) bandMembersTableView.layer.cornerRadius = 10 bandMembersTableView.clipsToBounds = true //implement custom view of tableView and pickerView factionChoosingPicker.layer.cornerRadius = 15 factionChoosingPicker.clipsToBounds = true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait //why it is not work? } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func bandFiltration(by: Fraction) -> [Stats] { var filtratedBand = [Stats]() for member in bandMembers { if member.fraction == selectedFaction { filtratedBand.append(member) } } return filtratedBand } @IBAction func acceptButtonTouched(_ sender: UIButton) { bandMembers = bandFiltration(by: selectedFaction!) bandMembersTableView.reloadData() } //Getting data from AddingMembersTableViewController and prepare to insert data to band members table view @IBAction func unwindToAddingMemberViewTable(sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? AddingMembersTableViewController, let bandMember = sourceViewController.bandMember /*getting data */{ //adding new band member to your band let newBandMember = sourceViewController.bandMembers[bandMember] if !bandMembers.isEmpty { //checking new member faction if newBandMember.fraction != bandMembers[bandMembers.count - 1].fraction { //if faction did not mach to the band faction sourceViewController.dismiss(animated: true, completion: {print("Adding invalid member")}) alert(reason: "Invalid member", message: "You can't adding member from \(newBandMember.fraction.rawValue) faction to \(bandMembers[bandMembers.count - 1].fraction.rawValue) band.") return } } if bandMembers.isEmpty { //if you have no band if let newBandMember = newBandMember as? Master { //check of adding a master } else { //if you did not have any master yet sourceViewController.dismiss(animated: true, completion: {print("Dismiss to add some band master")}) alert(reason: "No master", message: "You did not have any band master yet, add someone.") return } } if let newBandMember = newBandMember as? Master { //if user add master, check if band have other one for master in bandMembers { if let master = master as? Master { sourceViewController.dismiss(animated: true, completion: {print("Dismiss of reason of adding second band master")}) //dismiss adding view and show error massage after that alert(reason: "Another master choosing", message: "In your band you have \(master.name), you can't add an other master") //showing error massage //alert(reason: "Another master choosing", message: "In your band you have \(master.name), you can't add an other master") return } } } //checking price of new member and valid of adding him to band var summuryMembersPrice = 0 for member in bandMembers { summuryMembersPrice += member.cost } summuryMembersPrice += newBandMember.cost for master in bandMembers { //finding band master's cash if let master = master as? Master { let playerCash = gameFormat[choosedGameFormat.selectedSegmentIndex] + master.cash if playerCash < summuryMembersPrice { //if new member too cost sourceViewController.dismiss(animated: true, completion: {print("Dissmis of reason of overpricing")}) alert(reason: "Overprice", message: "Adding a new member is imposible, you need extra \(summuryMembersPrice - playerCash) soulstones") return } } } let newIndexPath = IndexPath(row: bandMembers.count, section: 0) let memberLeftHits = newBandMember.wounds bandWounds.append(memberLeftHits) //add wounds for checking wounds that left bandMembers.append(newBandMember) //add member to array //insert data to tableview bandMembersTableView.insertRows(at: [newIndexPath], with: .bottom) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddingNewCharacter" { let destinationNavigationController = segue.destination as! UINavigationController let destinationViewController = destinationNavigationController.topViewController as! AddingMembersTableViewController destinationViewController.selectedFaction = selectedFaction } else if segue.identifier == "showStatCards" { let destinationNavigationController = segue.destination as! UINavigationController let destinationViewController = destinationNavigationController.topViewController as! StatCardViewController guard let selectedMember = sender as? BandMembersTableViewCell else { fatalError("Error with choosing member")} guard let indexforMember = bandMembersTableView.indexPath(for: selectedMember) else { fatalError("Error with finding index") } let choosingMember = bandMembers[indexforMember.row] destinationViewController.currentMember = choosingMember guard let hitLeft = Int(selectedMember.bandMemberHillPoint.text!) else { fatalError("Cannot convert hillPoint to int") } destinationViewController.hitsLeft = hitLeft } } @IBAction func unwindToStatCard(sender: UIStoryboardSegue) { guard let statCardController = sender.source as? StatCardViewController else { fatalError("Unexpected sender for unwindToStatCard()") } let newHills = statCardController.hitsLeft guard let indexOfSelectedRow = bandMembersTableView.indexPathForSelectedRow else { fatalError("Can't find selected row for update data") } /*let selectedRow = bandMembersTableView.cellForRow(at: indexOfSelectedRow) as! BandMembersTableViewCell selectedRow.bandMemberHillPoint.text = String(newHills)*/ //bandMembers[indexOfSelectedRow.row].wounds = newHills bandWounds[indexOfSelectedRow.row] = newHills bandMembersTableView.reloadRows(at: [indexOfSelectedRow], with: .automatic) } func numberOfSections(in tableView: UITableView) -> Int { // return the number of sections return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return the number of row in section return bandMembers.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat.init(50) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BandMember", for: indexPath) as! BandMembersTableViewCell cell.bandMemberName.text = bandMembers[indexPath.row].name cell.bandMemberHillPoint.text = String(bandWounds[indexPath.row]) return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { bandMembers.remove(at: indexPath.row) bandWounds.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } //error massage func alert(reason: String, message: String) { let alert = UIAlertController(title: reason, message: message, preferredStyle: .alert) alert.addAction(.init(title: "Ok, go next", style: .default, handler: nil)) self.present(alert, animated: true, completion: {print("Error displayed on Card View Controller")}) } //MARK: picker view controll func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return factions.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return factions[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedFaction = Fraction(rawValue: factions[row]) } }
gpl-3.0
n8armstrong/CalendarView
CalendarView/Carthage/Checkouts/SwiftMoment/SwiftMoment/SwiftMoment/Moment.swift
1
16410
// // Moment.swift // SwiftMoment // // Created by Adrian on 19/01/15. // Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved. // // Swift adaptation of Moment.js http://momentjs.com // Github: https://github.com/moment/moment/ import Foundation /** Returns a moment representing the current instant in time at the current timezone - parameter timeZone: An NSTimeZone object - parameter locale: An NSLocale object - returns: A moment instance. */ public func moment(_ timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment { return Moment(timeZone: timeZone, locale: locale) } public func utc() -> Moment { let zone = TimeZone(abbreviation: "UTC")! return moment(zone) } /** Returns an Optional wrapping a Moment structure, representing the current instant in time. If the string passed as parameter cannot be parsed by the function, the Optional wraps a nil value. - parameter stringDate: A string with a date representation. - parameter timeZone: An NSTimeZone object - parameter locale: An NSLocale object - returns: <#return value description#> */ public func moment(_ stringDate: String, timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { let formatter = DateFormatter() formatter.timeZone = timeZone formatter.locale = locale let isoFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" // The contents of the array below are borrowed // and adapted from the source code of Moment.js // https://github.com/moment/moment/blob/develop/moment.js let formats = [ isoFormat, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd", "h:mm:ss A", "h:mm A", "MM/dd/yyyy", "MMMM d, yyyy", "MMMM d, yyyy LT", "dddd, MMMM D, yyyy LT", "yyyyyy-MM-dd", "yyyy-MM-dd", "GGGG-[W]WW-E", "GGGG-[W]WW", "yyyy-ddd", "HH:mm:ss.SSSS", "HH:mm:ss", "HH:mm", "HH" ] for format in formats { formatter.dateFormat = format if let date = formatter.date(from: stringDate) { return Moment(date: date, timeZone: timeZone, locale: locale) } } return nil } public func moment(_ stringDate: String, dateFormat: String, timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.timeZone = timeZone formatter.locale = locale if let date = formatter.date(from: stringDate) { return Moment(date: date, timeZone: timeZone, locale: locale) } return nil } /** Builds a new Moment instance using an array with the following components, in the following order: [ year, month, day, hour, minute, second ] - parameter params: An array of integer values as date components - parameter timeZone: An NSTimeZone object - parameter locale: An NSLocale object - returns: An optional wrapping a Moment instance */ public func moment(_ params: [Int], timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { if params.count > 0 { var calendar = Calendar.current calendar.timeZone = timeZone var components = DateComponents() components.year = params[0] if params.count > 1 { components.month = params[1] if params.count > 2 { components.day = params[2] if params.count > 3 { components.hour = params[3] if params.count > 4 { components.minute = params[4] if params.count > 5 { components.second = params[5] } } } } } if let date = calendar.date(from: components) { return moment(date, timeZone: timeZone, locale: locale) } } return nil } public func moment(_ dict: [String: Int], timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { if dict.count > 0 { var params = [Int]() if let year = dict["year"] { params.append(year) } if let month = dict["month"] { params.append(month) } if let day = dict["day"] { params.append(day) } if let hour = dict["hour"] { params.append(hour) } if let minute = dict["minute"] { params.append(minute) } if let second = dict["second"] { params.append(second) } return moment(params, timeZone: timeZone, locale: locale) } return nil } public func moment(_ milliseconds: Int) -> Moment { return moment(TimeInterval(milliseconds / 1000)) } public func moment(_ seconds: TimeInterval) -> Moment { let interval = TimeInterval(seconds) let date = Date(timeIntervalSince1970: interval) return Moment(date: date) } public func moment(_ date: Date, timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment { return Moment(date: date, timeZone: timeZone, locale: locale) } public func moment(_ moment: Moment) -> Moment { let date = moment.date let timeZone = moment.timeZone let locale = moment.locale return Moment(date: date, timeZone: timeZone, locale: locale) } public func past() -> Moment { return Moment(date: Date.distantPast ) } public func future() -> Moment { return Moment(date: Date.distantFuture ) } public func since(_ past: Moment) -> Duration { return moment().intervalSince(past) } public func maximum(_ moments: Moment...) -> Moment? { if moments.count > 0 { var max: Moment = moments[0] for moment in moments { if moment > max { max = moment } } return max } return nil } public func minimum(_ moments: Moment...) -> Moment? { if moments.count > 0 { var min: Moment = moments[0] for moment in moments { if moment < min { min = moment } } return min } return nil } /** Internal structure used by the family of moment() functions. Instead of modifying the native NSDate class, this is a wrapper for the NSDate object. To get this wrapper object, simply call moment() with one of the supported input types. */ public struct Moment: Comparable { public let minuteInSeconds = 60 public let hourInSeconds = 3600 public let dayInSeconds = 86400 public let weekInSeconds = 604800 public let monthInSeconds = 2592000 public let yearInSeconds = 31536000 public let date: Date public let timeZone: TimeZone public let locale: Locale init(date: Date = Date(), timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) { self.date = date self.timeZone = timeZone self.locale = locale } /// Returns the year of the current instance. public var year: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.year, from: date) return components.year! } /// Returns the month (1-12) of the current instance. public var month: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.month, from: date) return components.month! } /// Returns the name of the month of the current instance, in the current locale. public var monthName: String { let formatter = DateFormatter() formatter.locale = locale return formatter.monthSymbols[month - 1] } public var day: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.day, from: date) return components.day! } public var hour: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.hour, from: date) return components.hour! } public var minute: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.minute, from: date) return components.minute! } public var second: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.second, from: date) return components.second! } public var weekday: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.weekday, from: date) return components.weekday! } public var weekdayName: String { let formatter = DateFormatter() formatter.locale = locale formatter.dateFormat = "EEEE" formatter.timeZone = timeZone return formatter.string(from: date) } public var weekdayOrdinal: Int { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone let components = (cal as NSCalendar).components(.weekdayOrdinal, from: date) return components.weekdayOrdinal! } public var weekOfYear: Int { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone let components = (cal as NSCalendar).components(.weekOfYear, from: date) return components.weekOfYear! } public var quarter: Int { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone let components = (cal as NSCalendar).components(.quarter, from: date) return components.quarter! } // Methods public func get(_ unit: TimeUnit) -> Int? { switch unit { case .Seconds: return second case .Minutes: return minute case .Hours: return hour case .Days: return day case .Weeks: return weekOfYear case .Months: return month case .Quarters: return quarter case .Years: return year } } public func get(_ unitName: String) -> Int? { if let unit = TimeUnit(rawValue: unitName) { return get(unit) } return nil } public func format(_ dateFormat: String = "yyyy-MM-dd HH:mm:ss ZZZZ") -> String { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.timeZone = timeZone formatter.locale = locale return formatter.string(from: date) } public func isEqualTo(_ moment: Moment) -> Bool { return (date == moment.date) } public func intervalSince(_ moment: Moment) -> Duration { let interval = date.timeIntervalSince(moment.date) return Duration(value: Int(interval)) } public func add(_ value: Int, _ unit: TimeUnit) -> Moment { var interval = value switch unit { case .Years: interval = value * Int(1.years.interval) case .Quarters: interval = value * Int(1.quarters.interval) case .Months: interval = value * Int(1.months.interval) case .Weeks: interval = value * Int(1.weeks.interval) case .Days: interval = value * Int(1.days.interval) case .Hours: interval = value * Int(1.hours.interval) case .Minutes: interval = value * Int(1.minutes.interval) case .Seconds: interval = value } return add(TimeInterval(interval), .Seconds) } public func add(_ value: TimeInterval, _ unit: TimeUnit) -> Moment { let seconds = convert(value, unit) let interval = TimeInterval(seconds) let newDate = date.addingTimeInterval(interval) return Moment(date: newDate, timeZone: timeZone) } public func add(_ value: Int, _ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return add(value, unit) } return self } public func add(_ duration: Duration) -> Moment { return add(duration.interval, .Seconds) } public func subtract(_ value: TimeInterval, _ unit: TimeUnit) -> Moment { return add(-value, unit) } public func subtract(_ value: Int, _ unit: TimeUnit) -> Moment { return add(-value, unit) } public func subtract(_ value: Int, _ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return subtract(value, unit) } return self } public func subtract(_ duration: Duration) -> Moment { return subtract(duration.interval, .Seconds) } public func isCloseTo(_ moment: Moment, precision: TimeInterval = 300) -> Bool { // "Being close" is measured using a precision argument // which is initialized a 300 seconds, or 5 minutes. let delta = intervalSince(moment) return abs(delta.interval) < precision } public func startOf(_ unit: TimeUnit) -> Moment { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone var newDate: Date? var components = (cal as NSCalendar).components([.year, .month, .weekday, .day, .hour, .minute, .second], from: date) switch unit { case .Seconds: return self case .Years: components.month = 1 fallthrough case .Quarters, .Months, .Weeks: if unit == .Weeks { components.day = components.day! - (components.weekday! - 2) } else { components.day = 1 } fallthrough case .Days: components.hour = 0 fallthrough case .Hours: components.minute = 0 fallthrough case .Minutes: components.second = 0 } newDate = cal.date(from: components) return newDate == nil ? self : Moment(date: newDate!, timeZone: timeZone) } public func startOf(_ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return startOf(unit) } return self } public func endOf(_ unit: TimeUnit) -> Moment { return startOf(unit).add(1, unit).subtract(1.seconds) } public func endOf(_ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return endOf(unit) } return self } public func epoch() -> TimeInterval { return date.timeIntervalSince1970 } // Private methods func convert(_ value: Double, _ unit: TimeUnit) -> Double { switch unit { case .Seconds: return value case .Minutes: return value * 60 case .Hours: return value * 3600 // 60 minutes case .Days: return value * 86400 // 24 hours case .Weeks: return value * 605800 // 7 days case .Months: return value * 2592000 // 30 days case .Quarters: return value * 7776000 // 3 months case .Years: return value * 31536000 // 365 days } } } extension Moment: CustomStringConvertible { public var description: String { return format() } } extension Moment: CustomDebugStringConvertible { public var debugDescription: String { return description } }
mit
ip3r/Cart
Cart/Core/UIKit/Transitions/DismissTransition.swift
1
398
// // DismissTransition.swift // Cart // // Created by Jens Meder on 12.06.17. // Copyright © 2017 Jens Meder. All rights reserved. // import UIKit internal final class DismissTransition: Transition { // MARK: Init internal init() { } // MARK: Transition func transition(parent: UIViewController) { parent.dismiss(animated: true, completion: nil) } }
mit
certificate-helper/TLS-Inspector
TLS Inspector/Features/RecentLookups.swift
1
2880
import Foundation private let LIST_KEY = "RECENT_DOMAINS" /// Class for managing recently inspected domains class RecentLookups { /// Return all recently inspected domains public static func GetRecentLookups() -> [String] { guard let list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return [] } return list } /// Add a new recently inspected domain. If the domain was already in the list, it is moved to index 0. /// - Parameter domain: The domain to add. Case insensitive. public static func AddLookup(_ url: URL) { var list: [String] = [] if let savedList = AppDefaults.array(forKey: LIST_KEY) as? [String] { list = savedList } guard let host = url.host else { LogError("Unable to add URL \(url) to lookup list: host is nil") return } var port = 443 if let urlPort = url.port { port = urlPort } var domain = host if port != 443 { domain += ":\(port)" } if let index = list.firstIndex(of: domain.lowercased()) { list.remove(at: index) } if list.count >= 5 { list.remove(at: 4) } LogDebug("Adding query '\(domain.lowercased())' to recent lookup list") list.insert(domain.lowercased(), at: 0) AppDefaults.set(list, forKey: LIST_KEY) } /// Remove the recently inspected domain at the specified index. /// - Parameter index: The index to remove. public static func RemoveLookup(index: Int) { guard var list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return } if index > list.count || index < 0 { return } list.remove(at: index) AppDefaults.set(list, forKey: LIST_KEY) } /// Remove the specified recently inspected domain. /// - Parameter domain: The domain to remove. Case insensitive. public static func RemoveLookup(domain: String) { guard var list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return } guard let index = IndexOfDomain(domain) else { return } list.remove(at: index) AppDefaults.set(list, forKey: LIST_KEY) } /// Remove all recently inspected domains. public static func RemoveAllLookups() { AppDefaults.set([], forKey: LIST_KEY) } /// Get the index of the specified domain. Returns nil if not found. /// - Parameter domain: The domain to search for. Case insenstivie. public static func IndexOfDomain(_ domain: String) -> Int? { guard let list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return nil } return list.firstIndex(of: domain.lowercased()) } }
gpl-3.0
natestedman/PrettyOkayKit
PrettyOkayKitTests/UserTests.swift
1
4338
// Copyright (c) 2016, Nate Stedman <nate@natestedman.com> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. @testable import PrettyOkayKit import XCTest final class UserTests: XCTestCase { func testDecodeNullOptionals() { let encoded: [String:AnyObject] = [ "_links":[ "password_reset":[ "href":"/account/password-reset?user_id=1" ], "self":[ "href":"/users/1" ] ], "avatar_image_key": NSNull(), "avatar_url": NSNull(), "avatar_url_centered_126": NSNull(), "bio": NSNull(), "cover_image": NSNull(), "cover_image_big_url": NSNull(), "cover_image_key": NSNull(), "cover_image_thumb_url": NSNull(), "created_at": [ "_date":"2014-08-14T20:55:51.201380+00:00" ], "good_count": 100, "id": 1, "last_activity_at": [ "_date":"2014-08-14T20:55:51.848298+00:00" ], "location": NSNull(), "name": "Test", "updated_at": [ "_date":"2014-08-14T20:55:51.848256+00:00" ], "url": NSNull(), "username":"test" ] XCTAssertEqual(try? User(encoded: encoded), User( identifier: 1, username: "test", name: "Test", biography: nil, location: nil, URL: nil, avatarURL: nil, avatarURLCentered126: nil, coverURL: nil, coverLargeURL: nil, coverThumbURL: nil, goodsCount: 100 )) } func testDecodeNonNullOptionals() { let encoded: [String:AnyObject] = [ "_links":[ "password_reset":[ "href":"/account/password-reset?user_id=1" ], "self":[ "href":"/users/1" ] ], "avatar_image_key": NSNull(), "avatar_url": "http://test.com/avatar", "avatar_url_centered_126": "http://test.com/avatar_126", "bio": "Test Bio", "cover_image": "http://test.com/cover", "cover_image_big_url": "http://test.com/cover_big", "cover_image_key": NSNull(), "cover_image_thumb_url": "http://test.com/cover_thumb", "created_at": [ "_date":"2014-08-14T20:55:51.201380+00:00" ], "good_count": 100, "id": 1, "last_activity_at": [ "_date":"2014-08-14T20:55:51.848298+00:00" ], "location": "Test Location", "name": "Test", "updated_at": [ "_date":"2014-08-14T20:55:51.848256+00:00" ], "url": "http://test.com", "username":"test" ] XCTAssertEqual(try? User(encoded: encoded), User( identifier: 1, username: "test", name: "Test", biography: "Test Bio", location: "Test Location", URL: NSURL(string: "http://test.com")!, avatarURL: NSURL(string: "http://test.com/avatar")!, avatarURLCentered126: NSURL(string: "http://test.com/avatar_126")!, coverURL: NSURL(string: "http://test.com/cover")!, coverLargeURL: NSURL(string: "http://test.com/cover_big")!, coverThumbURL: NSURL(string: "http://test.com/cover_thumb")!, goodsCount: 100 )) } }
isc
noppoMan/aws-sdk-swift
Sources/Soto/Services/Shield/Shield_Shapes.swift
1
44420
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension Shield { // MARK: Enums public enum AttackLayer: String, CustomStringConvertible, Codable { case application = "APPLICATION" case network = "NETWORK" public var description: String { return self.rawValue } } public enum AttackPropertyIdentifier: String, CustomStringConvertible, Codable { case destinationUrl = "DESTINATION_URL" case referrer = "REFERRER" case sourceAsn = "SOURCE_ASN" case sourceCountry = "SOURCE_COUNTRY" case sourceIpAddress = "SOURCE_IP_ADDRESS" case sourceUserAgent = "SOURCE_USER_AGENT" case wordpressPingbackReflector = "WORDPRESS_PINGBACK_REFLECTOR" case wordpressPingbackSource = "WORDPRESS_PINGBACK_SOURCE" public var description: String { return self.rawValue } } public enum AutoRenew: String, CustomStringConvertible, Codable { case disabled = "DISABLED" case enabled = "ENABLED" public var description: String { return self.rawValue } } public enum ProactiveEngagementStatus: String, CustomStringConvertible, Codable { case disabled = "DISABLED" case enabled = "ENABLED" case pending = "PENDING" public var description: String { return self.rawValue } } public enum SubResourceType: String, CustomStringConvertible, Codable { case ip = "IP" case url = "URL" public var description: String { return self.rawValue } } public enum SubscriptionState: String, CustomStringConvertible, Codable { case active = "ACTIVE" case inactive = "INACTIVE" public var description: String { return self.rawValue } } public enum Unit: String, CustomStringConvertible, Codable { case bits = "BITS" case bytes = "BYTES" case packets = "PACKETS" case requests = "REQUESTS" public var description: String { return self.rawValue } } // MARK: Shapes public struct AssociateDRTLogBucketRequest: AWSEncodableShape { /// The Amazon S3 bucket that contains your AWS WAF logs. public let logBucket: String public init(logBucket: String) { self.logBucket = logBucket } public func validate(name: String) throws { try self.validate(self.logBucket, name: "logBucket", parent: name, max: 63) try self.validate(self.logBucket, name: "logBucket", parent: name, min: 3) try self.validate(self.logBucket, name: "logBucket", parent: name, pattern: "^([a-z]|(\\d(?!\\d{0,2}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})))([a-z\\d]|(\\.(?!(\\.|-)))|(-(?!\\.))){1,61}[a-z\\d]$") } private enum CodingKeys: String, CodingKey { case logBucket = "LogBucket" } } public struct AssociateDRTLogBucketResponse: AWSDecodableShape { public init() {} } public struct AssociateDRTRoleRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the role the DRT will use to access your AWS account. Prior to making the AssociateDRTRole request, you must attach the AWSShieldDRTAccessPolicy managed policy to this role. For more information see Attaching and Detaching IAM Policies. public let roleArn: String public init(roleArn: String) { self.roleArn = roleArn } public func validate(name: String) throws { try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+") } private enum CodingKeys: String, CodingKey { case roleArn = "RoleArn" } } public struct AssociateDRTRoleResponse: AWSDecodableShape { public init() {} } public struct AssociateHealthCheckRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the health check to associate with the protection. public let healthCheckArn: String /// The unique identifier (ID) for the Protection object to add the health check association to. public let protectionId: String public init(healthCheckArn: String, protectionId: String) { self.healthCheckArn = healthCheckArn self.protectionId = protectionId } public func validate(name: String) throws { try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, max: 2048) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, min: 1) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, pattern: "^arn:aws:route53:::healthcheck/\\S{36}$") try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case healthCheckArn = "HealthCheckArn" case protectionId = "ProtectionId" } } public struct AssociateHealthCheckResponse: AWSDecodableShape { public init() {} } public struct AssociateProactiveEngagementDetailsRequest: AWSEncodableShape { /// A list of email addresses and phone numbers that the DDoS Response Team (DRT) can use to contact you for escalations to the DRT and to initiate proactive customer support. To enable proactive engagement, the contact list must include at least one phone number. The contacts that you provide here replace any contacts that were already defined. If you already have contacts defined and want to use them, retrieve the list using DescribeEmergencyContactSettings and then provide it here. public let emergencyContactList: [EmergencyContact] public init(emergencyContactList: [EmergencyContact]) { self.emergencyContactList = emergencyContactList } public func validate(name: String) throws { try self.emergencyContactList.forEach { try $0.validate(name: "\(name).emergencyContactList[]") } try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, max: 10) try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case emergencyContactList = "EmergencyContactList" } } public struct AssociateProactiveEngagementDetailsResponse: AWSDecodableShape { public init() {} } public struct AttackDetail: AWSDecodableShape { /// List of counters that describe the attack for the specified time period. public let attackCounters: [SummarizedCounter]? /// The unique identifier (ID) of the attack. public let attackId: String? /// The array of AttackProperty objects. public let attackProperties: [AttackProperty]? /// The time the attack ended, in Unix time in seconds. For more information see timestamp. public let endTime: Date? /// List of mitigation actions taken for the attack. public let mitigations: [Mitigation]? /// The ARN (Amazon Resource Name) of the resource that was attacked. public let resourceArn: String? /// The time the attack started, in Unix time in seconds. For more information see timestamp. public let startTime: Date? /// If applicable, additional detail about the resource being attacked, for example, IP address or URL. public let subResources: [SubResourceSummary]? public init(attackCounters: [SummarizedCounter]? = nil, attackId: String? = nil, attackProperties: [AttackProperty]? = nil, endTime: Date? = nil, mitigations: [Mitigation]? = nil, resourceArn: String? = nil, startTime: Date? = nil, subResources: [SubResourceSummary]? = nil) { self.attackCounters = attackCounters self.attackId = attackId self.attackProperties = attackProperties self.endTime = endTime self.mitigations = mitigations self.resourceArn = resourceArn self.startTime = startTime self.subResources = subResources } private enum CodingKeys: String, CodingKey { case attackCounters = "AttackCounters" case attackId = "AttackId" case attackProperties = "AttackProperties" case endTime = "EndTime" case mitigations = "Mitigations" case resourceArn = "ResourceArn" case startTime = "StartTime" case subResources = "SubResources" } } public struct AttackProperty: AWSDecodableShape { /// The type of distributed denial of service (DDoS) event that was observed. NETWORK indicates layer 3 and layer 4 events and APPLICATION indicates layer 7 events. public let attackLayer: AttackLayer? /// Defines the DDoS attack property information that is provided. The WORDPRESS_PINGBACK_REFLECTOR and WORDPRESS_PINGBACK_SOURCE values are valid only for WordPress reflective pingback DDoS attacks. public let attackPropertyIdentifier: AttackPropertyIdentifier? /// The array of Contributor objects that includes the top five contributors to an attack. public let topContributors: [Contributor]? /// The total contributions made to this attack by all contributors, not just the five listed in the TopContributors list. public let total: Int64? /// The unit of the Value of the contributions. public let unit: Unit? public init(attackLayer: AttackLayer? = nil, attackPropertyIdentifier: AttackPropertyIdentifier? = nil, topContributors: [Contributor]? = nil, total: Int64? = nil, unit: Unit? = nil) { self.attackLayer = attackLayer self.attackPropertyIdentifier = attackPropertyIdentifier self.topContributors = topContributors self.total = total self.unit = unit } private enum CodingKeys: String, CodingKey { case attackLayer = "AttackLayer" case attackPropertyIdentifier = "AttackPropertyIdentifier" case topContributors = "TopContributors" case total = "Total" case unit = "Unit" } } public struct AttackSummary: AWSDecodableShape { /// The unique identifier (ID) of the attack. public let attackId: String? /// The list of attacks for a specified time period. public let attackVectors: [AttackVectorDescription]? /// The end time of the attack, in Unix time in seconds. For more information see timestamp. public let endTime: Date? /// The ARN (Amazon Resource Name) of the resource that was attacked. public let resourceArn: String? /// The start time of the attack, in Unix time in seconds. For more information see timestamp. public let startTime: Date? public init(attackId: String? = nil, attackVectors: [AttackVectorDescription]? = nil, endTime: Date? = nil, resourceArn: String? = nil, startTime: Date? = nil) { self.attackId = attackId self.attackVectors = attackVectors self.endTime = endTime self.resourceArn = resourceArn self.startTime = startTime } private enum CodingKeys: String, CodingKey { case attackId = "AttackId" case attackVectors = "AttackVectors" case endTime = "EndTime" case resourceArn = "ResourceArn" case startTime = "StartTime" } } public struct AttackVectorDescription: AWSDecodableShape { /// The attack type. Valid values: UDP_TRAFFIC UDP_FRAGMENT GENERIC_UDP_REFLECTION DNS_REFLECTION NTP_REFLECTION CHARGEN_REFLECTION SSDP_REFLECTION PORT_MAPPER RIP_REFLECTION SNMP_REFLECTION MSSQL_REFLECTION NET_BIOS_REFLECTION SYN_FLOOD ACK_FLOOD REQUEST_FLOOD HTTP_REFLECTION UDS_REFLECTION MEMCACHED_REFLECTION public let vectorType: String public init(vectorType: String) { self.vectorType = vectorType } private enum CodingKeys: String, CodingKey { case vectorType = "VectorType" } } public struct Contributor: AWSDecodableShape { /// The name of the contributor. This is dependent on the AttackPropertyIdentifier. For example, if the AttackPropertyIdentifier is SOURCE_COUNTRY, the Name could be United States. public let name: String? /// The contribution of this contributor expressed in Protection units. For example 10,000. public let value: Int64? public init(name: String? = nil, value: Int64? = nil) { self.name = name self.value = value } private enum CodingKeys: String, CodingKey { case name = "Name" case value = "Value" } } public struct CreateProtectionRequest: AWSEncodableShape { /// Friendly name for the Protection you are creating. public let name: String /// The ARN (Amazon Resource Name) of the resource to be protected. The ARN should be in one of the following formats: For an Application Load Balancer: arn:aws:elasticloadbalancing:region:account-id:loadbalancer/app/load-balancer-name/load-balancer-id For an Elastic Load Balancer (Classic Load Balancer): arn:aws:elasticloadbalancing:region:account-id:loadbalancer/load-balancer-name For an AWS CloudFront distribution: arn:aws:cloudfront::account-id:distribution/distribution-id For an AWS Global Accelerator accelerator: arn:aws:globalaccelerator::account-id:accelerator/accelerator-id For Amazon Route 53: arn:aws:route53:::hostedzone/hosted-zone-id For an Elastic IP address: arn:aws:ec2:region:account-id:eip-allocation/allocation-id public let resourceArn: String public init(name: String, resourceArn: String) { self.name = name self.resourceArn = resourceArn } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 128) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[ a-zA-Z0-9_\\\\.\\\\-]*") try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1) try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws.*") } private enum CodingKeys: String, CodingKey { case name = "Name" case resourceArn = "ResourceArn" } } public struct CreateProtectionResponse: AWSDecodableShape { /// The unique identifier (ID) for the Protection object that is created. public let protectionId: String? public init(protectionId: String? = nil) { self.protectionId = protectionId } private enum CodingKeys: String, CodingKey { case protectionId = "ProtectionId" } } public struct CreateSubscriptionRequest: AWSEncodableShape { public init() {} } public struct CreateSubscriptionResponse: AWSDecodableShape { public init() {} } public struct DeleteProtectionRequest: AWSEncodableShape { /// The unique identifier (ID) for the Protection object to be deleted. public let protectionId: String public init(protectionId: String) { self.protectionId = protectionId } public func validate(name: String) throws { try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case protectionId = "ProtectionId" } } public struct DeleteProtectionResponse: AWSDecodableShape { public init() {} } public struct DeleteSubscriptionRequest: AWSEncodableShape { public init() {} } public struct DeleteSubscriptionResponse: AWSDecodableShape { public init() {} } public struct DescribeAttackRequest: AWSEncodableShape { /// The unique identifier (ID) for the attack that to be described. public let attackId: String public init(attackId: String) { self.attackId = attackId } public func validate(name: String) throws { try self.validate(self.attackId, name: "attackId", parent: name, max: 128) try self.validate(self.attackId, name: "attackId", parent: name, min: 1) try self.validate(self.attackId, name: "attackId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case attackId = "AttackId" } } public struct DescribeAttackResponse: AWSDecodableShape { /// The attack that is described. public let attack: AttackDetail? public init(attack: AttackDetail? = nil) { self.attack = attack } private enum CodingKeys: String, CodingKey { case attack = "Attack" } } public struct DescribeDRTAccessRequest: AWSEncodableShape { public init() {} } public struct DescribeDRTAccessResponse: AWSDecodableShape { /// The list of Amazon S3 buckets accessed by the DRT. public let logBucketList: [String]? /// The Amazon Resource Name (ARN) of the role the DRT used to access your AWS account. public let roleArn: String? public init(logBucketList: [String]? = nil, roleArn: String? = nil) { self.logBucketList = logBucketList self.roleArn = roleArn } private enum CodingKeys: String, CodingKey { case logBucketList = "LogBucketList" case roleArn = "RoleArn" } } public struct DescribeEmergencyContactSettingsRequest: AWSEncodableShape { public init() {} } public struct DescribeEmergencyContactSettingsResponse: AWSDecodableShape { /// A list of email addresses and phone numbers that the DDoS Response Team (DRT) can use to contact you if you have proactive engagement enabled, for escalations to the DRT and to initiate proactive customer support. public let emergencyContactList: [EmergencyContact]? public init(emergencyContactList: [EmergencyContact]? = nil) { self.emergencyContactList = emergencyContactList } private enum CodingKeys: String, CodingKey { case emergencyContactList = "EmergencyContactList" } } public struct DescribeProtectionRequest: AWSEncodableShape { /// The unique identifier (ID) for the Protection object that is described. When submitting the DescribeProtection request you must provide either the ResourceArn or the ProtectionID, but not both. public let protectionId: String? /// The ARN (Amazon Resource Name) of the AWS resource for the Protection object that is described. When submitting the DescribeProtection request you must provide either the ResourceArn or the ProtectionID, but not both. public let resourceArn: String? public init(protectionId: String? = nil, resourceArn: String? = nil) { self.protectionId = protectionId self.resourceArn = resourceArn } public func validate(name: String) throws { try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1) try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws.*") } private enum CodingKeys: String, CodingKey { case protectionId = "ProtectionId" case resourceArn = "ResourceArn" } } public struct DescribeProtectionResponse: AWSDecodableShape { /// The Protection object that is described. public let protection: Protection? public init(protection: Protection? = nil) { self.protection = protection } private enum CodingKeys: String, CodingKey { case protection = "Protection" } } public struct DescribeSubscriptionRequest: AWSEncodableShape { public init() {} } public struct DescribeSubscriptionResponse: AWSDecodableShape { /// The AWS Shield Advanced subscription details for an account. public let subscription: Subscription? public init(subscription: Subscription? = nil) { self.subscription = subscription } private enum CodingKeys: String, CodingKey { case subscription = "Subscription" } } public struct DisableProactiveEngagementRequest: AWSEncodableShape { public init() {} } public struct DisableProactiveEngagementResponse: AWSDecodableShape { public init() {} } public struct DisassociateDRTLogBucketRequest: AWSEncodableShape { /// The Amazon S3 bucket that contains your AWS WAF logs. public let logBucket: String public init(logBucket: String) { self.logBucket = logBucket } public func validate(name: String) throws { try self.validate(self.logBucket, name: "logBucket", parent: name, max: 63) try self.validate(self.logBucket, name: "logBucket", parent: name, min: 3) try self.validate(self.logBucket, name: "logBucket", parent: name, pattern: "^([a-z]|(\\d(?!\\d{0,2}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})))([a-z\\d]|(\\.(?!(\\.|-)))|(-(?!\\.))){1,61}[a-z\\d]$") } private enum CodingKeys: String, CodingKey { case logBucket = "LogBucket" } } public struct DisassociateDRTLogBucketResponse: AWSDecodableShape { public init() {} } public struct DisassociateDRTRoleRequest: AWSEncodableShape { public init() {} } public struct DisassociateDRTRoleResponse: AWSDecodableShape { public init() {} } public struct DisassociateHealthCheckRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the health check that is associated with the protection. public let healthCheckArn: String /// The unique identifier (ID) for the Protection object to remove the health check association from. public let protectionId: String public init(healthCheckArn: String, protectionId: String) { self.healthCheckArn = healthCheckArn self.protectionId = protectionId } public func validate(name: String) throws { try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, max: 2048) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, min: 1) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, pattern: "^arn:aws:route53:::healthcheck/\\S{36}$") try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case healthCheckArn = "HealthCheckArn" case protectionId = "ProtectionId" } } public struct DisassociateHealthCheckResponse: AWSDecodableShape { public init() {} } public struct EmergencyContact: AWSEncodableShape & AWSDecodableShape { /// Additional notes regarding the contact. public let contactNotes: String? /// The email address for the contact. public let emailAddress: String /// The phone number for the contact. public let phoneNumber: String? public init(contactNotes: String? = nil, emailAddress: String, phoneNumber: String? = nil) { self.contactNotes = contactNotes self.emailAddress = emailAddress self.phoneNumber = phoneNumber } public func validate(name: String) throws { try self.validate(self.contactNotes, name: "contactNotes", parent: name, max: 1024) try self.validate(self.contactNotes, name: "contactNotes", parent: name, min: 1) try self.validate(self.contactNotes, name: "contactNotes", parent: name, pattern: "^[\\w\\s\\.\\-,:/()+@]*$") try self.validate(self.emailAddress, name: "emailAddress", parent: name, max: 150) try self.validate(self.emailAddress, name: "emailAddress", parent: name, min: 1) try self.validate(self.emailAddress, name: "emailAddress", parent: name, pattern: "^\\S+@\\S+\\.\\S+$") try self.validate(self.phoneNumber, name: "phoneNumber", parent: name, max: 16) try self.validate(self.phoneNumber, name: "phoneNumber", parent: name, min: 1) try self.validate(self.phoneNumber, name: "phoneNumber", parent: name, pattern: "^\\+[1-9]\\d{1,14}$") } private enum CodingKeys: String, CodingKey { case contactNotes = "ContactNotes" case emailAddress = "EmailAddress" case phoneNumber = "PhoneNumber" } } public struct EnableProactiveEngagementRequest: AWSEncodableShape { public init() {} } public struct EnableProactiveEngagementResponse: AWSDecodableShape { public init() {} } public struct GetSubscriptionStateRequest: AWSEncodableShape { public init() {} } public struct GetSubscriptionStateResponse: AWSDecodableShape { /// The status of the subscription. public let subscriptionState: SubscriptionState public init(subscriptionState: SubscriptionState) { self.subscriptionState = subscriptionState } private enum CodingKeys: String, CodingKey { case subscriptionState = "SubscriptionState" } } public struct Limit: AWSDecodableShape { /// The maximum number of protections that can be created for the specified Type. public let max: Int64? /// The type of protection. public let type: String? public init(max: Int64? = nil, type: String? = nil) { self.max = max self.type = type } private enum CodingKeys: String, CodingKey { case max = "Max" case type = "Type" } } public struct ListAttacksRequest: AWSEncodableShape { /// The end of the time period for the attacks. This is a timestamp type. The sample request above indicates a number type because the default used by WAF is Unix time in seconds. However any valid timestamp format is allowed. public let endTime: TimeRange? /// The maximum number of AttackSummary objects to be returned. If this is left blank, the first 20 results will be returned. This is a maximum value; it is possible that AWS WAF will return the results in smaller batches. That is, the number of AttackSummary objects returned could be less than MaxResults, even if there are still more AttackSummary objects yet to return. If there are more AttackSummary objects to return, AWS WAF will always also return a NextToken. public let maxResults: Int? /// The ListAttacksRequest.NextMarker value from a previous call to ListAttacksRequest. Pass null if this is the first call. public let nextToken: String? /// The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources for this account will be included. public let resourceArns: [String]? /// The start of the time period for the attacks. This is a timestamp type. The sample request above indicates a number type because the default used by WAF is Unix time in seconds. However any valid timestamp format is allowed. public let startTime: TimeRange? public init(endTime: TimeRange? = nil, maxResults: Int? = nil, nextToken: String? = nil, resourceArns: [String]? = nil, startTime: TimeRange? = nil) { self.endTime = endTime self.maxResults = maxResults self.nextToken = nextToken self.resourceArns = resourceArns self.startTime = startTime } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10000) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 0) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 4096) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^.*$") try self.resourceArns?.forEach { try validate($0, name: "resourceArns[]", parent: name, max: 2048) try validate($0, name: "resourceArns[]", parent: name, min: 1) try validate($0, name: "resourceArns[]", parent: name, pattern: "^arn:aws.*") } } private enum CodingKeys: String, CodingKey { case endTime = "EndTime" case maxResults = "MaxResults" case nextToken = "NextToken" case resourceArns = "ResourceArns" case startTime = "StartTime" } } public struct ListAttacksResponse: AWSDecodableShape { /// The attack information for the specified time range. public let attackSummaries: [AttackSummary]? /// The token returned by a previous call to indicate that there is more data available. If not null, more results are available. Pass this value for the NextMarker parameter in a subsequent call to ListAttacks to retrieve the next set of items. AWS WAF might return the list of AttackSummary objects in batches smaller than the number specified by MaxResults. If there are more AttackSummary objects to return, AWS WAF will always also return a NextToken. public let nextToken: String? public init(attackSummaries: [AttackSummary]? = nil, nextToken: String? = nil) { self.attackSummaries = attackSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case attackSummaries = "AttackSummaries" case nextToken = "NextToken" } } public struct ListProtectionsRequest: AWSEncodableShape { /// The maximum number of Protection objects to be returned. If this is left blank the first 20 results will be returned. This is a maximum value; it is possible that AWS WAF will return the results in smaller batches. That is, the number of Protection objects returned could be less than MaxResults, even if there are still more Protection objects yet to return. If there are more Protection objects to return, AWS WAF will always also return a NextToken. public let maxResults: Int? /// The ListProtectionsRequest.NextToken value from a previous call to ListProtections. Pass null if this is the first call. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10000) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 0) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 4096) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^.*$") } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListProtectionsResponse: AWSDecodableShape { /// If you specify a value for MaxResults and you have more Protections than the value of MaxResults, AWS Shield Advanced returns a NextToken value in the response that allows you to list another group of Protections. For the second and subsequent ListProtections requests, specify the value of NextToken from the previous response to get information about another batch of Protections. AWS WAF might return the list of Protection objects in batches smaller than the number specified by MaxResults. If there are more Protection objects to return, AWS WAF will always also return a NextToken. public let nextToken: String? /// The array of enabled Protection objects. public let protections: [Protection]? public init(nextToken: String? = nil, protections: [Protection]? = nil) { self.nextToken = nextToken self.protections = protections } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case protections = "Protections" } } public struct Mitigation: AWSDecodableShape { /// The name of the mitigation taken for this attack. public let mitigationName: String? public init(mitigationName: String? = nil) { self.mitigationName = mitigationName } private enum CodingKeys: String, CodingKey { case mitigationName = "MitigationName" } } public struct Protection: AWSDecodableShape { /// The unique identifier (ID) for the Route 53 health check that's associated with the protection. public let healthCheckIds: [String]? /// The unique identifier (ID) of the protection. public let id: String? /// The friendly name of the protection. For example, My CloudFront distributions. public let name: String? /// The ARN (Amazon Resource Name) of the AWS resource that is protected. public let resourceArn: String? public init(healthCheckIds: [String]? = nil, id: String? = nil, name: String? = nil, resourceArn: String? = nil) { self.healthCheckIds = healthCheckIds self.id = id self.name = name self.resourceArn = resourceArn } private enum CodingKeys: String, CodingKey { case healthCheckIds = "HealthCheckIds" case id = "Id" case name = "Name" case resourceArn = "ResourceArn" } } public struct SubResourceSummary: AWSDecodableShape { /// The list of attack types and associated counters. public let attackVectors: [SummarizedAttackVector]? /// The counters that describe the details of the attack. public let counters: [SummarizedCounter]? /// The unique identifier (ID) of the SubResource. public let id: String? /// The SubResource type. public let type: SubResourceType? public init(attackVectors: [SummarizedAttackVector]? = nil, counters: [SummarizedCounter]? = nil, id: String? = nil, type: SubResourceType? = nil) { self.attackVectors = attackVectors self.counters = counters self.id = id self.type = type } private enum CodingKeys: String, CodingKey { case attackVectors = "AttackVectors" case counters = "Counters" case id = "Id" case type = "Type" } } public struct Subscription: AWSDecodableShape { /// If ENABLED, the subscription will be automatically renewed at the end of the existing subscription period. When you initally create a subscription, AutoRenew is set to ENABLED. You can change this by submitting an UpdateSubscription request. If the UpdateSubscription request does not included a value for AutoRenew, the existing value for AutoRenew remains unchanged. public let autoRenew: AutoRenew? /// The date and time your subscription will end. public let endTime: Date? /// Specifies how many protections of a given type you can create. public let limits: [Limit]? /// If ENABLED, the DDoS Response Team (DRT) will use email and phone to notify contacts about escalations to the DRT and to initiate proactive customer support. If PENDING, you have requested proactive engagement and the request is pending. The status changes to ENABLED when your request is fully processed. If DISABLED, the DRT will not proactively notify contacts about escalations or to initiate proactive customer support. public let proactiveEngagementStatus: ProactiveEngagementStatus? /// The start time of the subscription, in Unix time in seconds. For more information see timestamp. public let startTime: Date? /// The length, in seconds, of the AWS Shield Advanced subscription for the account. public let timeCommitmentInSeconds: Int64? public init(autoRenew: AutoRenew? = nil, endTime: Date? = nil, limits: [Limit]? = nil, proactiveEngagementStatus: ProactiveEngagementStatus? = nil, startTime: Date? = nil, timeCommitmentInSeconds: Int64? = nil) { self.autoRenew = autoRenew self.endTime = endTime self.limits = limits self.proactiveEngagementStatus = proactiveEngagementStatus self.startTime = startTime self.timeCommitmentInSeconds = timeCommitmentInSeconds } private enum CodingKeys: String, CodingKey { case autoRenew = "AutoRenew" case endTime = "EndTime" case limits = "Limits" case proactiveEngagementStatus = "ProactiveEngagementStatus" case startTime = "StartTime" case timeCommitmentInSeconds = "TimeCommitmentInSeconds" } } public struct SummarizedAttackVector: AWSDecodableShape { /// The list of counters that describe the details of the attack. public let vectorCounters: [SummarizedCounter]? /// The attack type, for example, SNMP reflection or SYN flood. public let vectorType: String public init(vectorCounters: [SummarizedCounter]? = nil, vectorType: String) { self.vectorCounters = vectorCounters self.vectorType = vectorType } private enum CodingKeys: String, CodingKey { case vectorCounters = "VectorCounters" case vectorType = "VectorType" } } public struct SummarizedCounter: AWSDecodableShape { /// The average value of the counter for a specified time period. public let average: Double? /// The maximum value of the counter for a specified time period. public let max: Double? /// The number of counters for a specified time period. public let n: Int? /// The counter name. public let name: String? /// The total of counter values for a specified time period. public let sum: Double? /// The unit of the counters. public let unit: String? public init(average: Double? = nil, max: Double? = nil, n: Int? = nil, name: String? = nil, sum: Double? = nil, unit: String? = nil) { self.average = average self.max = max self.n = n self.name = name self.sum = sum self.unit = unit } private enum CodingKeys: String, CodingKey { case average = "Average" case max = "Max" case n = "N" case name = "Name" case sum = "Sum" case unit = "Unit" } } public struct TimeRange: AWSEncodableShape { /// The start time, in Unix time in seconds. For more information see timestamp. public let fromInclusive: Date? /// The end time, in Unix time in seconds. For more information see timestamp. public let toExclusive: Date? public init(fromInclusive: Date? = nil, toExclusive: Date? = nil) { self.fromInclusive = fromInclusive self.toExclusive = toExclusive } private enum CodingKeys: String, CodingKey { case fromInclusive = "FromInclusive" case toExclusive = "ToExclusive" } } public struct UpdateEmergencyContactSettingsRequest: AWSEncodableShape { /// A list of email addresses and phone numbers that the DDoS Response Team (DRT) can use to contact you if you have proactive engagement enabled, for escalations to the DRT and to initiate proactive customer support. If you have proactive engagement enabled, the contact list must include at least one phone number. public let emergencyContactList: [EmergencyContact]? public init(emergencyContactList: [EmergencyContact]? = nil) { self.emergencyContactList = emergencyContactList } public func validate(name: String) throws { try self.emergencyContactList?.forEach { try $0.validate(name: "\(name).emergencyContactList[]") } try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, max: 10) try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case emergencyContactList = "EmergencyContactList" } } public struct UpdateEmergencyContactSettingsResponse: AWSDecodableShape { public init() {} } public struct UpdateSubscriptionRequest: AWSEncodableShape { /// When you initally create a subscription, AutoRenew is set to ENABLED. If ENABLED, the subscription will be automatically renewed at the end of the existing subscription period. You can change this by submitting an UpdateSubscription request. If the UpdateSubscription request does not included a value for AutoRenew, the existing value for AutoRenew remains unchanged. public let autoRenew: AutoRenew? public init(autoRenew: AutoRenew? = nil) { self.autoRenew = autoRenew } private enum CodingKeys: String, CodingKey { case autoRenew = "AutoRenew" } } public struct UpdateSubscriptionResponse: AWSDecodableShape { public init() {} } }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/21821-swift-metatypetype-get.swift
11
280
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c{ enum b { struct B enum a class C<T where B : T> : T { { { } { } { } } } { { } } func a<c> ( ) -> [Void
mit
vicentesuarez/TransitionManager
TransitionManagerDemo/TransitionManagerDemoUITests/TransitionManagerDemoUITests.swift
1
1292
// // TransitionManagerDemoUITests.swift // TransitionManagerDemoUITests // // Created by Vicente Suarez on 1/13/17. // Copyright © 2017 Vicente Suarez. All rights reserved. // import XCTest class TransitionManagerDemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/21696-llvm-tinyptrvector-swift-constraints-failure-push-back.swift
11
295
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class d<T " { func o { class B { S<T B ) T> var d = c<T -> Void> struct c typealias e = class B<T where I. : C { var f = A? {
mit
robertoseidenberg/MixerBox
MixerBox/HSBMetalView.swift
1
375
#if !(IOS_SIMULATOR) import Metal #endif class HSBMetalView: MetalView { var brightness: Float = 1 #if !(IOS_SIMULATOR) override func updateFragmentBytes(forEncoder encoder: MTLRenderCommandEncoder) { var u = HSBUniforms(size: bounds.size, brightness: brightness) encoder.setFragmentBytes(&u, length: MemoryLayout<HSBUniforms>.size, index: 0) } #endif }
mit
hawkfalcon/SpaceEvaders
SpaceEvaders/Powerup.swift
1
633
import SpriteKit var bombArray = Array<SKTexture>(); class Powerup: Sprite { init(x: CGFloat, y: CGFloat) { super.init(named: "powerup1", x: x, y: y) self.name = "powerup" self.setScale(1.5) self.alpha = 0 fire() } func fire() { for index in 1 ... 15 { bombArray.append(SKTexture(imageNamed: "powerup\(index)")) } let animateAction = SKAction.animate(with: bombArray, timePerFrame: 0.10); self.run(SKAction.repeatForever(animateAction)) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
jmieville/ToTheMoonAndBack-PitchPerfect
PitchPerfect/PlaySoundsViewController.swift
1
2162
// // PlaySoundsViewController.swift // PitchPerfect // // Created by Jean-Marc Kampol Mieville on 5/30/2559 BE. // Copyright © 2559 Jean-Marc Kampol Mieville. All rights reserved. // import AVFoundation import UIKit class PlaySoundsViewController: UIViewController { //Outlets @IBOutlet weak var snailButton: UIButton! @IBOutlet weak var rabbitButton: UIButton! @IBOutlet weak var chipmunkButton: UIButton! @IBOutlet weak var darthVaderButton: UIButton! @IBOutlet weak var echoButton: UIButton! @IBOutlet weak var revertButton: UIButton! @IBOutlet weak var stopButton: UIButton! var recordedAudioURL: NSURL! var audioFile: AVAudioFile! var audioEngine: AVAudioEngine! var audioPlayerNode: AVAudioPlayerNode! var stopTimer: Timer! enum ButtonType: Int { case Slow = 0, Fast, Chipmunk, Vader, Echo, Reverb } @IBAction func playSoundForButton(sender: UIButton) { print("Play Sound Button Pressed") switch(ButtonType(rawValue: sender.tag)!) { case .Slow: playSound(rate: 0.5) case .Fast: playSound(rate: 1.5) case .Chipmunk: playSound(pitch: 1000) case .Vader: playSound(pitch: -1000) case .Echo: playSound(echo: true) case .Reverb: playSound(reverb: true) } configureUI(playState: .Playing) } @IBAction func StopButtonPressed(sender: UIButton) { print("Stop Sound Button Pressed") stopAudio() } override func viewDidLoad() { super.viewDidLoad() print("PlaySoundsViewController loaded") setupAudio() } override func viewWillAppear(_ animated: Bool) { configureUI(playState: .NotPlaying) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "stopRecording") { let playSoundsVC = segue.destination as! PlaySoundsViewController let recordedAudioURL = sender as! NSURL playSoundsVC.recordedAudioURL = recordedAudioURL } } }
mit
Trioser/Calculator
Calculator/ViewController.swift
1
4171
// // ViewController.swift // Calculator // // Created by Richard E Millet on 1/28/15. // Copyright (c) 2015 remillet. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. history.text = "" display.text = "0.0" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // // My changes // let enterSymbol = "⏎" let memoryKey = "M" var activeTyping : Bool = false var calculatorBrain = CalculatorBrain() @IBOutlet weak var display: UILabel! @IBOutlet weak var history: UILabel! // Settable/Gettable aka "Computed" property private var displayValue : Double? { set { activeTyping = false if newValue == nil { display.text = " " } else { display.text = "\(newValue!)" } } get { return NSNumberFormatter().numberFromString(display.text!)?.doubleValue } } @IBAction func memorySet(sender: UIButton) { if let currentDisplayValue = displayValue { activeTyping = false calculatorBrain.setMemoryVariable(memoryKey, value: currentDisplayValue) displayValue = calculatorBrain.evaluate() } else { println("Current display value is not valid for memory set key.") } } @IBAction func memoryGet(sender: UIButton) { if activeTyping { enter(enterSymbol) } display.text = memoryKey enter(enterSymbol) } @IBAction func operate(sender: UIButton) { if activeTyping { enter(sender.currentTitle) } if let operatorString = sender.currentTitle { if let result = calculatorBrain.performOperation(operatorString) { displayValue = result } else { displayValue = nil } } history.text! = calculatorBrain.description } func doSort(nameList: Array<String>, operation: (String, String) -> Bool) -> Array<String> { var arraySize: Int = nameList.count var result = nameList var finished: Bool = false while (finished == false) { finished = true var index: Int = 0 while (index < arraySize - 1) { if (operation(result[index], result[index + 1])) { finished = false var swap = result[index] result[index] = result[index + 1] result[index + 1] = swap } index++ } } return result } @IBAction func appendDecimalPoint(sender: UIButton) { if (activeTyping == true) { if (display.text!.rangeOfString(".") == nil) { display.text = display.text! + "." } } else { display.text = "0." activeTyping = true } } // // An example sort routine showing closure syntax // @IBAction func arraySort() { let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] println("Unsorted: \(names)") let sortedNames = doSort(names, {return $0 > $1}) // equvalent of {(s1: String, s2: String) -> Bool in s2 > s1} println("Sorted: \(sortedNames)") let reverseSortedName = doSort(names, {return $1 > $0}) // {(s1: String, s2: String) -> Bool in s2 > s1}) println("Reverse sorted: \(reverseSortedName)") } @IBAction func appendPi(sender: UIButton) { if activeTyping { enter(enterSymbol) } display.text = piSymbol enter(enterSymbol) } @IBAction func clearEntry(sender: UIButton) { displayValue = 0 } @IBAction func clear(sender: UIButton) { displayValue = 0 history.text = "" calculatorBrain.clear() } @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! println("digit = \(digit)") if (activeTyping == true) { display.text = display.text! + digit } else { display.text = digit activeTyping = true } } @IBAction func enter(sender: UIButton) { enter(sender.currentTitle) } private func enter(op: String?) { // history.text! += display.text! // // if let historyOp = op { // history.text! += historyOp // } activeTyping = false if let operand = displayValue { displayValue = calculatorBrain.pushOperand(displayValue) } else { displayValue = calculatorBrain.pushOperand(display.text!) } history.text! = calculatorBrain.description } }
apache-2.0
ihomway/RayWenderlichCourses
Advanced Swift 3/Advanced Swift 3.playground/Pages/Protocols and Generics Challenge.xcplaygroundpage/Contents.swift
1
2283
//: [Previous](@previous) import Foundation // Challenge // // Inventory contains an array of different models that conform // to the Item protocol. Make all of the necessary changes to // the Item protocol and Inventory to make Inventory Equatable. // // Test it out by uncommenting the code below. protocol Item { var name: String { get } var weight: Int { get } func isEqual(to another:Item) -> Bool } extension Item { func isEqual(to another:Item) -> Bool { return name == another.name && weight == another.weight } } struct Inventory: Equatable { var items: [Item] static func ==(lhs: Inventory, rhs: Inventory) -> Bool { return lhs.items.count == rhs.items.count && !zip(lhs.items, rhs.items).contains(where: { let (item1, item2) = $0 return !item1.isEqual(to: item2) }) } } struct Armor: Item, Equatable { let name: String let weight: Int let armorClass: Int static func ==(lhs: Armor, rhs: Armor) -> Bool { return lhs.name == rhs.name && lhs.weight == rhs.weight && lhs.armorClass == rhs.armorClass } } struct Weapon: Item, Equatable { let name: String let weight: Int let damage: Int static func ==(lhs: Weapon, rhs: Weapon) -> Bool { return lhs.name == rhs.name && lhs.weight == rhs.weight && lhs.damage == rhs.damage } } struct Scroll: Item, Equatable { let name: String var weight: Int { return 1 } let magicWord: String static func ==(lhs: Scroll, rhs: Scroll) -> Bool { return lhs.name == rhs.name && lhs.magicWord == rhs.magicWord } } // Test code var tankEquipment = Inventory(items: [Armor(name: "Plate", weight: 180, armorClass: 2), Weapon(name: "Sword", weight: 20, damage: 30)]) var rogueEquipment = Inventory(items: [Armor(name: "Leather", weight: 40, armorClass: 7), Weapon(name: "Dagger", weight: 5, damage: 7)]) var wizardEquipment = Inventory(items: [Weapon(name: "Dagger", weight: 5, damage: 7), Scroll(name: "Create Water", magicWord: "Mizu!"), Scroll(name: "Vortex of Teeth", magicWord: "Sakana!"), Scroll(name: "Fireball", magicWord: "Utte!")]) tankEquipment == tankEquipment wizardEquipment == wizardEquipment tankEquipment != wizardEquipment tankEquipment != rogueEquipment tankEquipment == wizardEquipment tankEquipment == rogueEquipment //: [Next](@next)
mit
wolf81/Nimbl3Survey
Nimbl3Survey/PageIndicatorView.swift
1
6542
// // PageIndicatorView.swift // Nimbl3Survey // // Created by Wolfgang Schreurs on 24/03/2017. // Copyright © 2017 Wolftrail. All rights reserved. // import UIKit import GLKit protocol PageIndicatorViewDelegate: class { func pageIndicatorViewNavigateNextAction(_ view: PageIndicatorView) func pageIndicatorViewNavigatePreviousAction(_ view: PageIndicatorView) func pageIndicatorView(_ view: PageIndicatorView, touchedIndicatorAtIndex index: Int) } class PageIndicatorView: UIControl { private let horizontalMargin: CGFloat = 2 var animationDuration: TimeInterval = 0.2 weak var delegate: PageIndicatorViewDelegate? private var indicatorTouchRects = [CGRect]() // MARK: - Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } private func commonInit() { self.backgroundColor = UIColor(white: 0, alpha: 0) self.layer.masksToBounds = true } // MARK: - Properties override var frame: CGRect { didSet { self.layer.cornerRadius = fmin(bounds.width / 2, 10) } } var count: Int = NSNotFound { didSet { self.index = 0 setNeedsDisplay() } } var index: Int = NSNotFound { didSet { setNeedsDisplay() UIView.transition(with: self, duration: 0.2, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.layer.displayIfNeeded() }, completion: nil) } } var indicatorColor: UIColor = UIColor.white { didSet { setNeedsDisplay() } } var lineWidth: CGFloat = 2 { didSet { setNeedsDisplay() } } var verticalMargin: CGFloat = 10 { didSet { setNeedsDisplay() } } // MARK: - Drawing override func draw(_ rect: CGRect) { guard self.count != NSNotFound else { return } guard let ctx = UIGraphicsGetCurrentContext() else { return } ctx.saveGState() ctx.clear(rect) let highlighted = (self.isSelected || self.isHighlighted) if highlighted { let backgroundColor = UIColor(white: 0, alpha: 0.5) ctx.setFillColor(backgroundColor.cgColor) ctx.fill(rect) } let foregroundColor = highlighted ? self.indicatorColor.withAlphaComponent(0.5) : self.indicatorColor ctx.setFillColor(foregroundColor.cgColor) ctx.setStrokeColor(foregroundColor.cgColor) ctx.setLineWidth(self.lineWidth) let x: CGFloat = (rect.origin.x + (rect.width / 2)) let r: CGFloat = (rect.width / 2) - lineWidth - self.horizontalMargin let h = (rect.width - lineWidth - (self.horizontalMargin * 2)) let totalHeight = CGFloat(self.count) * h + fmax(CGFloat((self.count - 1)), CGFloat(0)) * verticalMargin var y: CGFloat = (rect.origin.y + rect.size.height / 2) - (totalHeight / 2) + h / 2 for i in (0 ..< count) { let origin = CGPoint(x: x, y: y) let fill = (i == self.index) drawCircleInContext(ctx, atOrigin: origin, withRadius: r, fill: fill) let touchRect = touchRectForCircleAtOrigin(origin, withRadius: r, inRect: rect) self.indicatorTouchRects.append(touchRect) y += (h + verticalMargin) } ctx.restoreGState() } // MARK: - Layout override func sizeThatFits(_ size: CGSize) -> CGSize { let width = min(16 + (self.horizontalMargin * 2), size.width) return CGSize(width: width, height: size.height) } // MARK: - State changes override var isSelected: Bool { didSet { setNeedsDisplay() UIView.transition(with: self, duration: self.animationDuration, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.layer.displayIfNeeded() }, completion: nil) } } override var isHighlighted: Bool { didSet { setNeedsDisplay() UIView.transition(with: self, duration: self.animationDuration, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.layer.displayIfNeeded() }, completion: nil) } } // MARK: - User interaction override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) guard let touch = touches.first else { return } let point = touch.location(in: self) if let touchedRect = (self.indicatorTouchRects.filter { $0.contains(point) }).first { if let index = self.indicatorTouchRects.index(of: touchedRect) { self.delegate?.pageIndicatorView(self, touchedIndicatorAtIndex: index) } } else { if point.y > (self.indicatorTouchRects.first?.minY)! { self.delegate?.pageIndicatorViewNavigatePreviousAction(self) } else if point.y < (self.indicatorTouchRects.last?.maxY)! { self.delegate?.pageIndicatorViewNavigateNextAction(self) } } } // MARK: - Private private func touchRectForCircleAtOrigin(_ origin: CGPoint, withRadius radius: CGFloat, inRect rect: CGRect) -> CGRect { let yOffset = (self.verticalMargin / 2) + self.lineWidth var touchRect = CGRect() touchRect.origin.y = origin.y - radius - yOffset touchRect.origin.x = 0 touchRect.size.height = (radius * 2) + (yOffset * 2) touchRect.size.width = rect.width return touchRect } private func drawCircleInContext(_ ctx: CGContext, atOrigin origin: CGPoint, withRadius radius: CGFloat, fill: Bool) { let endAngle = CGFloat(GLKMathDegreesToRadians(360)) ctx.addArc(center: origin, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true) if fill { ctx.drawPath(using: .fillStroke) } else { ctx.strokePath() } } }
bsd-2-clause
wuyezhiguhun/DDSwift
DDSwift/百思不得姐/Main/View/DDBsbdjTabBar.swift
1
2548
// // DDBsbdjTabBar.swift // DDSwift // // Created by yutongmac on 2017/7/6. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class DDBsbdjTabBar: UITabBar { override func layoutSubviews() { super.layoutSubviews() let btnW = self.frame.size.width / (CGFloat)((self.items?.count)! + 1) let btnH = self.frame.size.height var x: Float = 0.0 var i = 0 for tabBarBtn in self.subviews { if tabBarBtn.isKind(of: NSClassFromString("UITabBarButton")!) { if i == 0 && _previousClickedTabBarBtn == nil { _previousClickedTabBarBtn = tabBarBtn as? UIControl } if i == 2 { i = i + 1 } x = Float(i) * Float(btnW) tabBarBtn.frame = CGRect(x: CGFloat(x), y: 0.0, width: btnW, height: btnH) i = i + 1 } } self.publishButton.center = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.5) } func publishButtonClick() -> Void { let publishView = DDBsbdjPublishView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)) UIApplication.shared.keyWindow?.addSubview(publishView) publishView.frame = (UIApplication.shared.keyWindow?.bounds)! } var _publishButton : UIButton? var publishButton : UIButton { get { if _publishButton == nil { _publishButton = UIButton(type: UIButtonType.custom) _publishButton?.setImage(UIImage(named: "tabBar_publish_icon"), for: UIControlState.normal) _publishButton?.setImage(UIImage(named: "tabBar_publish_click_icon"), for: UIControlState.highlighted) _publishButton?.sizeToFit() _publishButton?.addTarget(self, action: #selector(publishButtonClick), for: UIControlEvents.touchUpInside) self.addSubview(_publishButton!) } return _publishButton! } set { _publishButton = publishButton } } var _previousClickedTabBarBtn : UIControl? var previousClickedTabBarBtn : UIControl { get { if _previousClickedTabBarBtn == nil { _previousClickedTabBarBtn = UIControl() } return _previousClickedTabBarBtn! } set { _previousClickedTabBarBtn = previousClickedTabBarBtn } } }
mit
zhangchn/swelly
swelly/ViewController.swift
1
6187
// // ViewController.swift // swelly // // Created by ZhangChen on 05/10/2016. // // import Cocoa class ViewController: NSViewController { @IBOutlet weak var termView : TermView! @IBOutlet weak var connectButton : NSButton! @IBOutlet weak var siteAddressField: NSTextField! @IBOutlet weak var newConnectionView: NSView! var site : Site = Site() var windowDelegate = MainWindowDelegate() var idleTimer: Timer! var reconnectTimer: Timer! weak var currentConnectionViewController : ConnectionViewController? override func viewWillAppear() { super.viewWillAppear() termView.adjustFonts() } override func viewDidAppear() { super.viewDidAppear() self.view.window?.makeFirstResponder(termView) self.view.window?.delegate = windowDelegate self.view.window?.isReleasedWhenClosed = false self.view.window?.backgroundColor = .black let identifier = "login-segue" if (!self.termView.connected) { self.performSegue(withIdentifier: identifier, sender: self) } // let newConnectionAlert = NSAlert(error: NSError(domain: "", code: 0, userInfo: nil)) // newConnectionAlert.alertStyle = .informational // newConnectionAlert.accessoryView = newConnectionView // newConnectionAlert.messageText = "Connect to BBS..." // newConnectionAlert.icon = nil // newConnectionAlert.beginSheetModal(for: self.view.window!) { (resp: NSApplication.ModalResponse) in // self.performSegue(withIdentifier: NSStoryboard.SegueIdentifier.init("login-segue"), sender: self) // } } override func viewDidLoad() { super.viewDidLoad() windowDelegate.controller = self idleTimer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self](timer) in self?.termView?.connection?.sendAntiIdle() } } deinit { idleTimer.invalidate() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } var connectObserver : AnyObject? var disconnectObserver: AnyObject? func connectTo(site address:String, as user: String, using protoc: ConnectionProtocol) { site.address = address site.connectionProtocol = protoc let connection = Connection(site: site) connection.userName = user connection.setup() let term = Terminal() term.delegate = termView connection.terminal = term termView.connection = connection connectObserver = NotificationCenter.default.addObserver(forName: .connectionDidConnect, object: connection, queue: .main) { [weak self] (note) in if let self = self, let connWindow = self.currentConnectionViewController?.view.window { self.view.window?.endSheet(connWindow) } } disconnectObserver = NotificationCenter.default.addObserver(forName: .connectionDidDisconnect, object: connection, queue: .main) { [weak self](note) in if let ob1 = self?.connectObserver { NotificationCenter.default.removeObserver(ob1) } if let ob2 = self?.disconnectObserver { NotificationCenter.default.removeObserver(ob2) } if let vc = self?.currentConnectionViewController { vc.resetUI() } else { let identifier = "login-segue" self?.performSegue(withIdentifier: identifier, sender: self!) } } } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if (segue.identifier ?? "") == "login-segue" { if let vc = segue.destinationController as? ConnectionViewController { vc.terminalViewController = self currentConnectionViewController = vc } } } @IBOutlet var leadingConstraint: NSLayoutConstraint! @IBOutlet var trailingConstraint: NSLayoutConstraint! @IBOutlet var aspectConstraint: NSLayoutConstraint! func disableConstraintsForFullScreen() { aspectConstraint.isActive = false } func enableConstraintsFromFullScreen() { aspectConstraint.isActive = true } } class MainWindowDelegate: NSObject, NSWindowDelegate { weak var controller: ViewController! /* func windowShouldClose(_ sender: NSWindow) -> Bool { sender.setIsVisible(false) return false } */ func windowWillEnterFullScreen(_ notification: Notification) { controller.disableConstraintsForFullScreen() } func windowWillExitFullScreen(_ notification: Notification) { controller.enableConstraintsFromFullScreen() } } class ConnectionViewController : NSViewController { weak var terminalViewController: ViewController! @IBOutlet weak var addressField: NSTextField! @IBOutlet weak var userNameField: NSTextField! @IBOutlet weak var connectionTypeControl: NSSegmentedControl! @IBOutlet weak var confirmButton: NSButton! @IBOutlet weak var cancelButton: NSButton! override func viewDidLoad() { self.userNameField.stringValue = (NSApp.delegate as! AppDelegate).username ?? "" self.addressField.stringValue = (NSApp.delegate as! AppDelegate).site ?? "" } @IBAction func didPressConnect(_ sender: Any) { self.confirmButton.title = "Connecting" self.confirmButton.isEnabled = false (NSApp.delegate as! AppDelegate).username = self.userNameField.stringValue (NSApp.delegate as! AppDelegate).site = self.addressField.stringValue terminalViewController.connectTo(site: addressField.stringValue, as: userNameField.stringValue, using: connectionTypeControl.selectedSegment == 0 ? .telnet : .ssh) } func resetUI() { self.confirmButton.title = "Connect" self.confirmButton.isEnabled = true } @IBAction func didPressCancel(_ sender: Any) { terminalViewController.view.window?.endSheet(view.window!) } }
gpl-2.0
eugeneego/utilities-ios
Sources/Network/Http/Serializers/JsonHttpSerializer.swift
1
1198
// // JsonHttpSerializer // Legacy // // Copyright (c) 2015 Eugene Egorov. // License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE // import Foundation public enum JsonHttpSerializerError: Error { case serialization(Error) case deserialization(Error) } public struct JsonHttpSerializer: HttpSerializer { public typealias Value = Any public typealias Error = JsonHttpSerializerError public let contentType: String = "application/json" public init() {} public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { guard let value = value else { return .success(Data()) } return Result( catching: { try JSONSerialization.data(withJSONObject: value, options: []) }, unknown: { .error(Error.serialization($0)) } ) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { guard let data = data, !data.isEmpty else { return .success([:]) } return Result( catching: { try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) }, unknown: { .error(Error.deserialization($0)) } ) } }
mit
kingcos/Swift-X-Algorithms
LeetCode/035-Search-Insert-Position/035-Search-Insert-Position.playground/Contents.swift
1
750
import UIKit class Solution_1 { // 44 ms func searchInsert(_ nums: [Int], _ target: Int) -> Int { if let index = nums.firstIndex(of: target) { return index } var nums = nums nums.append(target) return nums.sorted().firstIndex(of: target) ?? 0 } } class Solution_2 { // 40 ms func searchInsert(_ nums: [Int], _ target: Int) -> Int { if let last = nums.last, last < target { return nums.count } for i in 0..<nums.count-1 { if nums[i] == target { return i } if target >= nums[i] && target <= nums[i+1] { return i + 1 } } return 0 } }
mit
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/ReferrerStatsRecordValueTests.swift
1
3739
import XCTest @testable import WordPress class ReferrerStatsRecordValueTests: StatsTestCase { func testCreation() { let parent = createStatsRecord(in: mainContext, type: .referrers, period: .week, date: Date()) let referrer = ReferrerStatsRecordValue(parent: parent) referrer.label = "test" referrer.viewsCount = 9001 XCTAssertNoThrow(try mainContext.save()) let fr = StatsRecord.fetchRequest(for: .referrers, on: Date(), periodType: .week) let results = try! mainContext.fetch(fr) XCTAssertEqual(results.count, 1) XCTAssertEqual(results.first!.values?.count, 1) let fetchedReferrer = results.first?.values?.firstObject! as! ReferrerStatsRecordValue XCTAssertEqual(fetchedReferrer.label, referrer.label) XCTAssertEqual(fetchedReferrer.viewsCount, referrer.viewsCount) } func testChildrenRelationships() { let parent = createStatsRecord(in: mainContext, type: .referrers, period: .week, date: Date()) let referer = ReferrerStatsRecordValue(parent: parent) referer.label = "parent" referer.viewsCount = 5000 let child = ReferrerStatsRecordValue(context: mainContext) child.label = "child" child.viewsCount = 4000 let child2 = ReferrerStatsRecordValue(context: mainContext) child2.label = "child2" child2.viewsCount = 1 referer.addToChildren([child, child2]) XCTAssertNoThrow(try mainContext.save()) let fr = StatsRecord.fetchRequest(for: .referrers, on: Date(), periodType: .week) let results = try! mainContext.fetch(fr) XCTAssertEqual(results.count, 1) XCTAssertEqual(results.first!.values?.count, 1) let fetchedReferer = results.first?.values?.firstObject! as! ReferrerStatsRecordValue XCTAssertEqual(fetchedReferer.label, referer.label) let children = fetchedReferer.children?.array as? [ReferrerStatsRecordValue] XCTAssertNotNil(children) XCTAssertEqual(children!.count, 2) XCTAssertEqual(children!.first!.label, child.label) XCTAssertEqual(children![1].label, child2.label) XCTAssertEqual(9001, fetchedReferer.viewsCount + children!.first!.viewsCount + children![1].viewsCount) } func testURLConversionWorks() { let parent = createStatsRecord(in: mainContext, type: .referrers, period: .week, date: Date()) let referer = ReferrerStatsRecordValue(parent: parent) referer.label = "test" referer.viewsCount = 5000 referer.urlString = "www.wordpress.com" parent.addToValues(referer) XCTAssertNoThrow(try mainContext.save()) let fetchRequest = StatsRecord.fetchRequest(for: .referrers, on: Date(), periodType: .week) let result = try! mainContext.fetch(fetchRequest) let fetchedValue = result.first!.values!.firstObject as! ReferrerStatsRecordValue XCTAssertNotNil(fetchedValue.referrerURL) } func testIconURLConversionWorks() { let parent = createStatsRecord(in: mainContext, type: .referrers, period: .week, date: Date()) let referer = ReferrerStatsRecordValue(parent: parent) referer.label = "test" referer.viewsCount = 5000 referer.iconURLString = "www.wordpress.com" parent.addToValues(referer) XCTAssertNoThrow(try mainContext.save()) let fetchRequest = StatsRecord.fetchRequest(for: .referrers, on: Date(), periodType: .week) let result = try! mainContext.fetch(fetchRequest) let fetchedValue = result.first!.values!.firstObject as! ReferrerStatsRecordValue XCTAssertNotNil(fetchedValue.iconURL) } }
gpl-2.0
araustin/udacity-meme-me
Meme Me/MemeCollectionViewCell.swift
1
397
// // MemeCollectionViewItem.swift // Meme Me // // Created by Ra Ra Ra on 4/21/15. // Copyright (c) 2015 Russell Austin. All rights reserved. // import UIKit /// MemeCollectionViewCell represents a cell in the sent memes collection view class MemeCollectionViewCell: UICollectionViewCell { @IBOutlet weak var memeImageView: UIImageView! @IBOutlet weak var deleteButton: UIButton! }
mit
CedricEugeni/CircleProgressView
CircleProgressViewTests/CircleProgressViewTests.swift
1
1014
// // CircleProgressViewTests.swift // CircleProgressViewTests // // Created by Cédric Eugeni on 22/04/2017. // Copyright © 2017 cedric. All rights reserved. // import XCTest @testable import CircleProgressView class CircleProgressViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
chinlam91/edx-app-ios
Source/NetworkManager.swift
2
11715
// // CourseOutline.swift // edX // // Created by Jake Lim on 5/09/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" case PATCH = "PATCH" } public enum RequestBody { case JSONBody(JSON) case DataBody(data : NSData, contentType : String) case EmptyBody } public enum ResponseDeserializer<Out> { case JSONResponse((NSHTTPURLResponse, JSON) -> Result<Out>) case DataResponse((NSHTTPURLResponse, NSData) -> Result<Out>) case NoContent(NSHTTPURLResponse -> Result<Out>) } public struct NetworkRequest<Out> { let method : HTTPMethod let path : String // Absolute URL or URL relative to the API base let requiresAuth : Bool let body : RequestBody let query: [String:JSON] let deserializer : ResponseDeserializer<Out> public init(method : HTTPMethod, path : String, requiresAuth : Bool = false, body : RequestBody = .EmptyBody, query : [String:JSON] = [:], deserializer : ResponseDeserializer<Out>) { self.method = method self.path = path self.requiresAuth = requiresAuth self.body = body self.query = query self.deserializer = deserializer } //Apparently swift doesn't allow a computed property in a struct func pageSize() -> Int? { if let pageSize = query["page_size"] { return pageSize.intValue } else { return nil } } } extension NetworkRequest: CustomDebugStringConvertible { public var debugDescription: String { return "\(_stdlib_getDemangledTypeName(self.dynamicType)) {\(method):\(path)}" } } public struct NetworkResult<Out> { public let request: NSURLRequest? public let response: NSHTTPURLResponse? public let data: Out? public let baseData : NSData? public let error: NSError? public init(request : NSURLRequest?, response : NSHTTPURLResponse?, data : Out?, baseData : NSData?, error : NSError?) { self.request = request self.response = response self.data = data self.error = error self.baseData = baseData } } public class NetworkTask : Removable { let request : Request private init(request : Request) { self.request = request } public func remove() { request.cancel() } } @objc public protocol AuthorizationHeaderProvider { var authorizationHeaders : [String:String] { get } } public class NetworkManager : NSObject { public typealias JSONInterceptor = (response : NSHTTPURLResponse, json : JSON) -> Result<JSON> private let authorizationHeaderProvider: AuthorizationHeaderProvider? private let baseURL : NSURL private let cache : ResponseCache private var jsonInterceptors : [JSONInterceptor] = [] public init(authorizationHeaderProvider: AuthorizationHeaderProvider? = nil, baseURL : NSURL, cache : ResponseCache) { self.authorizationHeaderProvider = authorizationHeaderProvider self.baseURL = baseURL self.cache = cache } /// Allows you to add a processing pass to any JSON response. /// Typically used to check for errors that can be sent by any request public func addJSONInterceptor(interceptor : (response : NSHTTPURLResponse, json : JSON) -> Result<JSON>) { jsonInterceptors.append(interceptor) } public func URLRequestWithRequest<Out>(request : NetworkRequest<Out>) -> Result<NSURLRequest> { return NSURL(string: request.path, relativeToURL: baseURL).toResult().flatMap { url -> Result<NSURLRequest> in let URLRequest = NSURLRequest(URL: url) if request.query.count == 0 { return Success(URLRequest) } var queryParams : [String:String] = [:] for (key, value) in request.query { if let stringValue = value.rawString(options : NSJSONWritingOptions()) { queryParams[key] = stringValue } } // Alamofire has a kind of contorted API where you can encode parameters over URLs // or through the POST body, but you can't do both at the same time. // // So first we encode the get parameters let (paramRequest, error) = ParameterEncoding.URL.encode(URLRequest, parameters: queryParams) if let error = error { return Failure(error) } else { return Success(paramRequest) } } .flatMap { URLRequest in let mutableURLRequest = URLRequest.mutableCopy() as! NSMutableURLRequest if request.requiresAuth { for (key, value) in self.authorizationHeaderProvider?.authorizationHeaders ?? [:] { mutableURLRequest.setValue(value, forHTTPHeaderField: key) } } mutableURLRequest.HTTPMethod = request.method.rawValue // Now we encode the body switch request.body { case .EmptyBody: return Success(mutableURLRequest) case let .DataBody(data: data, contentType: contentType): mutableURLRequest.HTTPBody = data mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") return Success(mutableURLRequest) case let .JSONBody(json): let (bodyRequest, error) = ParameterEncoding.JSON.encode(mutableURLRequest, parameters: json.dictionaryObject ?? [:]) if let error = error { return Failure(error) } else { return Success(bodyRequest) } } } } private static func deserialize<Out>(deserializer : ResponseDeserializer<Out>, interceptors : [JSONInterceptor], response : NSHTTPURLResponse?, data : NSData?) -> Result<Out> { if let response = response { switch deserializer { case let .JSONResponse(f): if let data = data, raw : AnyObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) { let json = JSON(raw) let result = interceptors.reduce(Success(json)) {(current : Result<JSON>, interceptor : (response : NSHTTPURLResponse, json : JSON) -> Result<JSON>) -> Result<JSON> in return current.flatMap {interceptor(response : response, json: $0)} } return result.flatMap { return f(response, $0) } } else { return Failure(NSError.oex_unknownError()) } case let .DataResponse(f): return data.toResult().flatMap { f(response, $0) } case let .NoContent(f): return f(response) } } else { return Failure() } } public func taskForRequest<Out>(request : NetworkRequest<Out>, handler: NetworkResult<Out> -> Void) -> Removable { let URLRequest = URLRequestWithRequest(request) let interceptors = jsonInterceptors let task = URLRequest.map {URLRequest -> NetworkTask in let task = Manager.sharedInstance.request(URLRequest) let serializer = { (URLRequest : NSURLRequest, response : NSHTTPURLResponse?, data : NSData?) -> (AnyObject?, NSError?) in let result = NetworkManager.deserialize(request.deserializer, interceptors: interceptors, response: response, data: data) return (Box((value : result.value, original : data)), result.error) } task.response(serializer: serializer) { (request, response, object, error) in let parsed = (object as? Box<(value : Out?, original : NSData?)>)?.value let result = NetworkResult<Out>(request: request, response: response, data: parsed?.value, baseData: parsed?.original, error: error) handler(result) } task.resume() return NetworkTask(request: task) } switch task { case let .Success(t): return t.value case let .Failure(error): dispatch_async(dispatch_get_main_queue()) { handler(NetworkResult(request: nil, response: nil, data: nil, baseData : nil, error: error)) } return BlockRemovable {} } } private func combineWithPersistentCacheFetch<Out>(stream : Stream<Out>, request : NetworkRequest<Out>) -> Stream<Out> { if let URLRequest = URLRequestWithRequest(request).value { let cacheStream = Sink<Out>() let interceptors = jsonInterceptors cache.fetchCacheEntryWithRequest(URLRequest, completion: {(entry : ResponseCacheEntry?) -> Void in if let entry = entry { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {[weak cacheStream] in let result = NetworkManager.deserialize(request.deserializer, interceptors: interceptors, response: entry.response, data: entry.data) dispatch_async(dispatch_get_main_queue()) {[weak cacheStream] in cacheStream?.close() cacheStream?.send(result) } }) } else { cacheStream.close() } }) return stream.cachedByStream(cacheStream) } else { return stream } } public func streamForRequest<Out>(request : NetworkRequest<Out>, persistResponse : Bool = false, autoCancel : Bool = true) -> Stream<Out> { let stream = Sink<NetworkResult<Out>>() let task = self.taskForRequest(request) {[weak stream, weak self] result in if let response = result.response, request = result.request where persistResponse { self?.cache.setCacheResponse(response, withData: result.baseData, forRequest: request, completion: nil) } stream?.close() stream?.send(result) } var result : Stream<Out> = stream.flatMap {(result : NetworkResult<Out>) -> Result<Out> in return result.data.toResult(result.error) } if persistResponse { result = combineWithPersistentCacheFetch(result, request: request) } if autoCancel { result = result.autoCancel(task) } return result } } extension NetworkManager { func addStandardInterceptors() { addJSONInterceptor { (response, json) -> Result<JSON> in if let statusCode = OEXHTTPStatusCode(rawValue: response.statusCode) where statusCode.is4xx { if json["has_access"].bool == false { let access = OEXCoursewareAccess(dictionary : json.dictionaryObject) return Failure(OEXCoursewareAccessError(coursewareAccess: access, displayInfo: nil)) } return Success(json) } else { return Success(json) } } } }
apache-2.0
Virpik/T
src/UI/[UIColor]/[UIColor][T][Components].swift
1
766
// // [UIColor][T][Components].swift // T // // Created by Virpik on 19/02/2018. // import Foundation public extension UIColor { // public typealias RGBAComponents = UIColor.RGBAComponents } public extension UIColor { // public typealias RGBAComponents = UIColor.RGBAComponents public var rgbaComponents: RGBAComponents { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return RGBAComponents(r: r, g: g, b: b, a: a) } public convenience init(_ components: RGBAComponents) { self.init(red: components.r, green: components.g, blue: components.b, alpha: components.a) } }
mit
sopinetchat/SopinetChat-iOS
Pod/Factories/SChatAvatarImageFactory.swift
1
6935
// // SChatAvatarImageFactory.swift // Pods // // Created by David Moreno Lora on 22/5/16. // // import Foundation public class SChatAvatarImageFactory: NSObject { // MARK: Public public static func avatarImageWithPlaceholder(placeholderImage: UIImage, diameter: UInt) -> SChatAvatarImage { let circlePlaceholderImage = SChatAvatarImageFactory.sChatCircularImage(placeholderImage, withDiameter: diameter, highlightedColor: nil) return SChatAvatarImage.avatarImageWithPlaceholder(circlePlaceholderImage) } public static func avatarImageWithImage(image: UIImage, diameter: UInt) -> SChatAvatarImage { let avatar = SChatAvatarImageFactory.circularAvatarImage(image, withDiameter: diameter) let highlightedAvatar = SChatAvatarImageFactory.circularAvatarHighlightedImage(image, withDiameter: diameter) return SChatAvatarImage(avatarImage: avatar, highlightedImage: highlightedAvatar, placeholderImage: avatar) } public static func circularAvatarImage(image: UIImage, withDiameter diameter: UInt) -> UIImage { return SChatAvatarImageFactory.sChatCircularImage(image, withDiameter: diameter, highlightedColor: nil) } public static func circularAvatarHighlightedImage(image: UIImage, withDiameter diameter: UInt) -> UIImage { return SChatAvatarImageFactory.sChatCircularImage(image, withDiameter: diameter, highlightedColor: UIColor(white: 0.1, alpha: 0.3)) } public static func avatarImageWithUserInitials(userInitials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont, diameter: UInt) -> SChatAvatarImage { let avatarImage = SChatAvatarImageFactory.sChatImageWithInitials(userInitials, backgroundColor: backgroundColor, textColor: textColor, font: font, diameter: diameter) let avatarHighlightedImage = SChatAvatarImageFactory.sChatCircularImage(avatarImage, withDiameter: diameter, highlightedColor: UIColor(white: 0.1, alpha: 0.3)) return SChatAvatarImage(avatarImage: avatarImage, highlightedImage: avatarHighlightedImage, placeholderImage: avatarHighlightedImage) } // MARK: Private private static func sChatImageWithInitials(initials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont, diameter: UInt) -> UIImage { assert(diameter > 0, "The diameter should be greater than 0 in sChatImageWithInitials function.") let frame = CGRectMake(0.0, 0.0, CGFloat(diameter), CGFloat(diameter)) let attributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor] let textFrame = (initials as! NSString).boundingRectWithSize(frame.size, options: [NSStringDrawingOptions.UsesLineFragmentOrigin, NSStringDrawingOptions.UsesFontLeading], attributes: attributes, context: nil) let frameMidPoint = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame)) let textFrameMidPoint = CGPointMake(CGRectGetMidX(textFrame), CGRectGetMidY(textFrame)) let dx: CGFloat = frameMidPoint.x - textFrameMidPoint.x let dy: CGFloat = frameMidPoint.y - textFrameMidPoint.y let drawPoint = CGPointMake(dx, dy) var image: UIImage? = nil UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, backgroundColor.CGColor) CGContextFillRect(context, frame) (initials as! NSString).drawAtPoint(drawPoint, withAttributes: attributes) image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return SChatAvatarImageFactory.sChatCircularImage(image!, withDiameter: diameter, highlightedColor: nil) } private static func sChatCircularImage(image: UIImage?, withDiameter diameter: UInt, highlightedColor: UIColor?) -> UIImage { assert(image != nil, "The image is nil in sChatCircularImage function") assert(diameter > 0, "The diameter should be greater than 0 in sChatCircularImage") let frame = CGRectMake(0.0, 0.0, CGFloat(diameter), CGFloat(diameter)) var newImage: UIImage? = nil UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() let imgPath = UIBezierPath(ovalInRect: frame) imgPath.addClip() image?.drawInRect(frame) if let _highlightedColor = highlightedColor { CGContextSetFillColorWithColor(context, _highlightedColor.CGColor) CGContextFillEllipseInRect(context, frame) } newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
gpl-3.0
YoungGary/30daysSwiftDemo
day20/day20/Model.swift
1
346
// // Model.swift // day20 // // Created by YOUNG on 2016/10/14. // Copyright © 2016年 Young. All rights reserved. // import UIKit class Model: NSObject { var image : String = "" var title : String = "" init(image: String,title : String) { self.image = image self.title = title } }
mit
sudeepunnikrishnan/ios-sdk
Instamojo/Request.swift
1
24897
// // Request.swift // Instamojo // // Created by Sukanya Raj on 20/02/17. // Copyright © 2017 Sukanya Raj. All rights reserved. // import UIKit public class Request: NSObject { var order: Order? var mode: Mode var orderID: String? var accessToken: String? var card: Card? var virtualPaymentAddress: String? var upiSubmissionResponse: UPISubmissionResponse? var orderRequestCallBack: OrderRequestCallBack? var juspayRequestCallBack: JuspayRequestCallBack? var upiCallBack: UPICallBack? public enum Mode { case OrderCreate case FetchOrder case Juspay case UPISubmission case UPIStatusCheck } /** * Network Request to create an order ID from Instamojo server. * * @param order Order model with all the mandatory fields set. * @param orderRequestCallBack OrderRequestCallBack interface for the Asynchronous Network Call. */ public init(order: Order, orderRequestCallBack: OrderRequestCallBack) { self.mode = Mode.OrderCreate self.order = order self.orderRequestCallBack = orderRequestCallBack } /** * Network Request to get order details from Juspay for JuspaySafeBrowser. * * @param order Order model with all the mandatory fields set. * @param card Card with all the proper validations done. * @param jusPayRequestCallBack JusPayRequestCallBack for Asynchronous network call. */ public init(order: Order, card: Card, jusPayRequestCallBack: JuspayRequestCallBack) { self.mode = Mode.Juspay self.order = order self.card = card self.juspayRequestCallBack = jusPayRequestCallBack } /** * Network request for UPISubmission Submission * * @param order Order * @param virtualPaymentAddress String * @param upiCallback UPICallback */ public init(order: Order, virtualPaymentAddress: String, upiCallBack: UPICallBack) { self.mode = Mode.UPISubmission self.order = order self.virtualPaymentAddress = virtualPaymentAddress self.upiCallBack = upiCallBack } /** * Network Request to check the status of the transaction * * @param order Order * @param upiSubmissionResponse UPISubmissionResponse * @param upiCallback UPICallback */ init(order: Order, upiSubmissionResponse: UPISubmissionResponse, upiCallback: UPICallBack ) { self.mode = Mode.UPIStatusCheck self.order = order self.upiSubmissionResponse = upiSubmissionResponse self.upiCallBack = upiCallback } /** * Network request to fetch the order * @param accessToken String * @param orderID String * @param orderRequestCallBack OrderRequestCallBack */ public init(orderID: String, accessToken: String, orderRequestCallBack: OrderRequestCallBack ) { self.mode = Mode.FetchOrder self.orderID = orderID self.accessToken = accessToken self.orderRequestCallBack = orderRequestCallBack } public func execute() { switch self.mode { case Mode.OrderCreate: createOrder() break case Mode.FetchOrder: fetchOrder() break case Mode.Juspay: juspayRequest() break case Mode.UPISubmission: executeUPIRequest() break case Mode.UPIStatusCheck: upiStatusCheck() break } } func createOrder() { let url: String = Urls.getOrderCreateUrl() let params: [String: Any] = ["name": order!.buyerName!, "email": order!.buyerEmail!, "amount": order!.amount!, "description": order!.orderDescription!, "phone": order!.buyerPhone!, "currency": order!.currency!, "transaction_id": order!.transactionID!, "redirect_url": order!.redirectionUrl!, "advanced_payment_options": "true", "mode": order!.mode!, "webhook_url": order!.webhook!] let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "POST" request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + order!.authToken!, forHTTPHeaderField: "Authorization") request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") let session = URLSession.shared let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { if jsonResponse["payment_options"] != nil { //Payment Options Recieved self.updateTransactionDetails(jsonResponse: jsonResponse) self.orderRequestCallBack?.onFinish(order: self.order!, error: "") } else { if jsonResponse["error"] != nil { if let errorMessage = jsonResponse["error"] as? String { self.orderRequestCallBack?.onFinish(order: self.order!, error:errorMessage) } } else { if jsonResponse["success"] != nil { if let success = jsonResponse["success"] as? Bool { if !success { if let errorMessage = jsonResponse["message"] as? String { self.orderRequestCallBack?.onFinish(order: self.order!, error: errorMessage) } } } } else { self.orderRequestCallBack?.onFinish(order: self.order!, error: "Error while creating an order") } } } } } catch { Logger.logError(tag: "Caught Exception", message: String(describing: error)) self.orderRequestCallBack?.onFinish(order: self.order!, error: String(describing: error)) } } else { self.orderRequestCallBack?.onFinish(order: self.order!, error: "Error while creating an order") print(error!.localizedDescription) } }) task.resume() } func updateTransactionDetails(jsonResponse: [String:Any]) { //update order details let orders = jsonResponse["order"] as? [String:Any] self.order!.id = orders?["id"] as? String self.order!.transactionID = orders?["transaction_id"] as? String self.order!.resourceURI = orders?["resource_uri"] as? String //update payment_options let paymentOptions = jsonResponse["payment_options"] as? [String:Any] //card_options of this order if paymentOptions?["card_options"] != nil { let card_options = paymentOptions?["card_options"] as? [String:Any] let submissionData = card_options?["submission_data"] as? [String : Any] let merchandID = submissionData?["merchant_id"] as? String let orderID = submissionData?["order_id"] as? String let submission_url = card_options?["submission_url"] as? String let cardOptions = CardOptions(orderID: orderID!, url: submission_url!, merchantID: merchandID!) self.order!.cardOptions = cardOptions } //netbanking_options of this order if paymentOptions?["netbanking_options"] != nil { let netbanking_options = paymentOptions?["netbanking_options"] as? [String:Any] let submission_url = netbanking_options?["submission_url"] as? String if let choicesArray = netbanking_options?["choices"] as? [[String: Any]] { var choices = [NetBankingBanks]() for i in 0 ..< choicesArray.count { let bank_name = choicesArray[i]["name"] as? String let bank_code = choicesArray[i]["id"] as? String let netBanks = NetBankingBanks.init(bankName: bank_name!, bankCode: bank_code!) choices.append(netBanks) } if choices.count > 0 { self.order!.netBankingOptions = NetBankingOptions(url: submission_url!, banks: choices) } } } //emi_options of this order if paymentOptions?["emi_options"] != nil { let emi_options = paymentOptions?["emi_options"] as? [String: Any] let submission_url = emi_options?["submission_url"] as? String if let emi_list = emi_options?["emi_list"] as? [[String : Any]] { var emis = [EMIBank]() for i in 0 ..< emi_list.count { let bank_name = emi_list[i]["bank_name"] as? String let bank_code = emi_list[i]["bank_code"] as? String var rates = [Int: Int]() if let ratesRaw = emi_list[i]["rates"] as? [[String : Any]] { for j in 0 ..< ratesRaw.count { let tenure = ratesRaw[j]["tenure"] as? Int let interest = ratesRaw[j]["interest"] as? Int if let _ = tenure { if let _ = interest { rates.updateValue(interest!, forKey: tenure!) } } } let sortedRates = rates.sorted(by: { $0.0 < $1.0 }) if rates.count > 0 { let emiBank = EMIBank(bankName: bank_name!, bankCode: bank_code!, rate: sortedRates) emis.append(emiBank) } } } let submissionData = emi_options?["submission_data"] as? [String : Any] let merchantID = submissionData?["merchant_id"] as? String let orderID = submissionData?["order_id"] as? String if emis.count > 0 { self.order?.emiOptions = EMIOptions(merchantID: merchantID!, orderID: orderID!, url: submission_url!, emiBanks: emis) } } } //wallet_options of this order if paymentOptions?["wallet_options"] != nil { let wallet_options = paymentOptions?["wallet_options"] as? [String: Any] let submission_url = wallet_options?["submission_url"] as? String if let choicesArray = wallet_options?["choices"] as? [[String: Any]] { var wallets = [Wallet]() for i in 0 ..< choicesArray.count { let name = choicesArray[i]["name"] as? String let walletID = choicesArray[i]["id"] as! Int let walletImage = choicesArray[i]["image"] as? String wallets.append(Wallet(name: name!, imageUrl: walletImage!, walletID: walletID.stringValue)) Logger.logDebug(tag: "String value", message: walletID.stringValue) } if wallets.count > 0 { self.order?.walletOptions = WalletOptions(url: submission_url!, wallets: wallets) } } } //upi_options of this order if paymentOptions?["upi_options"] != nil { let upi_options = paymentOptions?["upi_options"] as? [String: Any] self.order?.upiOptions = UPIOptions(url: (upi_options?["submission_url"] as? String)!) } } func fetchOrder() { let url: String = Urls.getOrderFetchURL(orderID: self.orderID!) let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "GET" let session = URLSession.shared request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + self.accessToken!, forHTTPHeaderField: "Authorization") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in if error == nil { let response = String(data: data!, encoding: String.Encoding.utf8) as String! do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { self.parseOrder(response: jsonResponse) self.orderRequestCallBack?.onFinish(order: self.order!, error: "") }else{ self.orderRequestCallBack?.onFinish(order:Order.init(), error: response!) } } catch { self.orderRequestCallBack?.onFinish(order:Order.init(), error: response!) } } else { self.orderRequestCallBack?.onFinish(order: Order.init(), error: "Error while making Instamojo request ") print(error!.localizedDescription) } }) task.resume() } func parseOrder(response: [String : Any]) { let orderResponse = response["order"] as? [String : Any] let id = orderResponse?["id"] as? String ?? "" let transactionID = orderResponse?["transaction_id"] as? String ?? "" let name = orderResponse?["name"] as? String ?? "" let email = orderResponse?["email"] as? String ?? "" let phone = orderResponse?["phone"] as? String ?? "" let amount = orderResponse?["amount"] as? String ?? "" let description = orderResponse?["description"] as? String ?? "" let currency = orderResponse?["currency"] as? String ?? "" let redirect_url = orderResponse?["redirect_url"] as? String ?? "" let webhook_url = orderResponse?["webhook_url"] as? String ?? "" let resource_uri = orderResponse?["resource_uri"] as? String ?? "" self.order = Order.init(authToken: accessToken!, transactionID: transactionID, buyerName: name, buyerEmail: email, buyerPhone: phone, amount: amount, description: description, webhook: webhook_url) self.order?.redirectionUrl = redirect_url self.order?.currency = currency self.order?.resourceURI = resource_uri self.order?.id = id self.updateTransactionDetails(jsonResponse: response) } func juspayRequest() { Logger.logDebug(tag: "Juspay Request", message: "Juspay Request On Start") let url: String = self.order!.cardOptions.url let session = URLSession.shared var params = ["order_id": self.order!.cardOptions.orderID, "merchant_id": self.order!.cardOptions.merchantID, "payment_method_type": "Card", "card_number": self.card!.cardNumber, "name_on_card": self.card!.cardHolderName, "card_exp_month": self.card!.getExpiryMonth(), "card_exp_year": self.card!.getExpiryYear(), "card_security_code": self.card!.cvv, "save_to_locker": self.card!.savedCard ? "true" : "false", "redirect_after_payment": "true", "format": "json"] as [String : Any] if self.order!.emiOptions != nil && self.order!.emiOptions.selectedBankCode != nil { params.updateValue("true", forKey: "is_emi") params.updateValue(self.order!.emiOptions.selectedBankCode, forKey :"emi_bank") params.updateValue(self.order!.emiOptions.selectedTenure, forKey: "emi_tenure") } Logger.logDebug(tag: "Params", message: String(describing: params)) let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "POST" request.setBodyContent(parameters: params) request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in Logger.logDebug(tag: "Juspay Request", message: "Network call completed") if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { Logger.logDebug(tag: "Juspay Request", message: String(describing: jsonResponse)) if jsonResponse["payment"] != nil { let payment = jsonResponse["payment"] as? [String : Any] let authentication = payment?["authentication"] as? [String : Any] let url = authentication?["url"] as? String let orderID = jsonResponse["order_id"] as? String let txn_id = jsonResponse["txn_id"] as? String let browserParams = BrowserParams() browserParams.url = url browserParams.orderId = orderID browserParams.clientId = self.order?.clientID browserParams.transactionId = txn_id browserParams.endUrlRegexes = Urls.getEndUrlRegex() self.juspayRequestCallBack?.onFinish(params: browserParams, error: "") } else { Logger.logDebug(tag: "Juspay Request", message: "Error on request") self.juspayRequestCallBack?.onFinish(params: BrowserParams.init(), error: "Error while making Instamojo request") } } } catch { let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) print("Error could not parse JSON: '\(String(describing: jsonStr))'") self.juspayRequestCallBack?.onFinish(params: BrowserParams.init(), error: "Error while making Instamojo request") Logger.logError(tag: "Caught Exception", message: String(describing: error)) } } else { self.juspayRequestCallBack?.onFinish(params: BrowserParams.init(), error: "Error while making Instamojo request") print(error!.localizedDescription) } }) task.resume() } func executeUPIRequest() { let url: String = self.order!.upiOptions.url let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "POST" let session = URLSession.shared let params = ["virtual_address": self.virtualPaymentAddress!] request.setBodyContent(parameters: params) request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + order!.authToken!, forHTTPHeaderField: "Authorization") request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { let upiSubmissionResponse = self.parseUPIResponse(response: jsonResponse) if upiSubmissionResponse.statusCode == Constants.FailedPayment { self.upiCallBack?.onSubmission(upiSubmissionResponse: UPISubmissionResponse.init(), exception: "Payment failed. Please try again.") } else { self.upiCallBack?.onSubmission(upiSubmissionResponse:upiSubmissionResponse, exception: "") } } } catch { self.upiCallBack?.onSubmission(upiSubmissionResponse: UPISubmissionResponse.init(), exception: "Error while making UPI Submission request. Please try again.") Logger.logError(tag: "Caught Exception", message: String(describing: error)) } } else { self.upiCallBack?.onSubmission(upiSubmissionResponse: UPISubmissionResponse.init(), exception: "Error while making UPI Submission request. Please try again.") print(error!.localizedDescription) } }) task.resume() } func parseUPIResponse(response: [String : Any]) -> UPISubmissionResponse { let paymentID = response["payment_id"] as? String let statusCode = response["status_code"] as? Int let payerVirtualAddress = response["payer_virtual_address"] as? String let statusCheckURL = response["status_check_url"] as? String let upiBank = response["upi_bank"] as? String let statusMessage = response["status_message"] as? String if var payeeVirtualAddress = response["payeeVirtualAddress"] as? String { if payeeVirtualAddress.isEmpty { payeeVirtualAddress = "" } } return UPISubmissionResponse.init(paymentID: paymentID!, statusCode: statusCode!, payerVirtualAddress: payerVirtualAddress!, payeeVirtualAddress: payerVirtualAddress!, statusCheckURL: statusCheckURL!, upiBank: upiBank!, statusMessage: statusMessage!) } func upiStatusCheck() { let url: String = self.upiSubmissionResponse!.statusCheckURL let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "GET" let session = URLSession.shared request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + order!.authToken!, forHTTPHeaderField: "Authorization") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { Logger.logDebug(tag: "UPI Status", message: String(describing: jsonResponse)) let statusCode = jsonResponse["status_code"] as? Int if statusCode == Constants.PendingPayment { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: statusCode!) } else if statusCode == Constants.FailedPayment { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: statusCode!) } else { self.upiCallBack?.onStatusCheckComplete(paymentComplete: true, status: statusCode!) } } } catch { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: Constants.PaymentError) Logger.logError(tag: "Caught Exception", message: String(describing: error)) } } else { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: Constants.PaymentError) print(error!.localizedDescription) } }) task.resume() } func getUserAgent() -> String { let versionName: String = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String)! + ";" let versionCode: String = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String)! let appID = Bundle.main.bundleIdentifier! + ";" return "Instamojo IOS SDK;" + UIDevice.current.model + ";" + "Apple;" + UIDevice.current.systemVersion + ";" + appID + versionName + versionCode } } public extension NSMutableURLRequest { func setBodyContent(parameters: [String : Any]) { let parameterArray = parameters.map { (key, value) -> String in return "\(key)=\((value as AnyObject))" } httpBody = parameterArray.joined(separator: "&").data(using: String.Encoding.utf8) } } public extension Int { var stringValue: String { return "\(self)" } }
lgpl-3.0
AlwaysRightInstitute/SwiftyHTTP
SwiftSockets/ActiveSocket.swift
1
12137
// // ActiveSocket.swift // SwiftSockets // // Created by Helge Hess on 6/11/14. // Copyright (c) 2014-2015 Always Right Institute. All rights reserved. // #if os(Linux) import Glibc #else import Darwin #endif import Dispatch public typealias ActiveSocketIPv4 = ActiveSocket<sockaddr_in> /** * Represents an active STREAM socket based on the standard Unix sockets * library. * * An active socket can be either a socket gained by calling accept on a * passive socket or by explicitly connecting one to an address (a client * socket). * Therefore an active socket has two addresses, the local and the remote one. * * There are three methods to perform a close, this is rooted in the fact that * a socket actually is full-duplex, it provides a send and a receive channel. * The stream-mode is updated according to what channels are open/closed. * Initially the socket is full-duplex and you cannot reopen a channel that was * shutdown. If you have shutdown both channels the socket can be considered * closed. * * Sample: * let socket = ActiveSocket<sockaddr_in>() * .onRead { * let (count, block) = $0.read() * if count < 1 { * print("EOF, or great error handling.") * return * } * print("Answer to ring,ring is: \(count) bytes: \(block)") * } * socket.connect(sockaddr_in(address:"127.0.0.1", port: 80)) * socket.write("Ring, ring!\r\n") */ public class ActiveSocket<T: SocketAddress>: Socket<T> { public var remoteAddress : T? = nil public var queue : dispatch_queue_t? = nil var readSource : dispatch_source_t? = nil var sendCount : Int = 0 var closeRequested : Bool = false var didCloseRead : Bool = false var readCB : ((ActiveSocket, Int) -> Void)? = nil // let the socket own the read buffer, what is the best buffer type? //var readBuffer : [CChar] = [CChar](count: 4096 + 2, repeatedValue: 42) var readBufferPtr = UnsafeMutablePointer<CChar>.alloc(4096 + 2) var readBufferSize : Int = 4096 { // available space, a bit more for '\0' didSet { if readBufferSize != oldValue { readBufferPtr.dealloc(oldValue + 2) readBufferPtr = UnsafeMutablePointer<CChar>.alloc(readBufferSize + 2) } } } public var isConnected : Bool { guard isValid else { return false } return remoteAddress != nil } /* init */ override public init(fd: FileDescriptor) { // required, otherwise the convenience one fails to compile super.init(fd: fd) } /* Still crashes Swift 2b3 compiler (when the method below is removed) public convenience init?() { self.init(type: SOCK_STREAM) // assumption is that we inherit this // though it should work right away? } */ public convenience init?(type: Int32 = sys_SOCK_STREAM) { // TODO: copy of Socket.init(type:), but required to compile. Not sure // what's going on with init inheritance here. Do I *have to* read the // manual??? let lfd = socket(T.domain, type, 0) guard lfd != -1 else { return nil } self.init(fd: FileDescriptor(lfd)) } public convenience init (fd: FileDescriptor, remoteAddress: T?, queue: dispatch_queue_t? = nil) { self.init(fd: fd) self.remoteAddress = remoteAddress self.queue = queue isSigPipeDisabled = fd.isValid // hm, hm? } deinit { readBufferPtr.dealloc(readBufferSize + 2) } /* close */ override public func close() { if debugClose { debugPrint("closing socket \(self)") } guard isValid else { // already closed if debugClose { debugPrint(" already closed.") } return } // always shutdown receiving end, should call shutdown() // TBD: not sure whether we have a locking issue here, can read&write // occur on different threads in GCD? if !didCloseRead { if debugClose { debugPrint(" stopping events ...") } stopEventHandler() // Seen this crash - if close() is called from within the readCB? readCB = nil // break potential cycles if debugClose { debugPrint(" shutdown read channel ...") } sysShutdown(fd.fd, sys_SHUT_RD); didCloseRead = true } if sendCount > 0 { if debugClose { debugPrint(" sends pending, requesting close ...") } closeRequested = true return } queue = nil // explicitly release, might be a good idea ;-) if debugClose { debugPrint(" super close.") } super.close() } /* connect */ public func connect(address: T, onConnect: ( ActiveSocket<T> ) -> Void) -> Bool { // FIXME: make connect() asynchronous via GCD guard !isConnected else { // TBD: could be tolerant if addresses match print("Socket is already connected \(self)") return false } guard fd.isValid else { return false } // Note: must be 'var' for ptr stuff, can't use let var addr = address let lfd = fd.fd let rc = withUnsafePointer(&addr) { ptr -> Int32 in let bptr = UnsafePointer<sockaddr>(ptr) // cast return sysConnect(lfd, bptr, socklen_t(addr.len)) //only returns block } guard rc == 0 else { print("Could not connect \(self) to \(addr)") return false } remoteAddress = addr onConnect(self) return true } /* read */ public func onRead(cb: ((ActiveSocket, Int) -> Void)?) -> Self { let hadCB = readCB != nil let hasNewCB = cb != nil if !hasNewCB && hadCB { stopEventHandler() } readCB = cb if hasNewCB && !hadCB { startEventHandler() } return self } // This doesn't work, can't override a stored property // Leaving this feature alone for now, doesn't have real-world importance // @lazy override var boundAddress: T? = getRawAddress() /* description */ override func descriptionAttributes() -> String { // must be in main class, override not available in extensions var s = super.descriptionAttributes() if remoteAddress != nil { s += " remote=\(remoteAddress!)" } return s } } extension ActiveSocket : OutputStreamType { // writing public func write(string: String) { string.withCString { (cstr: UnsafePointer<Int8>) -> Void in let len = Int(strlen(cstr)) if len > 0 { self.asyncWrite(cstr, length: len) } } } } public extension ActiveSocket { // writing // no let in extensions: let debugAsyncWrites = false var debugAsyncWrites : Bool { return false } public var canWrite : Bool { guard isValid else { assert(isValid, "Socket closed, can't do async writes anymore") return false } guard !closeRequested else { assert(!closeRequested, "Socket is being shutdown already!") return false } return true } public func write(data: dispatch_data_t) { sendCount += 1 if debugAsyncWrites { debugPrint("async send[\(data)]") } // in here we capture self, which I think is right. dispatch_write(fd.fd, data, queue!) { asyncData, error in if self.debugAsyncWrites { debugPrint("did send[\(self.sendCount)] data \(data) error \(error)") } self.sendCount = self.sendCount - 1 // -- fails? if self.sendCount == 0 && self.closeRequested { if self.debugAsyncWrites { debugPrint("closing after async write ...") } self.close() self.closeRequested = false } } } public func asyncWrite<T>(buffer: [T]) -> Bool { // While [T] seems to convert to ConstUnsafePointer<T>, this method // has the added benefit of being able to derive the buffer length guard canWrite else { return false } let writelen = buffer.count let bufsize = writelen * sizeof(T) guard bufsize > 0 else { // Nothing to write .. return true } if queue == nil { debugPrint("No queue set, using main queue") queue = dispatch_get_main_queue() } // the default destructor is supposed to copy the data. Not good, but // handling ownership is going to be messy #if os(Linux) let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil) #else /* os(Darwin) */ // TBD guard let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil) else { return false } #endif /* os(Darwin) */ write(asyncData) return true } public func asyncWrite<T>(buffer: UnsafePointer<T>, length:Int) -> Bool { // FIXME: can we remove this dupe of the [T] version? guard canWrite else { return false } let writelen = length let bufsize = writelen * sizeof(T) guard bufsize > 0 else { // Nothing to write .. return true } if queue == nil { debugPrint("No queue set, using main queue") queue = dispatch_get_main_queue() } // the default destructor is supposed to copy the data. Not good, but // handling ownership is going to be messy #if os(Linux) let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil); #else /* os(Darwin) */ guard let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil) else { return false } #endif /* os(Darwin) */ write(asyncData) return true } public func send<T>(buffer: [T], length: Int? = nil) -> Int { // var writeCount : Int = 0 let bufsize = length ?? buffer.count // this is funky let ( _, writeCount ) = fd.write(buffer, count: bufsize) return writeCount } } public extension ActiveSocket { // Reading // Note: Swift doesn't allow the readBuffer in here. public func read() -> ( size: Int, block: UnsafePointer<CChar>, error: Int32){ let bptr = UnsafePointer<CChar>(readBufferPtr) guard fd.isValid else { print("Called read() on closed socket \(self)") readBufferPtr[0] = 0 return ( -42, bptr, EBADF ) } var readCount: Int = 0 let bufsize = readBufferSize // FIXME: If I just close the Terminal which hosts telnet this continues // to read garbage from the server. Even with SIGPIPE off. readCount = sysRead(fd.fd, readBufferPtr, bufsize) guard readCount >= 0 else { readBufferPtr[0] = 0 return ( readCount, bptr, errno ) } readBufferPtr[readCount] = 0 // convenience return ( readCount, bptr, 0 ) } /* setup read event handler */ func stopEventHandler() { if readSource != nil { dispatch_source_cancel(readSource!) readSource = nil // abort()s if source is not resumed ... } } func startEventHandler() -> Bool { guard readSource == nil else { print("Read source already setup?") return true // already setup } /* do we have a queue? */ if queue == nil { debugPrint("No queue set, using main queue") queue = dispatch_get_main_queue() } /* setup GCD dispatch source */ readSource = dispatch_source_create( DISPATCH_SOURCE_TYPE_READ, UInt(fd.fd), // is this going to bite us? 0, queue! ) guard readSource != nil else { print("Could not create dispatch source for socket \(self)") return false } // TBD: do we create a retain cycle here (self vs self.readSource) readSource!.onEvent { [unowned self] _, readCount in if let cb = self.readCB { cb(self, Int(readCount)) } } /* actually start listening ... */ #if os(Linux) // TBD: what is the better way? dispatch_resume(unsafeBitCast(readSource!, dispatch_object_t.self)) #else /* os(Darwin) */ dispatch_resume(readSource!) #endif /* os(Darwin) */ return true } } public extension ActiveSocket { // ioctl var numberOfBytesAvailableForReading : Int? { return fd.numberOfBytesAvailableForReading } }
mit
saagarjha/iina
iina/JavascriptAPIUtils.swift
1
6645
// // JavascriptAPIUtils.swift // iina // // Created by Collider LI on 2/3/2019. // Copyright © 2019 lhc. All rights reserved. // import Foundation import JavaScriptCore fileprivate func searchBinary(_ file: String, in url: URL) -> URL? { let url = url.appendingPathComponent(file) return FileManager.default.fileExists(atPath: url.path) ? url : nil } fileprivate extension Process { var descriptionDict: [String: Any] { return [ "status": terminationStatus ] } } @objc protocol JavascriptAPIUtilsExportable: JSExport { func fileInPath(_ file: String) -> Bool func resolvePath(_ path: String) -> String? func exec(_ file: String, _ args: [String], _ cwd: JSValue?, _ stdoutHook_: JSValue?, _ stderrHook_: JSValue?) -> JSValue? func ask(_ title: String) -> Bool func prompt(_ title: String) -> String? func chooseFile(_ title: String, _ options: [String: Any]) -> Any } class JavascriptAPIUtils: JavascriptAPI, JavascriptAPIUtilsExportable { override func extraSetup() { context.evaluateScript(""" iina.utils.ERROR_BINARY_NOT_FOUND = -1; iina.utils.ERROR_RUNTIME = -2; """) } func fileInPath(_ file: String) -> Bool { guard permitted(to: .accessFileSystem) else { return false } if file.isEmpty { return false } if let _ = searchBinary(file, in: Utility.binariesURL) ?? searchBinary(file, in: Utility.exeDirURL) { return true } if let path = parsePath(file).path { return FileManager.default.fileExists(atPath: path) } return false } func resolvePath(_ path: String) -> String? { guard permitted(to: .accessFileSystem) else { return nil } return parsePath(path).path } func exec(_ file: String, _ args: [String], _ cwd: JSValue?, _ stdoutHook_: JSValue?, _ stderrHook_: JSValue?) -> JSValue? { guard permitted(to: .accessFileSystem) else { return nil } return createPromise { [unowned self] resolve, reject in var path = "" var args = args if !file.contains("/") { if let url = searchBinary(file, in: Utility.binariesURL) ?? searchBinary(file, in: Utility.exeDirURL) { // a binary included in IINA's bundle? path = url.absoluteString } else { // assume it's a system command path = "/bin/bash" args.insert(file, at: 0) args = ["-c", args.map { $0.replacingOccurrences(of: " ", with: "\\ ") .replacingOccurrences(of: "'", with: "\\'") .replacingOccurrences(of: "\"", with: "\\\"") }.joined(separator: " ")] } } else { // it should be an existing file if file.first == "/" { // an absolute path? path = file } else { path = parsePath(file).path ?? "" } // make sure the file exists guard FileManager.default.fileExists(atPath: path) else { reject.call(withArguments: [-1, "Cannot find the binary \(file)"]) return } } // If this binary belongs to the plugin but doesn't have exec permission, try fix it if !FileManager.default.isExecutableFile(atPath: path) && ( path.hasPrefix(self.pluginInstance.plugin.dataURL.path) || path.hasPrefix(self.pluginInstance.plugin.tmpURL.path)) { do { try FileManager.default.setAttributes([.posixPermissions: NSNumber(integerLiteral: 0o755)], ofItemAtPath: path) } catch { reject.call(withArguments: [-2, "The binary is not executable, and execute permission cannot be added"]) return } } let (stdout, stderr) = (Pipe(), Pipe()) let process = Process() process.environment = ["LC_ALL": "en_US.UTF-8"] process.launchPath = path process.arguments = args if let cwd = cwd, cwd.isString, let cwdPath = parsePath(cwd.toString()).path { process.currentDirectoryPath = cwdPath } process.standardOutput = stdout process.standardError = stderr var stdoutContent = "" var stderrContent = "" var stdoutHook: JSValue? var stderrHook: JSValue? if let hookVal = stdoutHook_, hookVal.isObject { stdoutHook = hookVal } if let hookVal = stderrHook_, hookVal.isObject { stderrHook = hookVal } stdout.fileHandleForReading.readabilityHandler = { file in guard let output = String(data: file.availableData, encoding: .utf8) else { return } stdoutContent += output stdoutHook?.call(withArguments: [output]) } stderr.fileHandleForReading.readabilityHandler = { file in guard let output = String(data: file.availableData, encoding: .utf8) else { return } stderrContent += output stderrHook?.call(withArguments: [output]) } process.launch() self.pluginInstance.queue.async { process.waitUntilExit() stderr.fileHandleForReading.readabilityHandler = nil stdout.fileHandleForReading.readabilityHandler = nil resolve.call(withArguments: [[ "status": process.terminationStatus, "stdout": stdoutContent, "stderr": stderrContent ] as [String: Any]]) } } } func ask(_ title: String) -> Bool { let panel = NSAlert() panel.messageText = title panel.addButton(withTitle: NSLocalizedString("general.ok", comment: "OK")) panel.addButton(withTitle: NSLocalizedString("general.cancel", comment: "Cancel")) return panel.runModal() == .alertFirstButtonReturn } func prompt(_ title: String) -> String? { let panel = NSAlert() panel.messageText = title let input = NSTextField(frame: NSRect(x: 0, y: 0, width: 240, height: 60)) input.lineBreakMode = .byWordWrapping input.usesSingleLineMode = false panel.accessoryView = input panel.addButton(withTitle: NSLocalizedString("general.ok", comment: "OK")) panel.addButton(withTitle: NSLocalizedString("general.cancel", comment: "Cancel")) panel.window.initialFirstResponder = input if panel.runModal() == .alertFirstButtonReturn { return input.stringValue } return nil } func chooseFile(_ title: String, _ options: [String: Any]) -> Any { let chooseDir = options["chooseDir"] as? Bool ?? false let allowedFileTypes = options["allowedFileTypes"] as? [String] return createPromise { resolve, reject in Utility.quickOpenPanel(title: title, chooseDir: chooseDir, allowedFileTypes: allowedFileTypes) { result in resolve.call(withArguments: [result.path]) } } } }
gpl-3.0
ahmad-atef/AutoScout24_Tech_Challenge
AutoScout24 Tech_Challenge/Helpers/Constants.swift
1
310
// // Constants.swift // AutoScout24 Tech_Challenge // // Created by Ahmad Atef on 5/10/17. // Copyright © 2017 Ahmad Atef. All rights reserved. // import UIKit import Foundation let APP_DELEGATE = UIApplication.shared.delegate as! AppDelegate let CONTEXT = APP_DELEGATE.persistentContainer.viewContext
mit
milseman/swift
test/Parse/toplevel_library_invalid.swift
10
944
// RUN: %target-typecheck-verify-swift -parse-as-library // RUN: %target-typecheck-verify-swift -parse-as-library -enable-astscope-lookup let x = 42 x + x; // expected-error {{expressions are not allowed at the top level}} expected-warning {{result of operator '+' is unused}} x + x; // expected-error {{expressions are not allowed at the top level}} expected-warning {{result of operator '+' is unused}} // Make sure we don't crash on closures at the top level ({ }) // expected-error {{expressions are not allowed at the top level}} expected-error{{expression resolves to an unused function}} ({ 5 }()) // expected-error {{expressions are not allowed at the top level}} // expected-warning @-1 {{result of call is unused}} // expected-error @+3 {{expected 'in' after for-each pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for i
apache-2.0
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/SwiftExtensions/Numbers.swift
2
569
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation public extension Int { public func format(f: String) -> String { return NSString(format: "%\(f)d", self) as String } } public extension Double { public func format(f: String) -> String { return NSString(format: "%\(f)f", self) as String } } public extension NSTimeInterval { public var time:String { return String(format:"%02d:%02d:%02d.%03d", Int((self/3600.0)%60),Int((self/60.0)%60), Int((self) % 60 ), Int(self*1000 % 1000 ) ) } }
agpl-3.0
superk589/CGSSGuide
DereGuide/Toolbox/Gacha/Controller/GachaCardFilterSortController.swift
2
611
// // GachaCardFilterSortController.swift // DereGuide // // Created by zzk on 2017/5/2. // Copyright © 2017 zzk. All rights reserved. // import UIKit class GachaCardFilterSortController: CardFilterSortController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) sorterTitles.append(NSLocalizedString("出现率", comment: "")) sorterMethods.append("odds") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
LibraryLoupe/PhotosPlus
PhotosPlus/Cameras/Panasonic/PanasonicLumixG85.swift
3
518
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Panasonic { public struct LumixG85: CameraModel { public init() {} public let name = "Panasonic Lumix G85" public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Panasonic.self } } public typealias PanasonicLumixG85 = Cameras.Manufacturers.Panasonic.LumixG85
mit
OldBulls/swift-weibo
ZNWeibo/ZNWeibo/AppDelegate.swift
1
1809
// // AppDelegate.swift // ZNWeibo // // Created by 金宝和信 on 16/7/6. // Copyright © 2016年 zn. All rights reserved. // import UIKit import QorumLogs //第三方打印log @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var defaultViewController :UIViewController? { let isLogin = UserAccountViewModel.shareIntance.isLogin return isLogin ? WelcomeViewController() : MainViewController() } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. // QorumLogs.enabled = true // QorumLogs.test() //设置全局颜色 UITabBar.appearance().tintColor = UIColor.orangeColor() UINavigationBar.appearance().tintColor = UIColor.orangeColor() //创建window window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = defaultViewController window?.makeKeyAndVisible() return true } } //MARK: - 自定义全局Log func ZNLog<T>(message:T, fileName:String = #file, funcName:String = #function, lineNum:Int = #line) { #if DEBUG //添加flat标签步骤:点击项目-->Build Setting-->swfit flag-->点击箭头-->点击Debug添加--> -D DEBUG //lastPathComponent 获取字符串最后一个 "/"后面的字符串 var file = (fileName as NSString).lastPathComponent as NSString let index = file.rangeOfString(".") file = file.substringToIndex(index.location) print("\(file):\(funcName)(\(lineNum)行)-\(message)") #endif }
mit
iOS-Swift-Developers/Swift
MVVM学习/1.了解MVVM/MVVM-SwiftUITests/MVVM_SwiftUITests.swift
1
1249
// // MVVM_SwiftUITests.swift // MVVM-SwiftUITests // // Created by 韩俊强 on 2018/2/23. // Copyright © 2018年 HaRi. All rights reserved. // import XCTest class MVVM_SwiftUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
rumana1411/Giphying
SwappingCollectionView/CustomTableViewCell.swift
1
596
// // CustomTableViewCell.swift // swRevealSlidingMenu // // Created by Rumana Nazmul on 20/6/17. // Copyright © 2017 ALFA. All rights reserved. // import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet weak var myImgView: UIImageView! @IBOutlet weak var myLbl: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
Cryptoc1/SpeechPrep
SpeechPrepTests/SpeechPrepTests.swift
1
916
// // SpeechPrepTests.swift // SpeechPrepTests // // Created by Cryptoc1 on 5/22/15. // Copyright (c) 2015 Cryptocosm Developers. All rights reserved. // import Cocoa import XCTest class SpeechPrepTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
Otbivnoe/Framezilla
Tests/MakerTests.swift
1
14912
// // MakerTests.swift // Framezilla // // Created by Nikita on 06/09/16. // Copyright © 2016 Nikita. All rights reserved. // import XCTest class MakerTests: BaseTest { /* Array configurator */ func testThatCorrectlyConfiguresFramesForArrayOfViews() { let label = UILabel(frame: .zero) let view = UIView(frame: .zero) [label, view].configureFrames { maker in maker.width(100) maker.height(50) } XCTAssertEqual(label.frame, CGRect(x: 0, y: 0, width: 100, height: 50)) XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 100, height: 50)) } /* bottom_to with nui_top */ func testThatCorrectlyConfigures_bottom_to_withAnotherView_top_relationWith_zeroInset() { testingView.configureFrame { maker in maker.bottom(to: nestedView2.nui_top) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 100, width: 50, height: 50)) } func testThatCorrectlyConfigures_bottom_to_withAnotherView_top_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.bottom(to: nestedView2.nui_top, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 90, width: 50, height: 50)) } /* bottom_to with nui_centerY */ func testThatCorrectlyConfigures_bottom_to_withAnotherView_centerY_relationWith_zeroInset() { testingView.configureFrame { maker in maker.bottom(to: nestedView2.nui_centerY) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 200, width: 50, height: 50)) } func testThatCorrectlyConfigures_bottom_to_withAnotherView_centerY_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.bottom(to: nestedView2.nui_centerY, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 190, width: 50, height: 50)) } /* bottom_to with nui_bottom */ func testThatCorrectlyConfigures_bottom_to_withAnotherView_bottom_relationWith_zeroInset() { testingView.configureFrame { maker in maker.bottom(to: nestedView2.nui_bottom) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 300, width: 50, height: 50)) } func testThatCorrectlyConfigures_bottom_to_withAnotherView_bottom_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.bottom(to: nestedView2.nui_bottom, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 290, width: 50, height: 50)) } /* top_to with nui_top */ func testThatCorrectlyConfigures_top_to_withAnotherView_top_relationWith_zeroInset() { testingView.configureFrame { maker in maker.top(to: nestedView2.nui_top) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 150, width: 50, height: 50)) } func testThatCorrectlyConfigures_top_to_withAnotherView_top_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.top(to: nestedView2.nui_top, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 160, width: 50, height: 50)) } /* top_to with nui_centerY */ func testThatCorrectlyConfigures_top_to_withAnotherView_centerY_relationWith_zeroInset() { testingView.configureFrame { maker in maker.top(to: nestedView2.nui_centerY) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 250, width: 50, height: 50)) } func testThatCorrectlyConfigures_top_to_withAnotherView_centerY_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.top(to: nestedView2.nui_centerY, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 260, width: 50, height: 50)) } /* top_to with nui_bottom */ func testThatCorrectlyConfigures_top_to_withAnotherView_bottom_relationWith_zeroInset() { testingView.configureFrame { maker in maker.top(to: nestedView2.nui_bottom) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 350, width: 50, height: 50)) } func testThatCorrectlyConfigures_top_to_withAnotherView_bottom_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.top(to: nestedView2.nui_bottom, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 360, width: 50, height: 50)) } /* right_to with nui_right */ func testThatCorrectlyConfigures_right_to_withAnotherView_right_relationWith_zeroInset() { testingView.configureFrame { maker in maker.right(to: nestedView2.nui_right) } XCTAssertEqual(testingView.frame, CGRect(x: 300, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_right_to_withAnotherView_right_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.right(to: nestedView2.nui_right, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 290, y: 0, width: 50, height: 50)) } /* top_to with nui_centerX */ func testThatCorrectlyConfigures_right_to_withAnotherView_centerX_relationWith_zeroInset() { testingView.configureFrame { maker in maker.right(to: nestedView2.nui_centerX) } XCTAssertEqual(testingView.frame, CGRect(x: 200, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_right_to_withAnotherView_centerX_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.right(to: nestedView2.nui_centerX, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 190, y: 0, width: 50, height: 50)) } /* top_to with nui_left */ func testThatCorrectlyConfigures_right_to_withAnotherView_left_relationWith_zeroInset() { testingView.configureFrame { maker in maker.right(to: nestedView2.nui_left) } XCTAssertEqual(testingView.frame, CGRect(x: 100, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_right_to_withAnotherView_left_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.right(to: nestedView2.nui_left, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 90, y: 0, width: 50, height: 50)) } /* left_to with nui_right */ func testThatCorrectlyConfigures_left_to_withAnotherView_right_relationWith_zeroInset() { testingView.configureFrame { maker in maker.left(to: nestedView2.nui_right) } XCTAssertEqual(testingView.frame, CGRect(x: 350, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_left_to_withAnotherView_right_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.left(to: nestedView2.nui_right, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 360, y: 0, width: 50, height: 50)) } /* left_to with nui_centerX */ func testThatCorrectlyConfigures_left_to_withAnotherView_centerX_relationWith_zeroInset() { testingView.configureFrame { maker in maker.left(to: nestedView2.nui_centerX) } XCTAssertEqual(testingView.frame, CGRect(x: 250, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_left_to_withAnotherView_centerX_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.left(to: nestedView2.nui_centerX, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 260, y: 0, width: 50, height: 50)) } /* left_to with nui_left */ func testThatCorrectlyConfigures_left_to_withAnotherView_left_relationWith_zeroInset() { testingView.configureFrame { maker in maker.left(to: nestedView2.nui_left) } XCTAssertEqual(testingView.frame, CGRect(x: 150, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_left_to_withAnotherView_left_relationWith_nonZeroInset() { testingView.configureFrame { maker in maker.left(to: nestedView2.nui_left, inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 160, y: 0, width: 50, height: 50)) } /* left to superview */ func testThatCorrectlyConfigures_left_toSuperviewWith_zeroInset() { testingView.configureFrame { maker in maker.left() } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_left_toSuperviewWith_nonZeroInset() { testingView.configureFrame { maker in maker.left(inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 10, y: 0, width: 50, height: 50)) } /* top to superview */ func testThatCorrectlyConfigures_top_toSuperviewWith_zeroInset() { testingView.configureFrame { maker in maker.top() } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_top_toSuperviewWith_nonZeroInset() { testingView.configureFrame { maker in maker.top(inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 10, width: 50, height: 50)) } /* bottom to superview */ func testThatCorrectlyConfigures_bottom_toSuperviewWith_zeroInset() { testingView.configureFrame { maker in maker.bottom() } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 450, width: 50, height: 50)) } func testThatCorrectlyConfigures_bottom_toSuperviewWith_nonZeroInset() { testingView.configureFrame { maker in maker.bottom(inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 0, y: 440, width: 50, height: 50)) } /* right to superview */ func testThatCorrectlyConfigures_right_toSuperviewWith_zeroInset() { testingView.configureFrame { maker in maker.right() } XCTAssertEqual(testingView.frame, CGRect(x: 450, y: 0, width: 50, height: 50)) } func testThatCorrectlyConfigures_right_toSuperviewWith_nonZeroInset() { testingView.configureFrame { maker in maker.right(inset: 10) } XCTAssertEqual(testingView.frame, CGRect(x: 440, y: 0, width: 50, height: 50)) } /* edges */ func testThatCorrectlyConfigures_margin_relation() { let inset: CGFloat = 5 testingView.configureFrame { maker in maker.margin(inset) } XCTAssertEqual(testingView.frame, CGRect(x: inset, y: inset, width: 490, height: 490)) } func testThatCorrectlyConfigures_equal_to_relationForNearSubview() { let insets = UIEdgeInsetsMake(5, 10, 15, 20) testingView.configureFrame { maker in maker.equal(to: nestedView1, insets: insets) } XCTAssertEqual(testingView.frame, CGRect(x: nestedView1.frame.minX + insets.left, y: nestedView1.frame.minY + insets.top, width: nestedView1.bounds.width-(insets.left + insets.right), height: nestedView1.bounds.height-(insets.top + insets.bottom))) } func testThatCorrectlyConfigures_equal_to_dependsOnSuperview() { testingView.configureFrame { maker in maker.equal(to: mainView) } XCTAssertEqual(testingView.frame, mainView.frame) } func testThatCorrectlyConfigures_edge_insets_toSuperview() { testingView.configureFrame { maker in maker.edges(insets: UIEdgeInsetsMake(10, 20, 40, 60)) } XCTAssertEqual(testingView.frame, CGRect(x: 20, y: 10, width: 420, height: 450)) } func testThatCorrectlyConfigures_edge_toSuperview() { testingView.configureFrame { maker in maker.edges(top: 20, left: 20, bottom: 20, right: 20) } XCTAssertEqual(testingView.frame, CGRect(x: 20, y: 20, width: 460, height: 460)) } /* container */ func testThatCorrectlyConfiguresContainer() { let view1 = UIView(frame: CGRect(x: 50, y: 50, width: 50, height: 50)) let view2 = UIView(frame: CGRect(x: 70, y: 70, width: 50, height: 50)) let containet = UIView() containet.addSubview(view1) containet.addSubview(view2) containet.configureFrame { maker in maker._container() } XCTAssertEqual(containet.frame, CGRect(x: 0, y: 0, width: 120, height: 120)) } /* sizeToFit */ func testThat_sizeToFit_correctlyConfigures() { let label = UILabel() label.text = "Hello" label.configureFrame { maker in maker.sizeToFit() } XCTAssertGreaterThan(label.bounds.width, 0) XCTAssertGreaterThan(label.bounds.height, 0) } /* sizeThatFits */ func testThat_sizeThatFits_correctlyConfigures() { let label = UILabel() label.text = "HelloHelloHelloHello" label.configureFrame { maker in maker.sizeThatFits(size: CGSize(width: 30, height: 0)) } XCTAssertEqual(label.bounds.width, 30) XCTAssertEqual(label.bounds.height, 0) } /* corner radius */ func testThat_cornerRadius_correctlyConfigures() { let view = UIView() view.configureFrame { maker in maker.cornerRadius(100) } XCTAssertEqual(view.layer.cornerRadius, 100) } func testThat_cornerRadiusWithHalfWidth_correctlyConfigures() { let view = UIView() view.configureFrame { maker in maker.width(100) maker.cornerRadius(byHalf: .width) } XCTAssertEqual(view.layer.cornerRadius, 50) } func testThat_cornerRadiusWithHalfHeight_correctlyConfigures() { let view = UIView() view.configureFrame { maker in maker.height(100) maker.cornerRadius(byHalf: .height) } XCTAssertEqual(view.layer.cornerRadius, 50) } }
mit
vornet/mapdoodle-ios
MapDoodle/Classes/PathDoodle.swift
1
1818
// // PathDoodle.swift // Pods // // Created by Vorn Mom on 8/2/16. // // import Foundation import MapKit public class PathDoodle : Doodle { public var id: String! public var points: [GeoPoint] var style: PathDoodleStyle var shouldRedraw: Bool = true var isBeingRemoved: Bool = false private var mapView: MKMapView! private var polyline: MKPolyline! init(style: PathDoodleStyle, points: [GeoPoint]) { self.style = style self.points = points } public func draw(context: DoodleContext) { if mapView == nil { mapView = context.mapView } if isBeingRemoved { return; } if polyline == nil || shouldRedraw { if polyline != nil { context.mapView.removeOverlay(polyline) } var coordinates = self.points.map({ geoPoint -> CLLocationCoordinate2D in CLLocationCoordinate2D(latitude: geoPoint.latitude, longitude: geoPoint.longitude)}) self.polyline = MKPolyline(coordinates: &coordinates, count: coordinates.count) context.mapView.addOverlay(self.polyline) } } public func remove() { if (isBeingRemoved) { return; } isBeingRemoved = true if polyline != nil && mapView != nil { mapView.removeOverlay(polyline); polyline = nil } } public var bounds: [GeoPoint] { get { return LocationUtil.getBounds(points) } } public func setupPolylineRenderer(polyline: MKPolyline) -> MKPolylineRenderer? { var polylineRenderer: MKPolylineRenderer? = nil if self.polyline === polyline { polylineRenderer = MKPolylineRenderer(overlay: polyline) polylineRenderer!.strokeColor = style.color polylineRenderer!.lineWidth = CGFloat(style.thickness / 2.5) } return polylineRenderer } }
mit
mohamede1945/quran-ios
Quran/PageBookmarkDataSource.swift
2
2143
// // PageBookmarkDataSource.swift // Quran // // Created by Mohamed Afifi on 11/1/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Foundation import GenericDataSources class PageBookmarkDataSource: BaseBookmarkDataSource<PageBookmark, BookmarkTableViewCell> { let numberFormatter = NumberFormatter() override func ds_collectionView(_ collectionView: GeneralCollectionView, configure cell: BookmarkTableViewCell, with item: PageBookmark, at indexPath: IndexPath) { let ayah = Quran.startAyahForPage(item.page) let suraFormat = NSLocalizedString("quran_sura_title", tableName: "Android", comment: "") let suraName = Quran.nameForSura(ayah.sura) cell.iconImage.image = #imageLiteral(resourceName: "bookmark-filled").withRenderingMode(.alwaysTemplate) cell.iconImage.tintColor = .bookmark() cell.name.text = String(format: suraFormat, suraName) cell.descriptionLabel.text = item.creationDate.bookmarkTimeAgo() cell.startPage.text = numberFormatter.format(NSNumber(value: item.page)) } func reloadData() { DispatchQueue.default .promise2(execute: self.persistence.retrievePageBookmarks) .then(on: .main) { items -> Void in self.items = items self.ds_reusableViewDelegate?.ds_reloadSections(IndexSet(integer: 0), with: .automatic) }.cauterize(tag: "BookmarksPersistence.retrievePageBookmarks") } }
gpl-3.0
iadmir/Signal-iOS
Signal/src/views/OWSAlerts.swift
1
2387
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation @objc class OWSAlerts: NSObject { let TAG = "[OWSAlerts]" /// Cleanup and present alert for no permissions public class func showNoMicrophonePermissionAlert() { let alertTitle = NSLocalizedString("CALL_AUDIO_PERMISSION_TITLE", comment:"Alert title when calling and permissions for microphone are missing") let alertMessage = NSLocalizedString("CALL_AUDIO_PERMISSION_MESSAGE", comment:"Alert message when calling and permissions for microphone are missing") let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) let dismissAction = UIAlertAction(title: CommonStrings.dismissButton, style: .cancel) let settingsString = NSLocalizedString("OPEN_SETTINGS_BUTTON", comment: "Button text which opens the settings app") let settingsAction = UIAlertAction(title: settingsString, style: .default) { _ in UIApplication.shared.openSystemSettings() } alertController.addAction(dismissAction) alertController.addAction(settingsAction) UIApplication.shared.frontmostViewController?.present(alertController, animated: true, completion: nil) } public class func showAlert(withTitle title: String) { self.showAlert(withTitle: title, message: nil, buttonTitle: nil) } public class func showAlert(withTitle title: String, message: String) { self.showAlert(withTitle: title, message: message, buttonTitle: nil) } public class func showAlert(withTitle title: String, message: String? = nil, buttonTitle: String? = nil) { assert(title.characters.count > 0) let actionTitle = (buttonTitle != nil ? buttonTitle : NSLocalizedString("OK", comment: "")) let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: nil)) UIApplication.shared.frontmostViewController?.present(alert, animated: true, completion: nil) } public class func cancelAction() -> UIAlertAction { let action = UIAlertAction(title: CommonStrings.cancelButton, style: .cancel) { _ in Logger.debug("Cancel item") // Do nothing. } return action } }
gpl-3.0
yzpniceboy/KeychainAccess
Lib/KeychainAccessTests/KeychainAccessTests.swift
6
27962
// // KeychainAccessTests.swift // KeychainAccessTests // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // import Foundation import XCTest import KeychainAccess class KeychainAccessTests: XCTestCase { override func setUp() { super.setUp() Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared").removeAll() Keychain(service: "Twitter").removeAll() Keychain(server: NSURL(string: "https://example.com")!, protocolType: .HTTPS).removeAll() Keychain().removeAll() } override func tearDown() { super.tearDown() } func locally(x: () -> ()) { x() } // MARK: func testGenericPassword() { locally { // Add Keychain items let keychain = Keychain(service: "Twitter") keychain.set("kishikawa_katsumi", key: "username") keychain.set("password_1234", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain.get("password") XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(service: "Twitter") keychain.set("katsumi_kishikawa", key: "username") keychain.set("1234_password", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain.get("password") XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(service: "Twitter") keychain.remove("username") keychain.remove("password") XCTAssertNil(keychain.get("username")) XCTAssertNil(keychain.get("password")) } } func testGenericPasswordSubscripting() { locally { // Add Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testInternetPassword() { locally { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain.set("kishikawa_katsumi", key: "username") keychain.set("password_1234", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain.get("password") XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain.set("katsumi_kishikawa", key: "username") keychain.set("1234_password", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain.get("password") XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain.remove("username") keychain.remove("password") XCTAssertNil(keychain.get("username")) XCTAssertNil(keychain.get("password")) } } func testInternetPasswordSubscripting() { locally { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testDefaultInitializer() { let keychain = Keychain() XCTAssertEqual(keychain.service, "") XCTAssertNil(keychain.accessGroup) } func testInitializerWithService() { let keychain = Keychain(service: "com.example.github-token") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertNil(keychain.accessGroup) } func testInitializerWithAccessGroup() { let keychain = Keychain(accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "") XCTAssertEqual(keychain.accessGroup!, "12ABCD3E4F.shared") } func testInitializerWithServiceAndAccessGroup() { let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertEqual(keychain.accessGroup!, "12ABCD3E4F.shared") } func testInitializerWithServer() { let URL = NSURL(string: "https://kishikawakatsumi.com")! let keychain = Keychain(server: URL, protocolType: .HTTPS) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.Default) } func testInitializerWithServerAndAuthenticationType() { let URL = NSURL(string: "https://kishikawakatsumi.com")! let keychain = Keychain(server: URL, protocolType: .HTTPS, authenticationType: .HTMLForm) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.HTMLForm) } // MARK: func testContains() { let keychain = Keychain(service: "Twitter") XCTAssertFalse(keychain.contains("username"), "not stored username") XCTAssertFalse(keychain.contains("password"), "not stored password") keychain.set("kishikawakatsumi", key: "username") XCTAssertTrue(keychain.contains("username"), "stored username") XCTAssertFalse(keychain.contains("password"), "not stored password") keychain.set("password1234", key: "password") XCTAssertTrue(keychain.contains("username"), "stored username") XCTAssertTrue(keychain.contains("password"), "stored password") } // MARK: func testSetString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.get("username"), "not stored username") XCTAssertNil(keychain.get("password"), "not stored password") keychain.set("kishikawakatsumi", key: "username") XCTAssertEqual(keychain.get("username")!, "kishikawakatsumi", "stored username") XCTAssertNil(keychain.get("password"), "not stored password") keychain.set("password1234", key: "password") XCTAssertEqual(keychain.get("username")!, "kishikawakatsumi", "stored username") XCTAssertEqual(keychain.get("password")!, "password1234", "stored password") } func testSetData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = NSJSONSerialization.dataWithJSONObject(JSONObject, options: nil, error: nil) let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.getData("JSONData"), "not stored JSON data") keychain.set(JSONData!, key: "JSONData") XCTAssertEqual(keychain.getData("JSONData")!, JSONData!, "stored JSON data") } func testRemoveString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.get("username"), "not stored username") XCTAssertNil(keychain.get("password"), "not stored password") keychain.set("kishikawakatsumi", key: "username") XCTAssertEqual(keychain.get("username")!, "kishikawakatsumi", "stored username") keychain.set("password1234", key: "password") XCTAssertEqual(keychain.get("password")!, "password1234", "stored password") keychain.remove("username") XCTAssertNil(keychain.get("username"), "removed username") XCTAssertEqual(keychain.get("password")!, "password1234", "left password") keychain.remove("password") XCTAssertNil(keychain.get("username"), "removed username") XCTAssertNil(keychain.get("password"), "removed password") } func testRemoveData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = NSJSONSerialization.dataWithJSONObject(JSONObject, options: nil, error: nil) let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.getData("JSONData"), "not stored JSON data") keychain.set(JSONData!, key: "JSONData") XCTAssertEqual(keychain.getData("JSONData")!, JSONData!, "stored JSON data") keychain.remove("JSONData") XCTAssertNil(keychain.getData("JSONData"), "removed JSON data") } // MARK: func testSubscripting() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain["username"], "not stored username") XCTAssertNil(keychain["password"], "not stored password") XCTAssertNil(keychain[string: "username"], "not stored username") XCTAssertNil(keychain[string: "password"], "not stored password") keychain["username"] = "kishikawakatsumi" XCTAssertEqual(keychain["username"]!, "kishikawakatsumi", "stored username") XCTAssertEqual(keychain[string: "username"]!, "kishikawakatsumi", "stored username") keychain["password"] = "password1234" XCTAssertEqual(keychain["password"]!, "password1234", "stored password") XCTAssertEqual(keychain[string: "password"]!, "password1234", "stored password") keychain["username"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertEqual(keychain["password"]!, "password1234", "left password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertEqual(keychain[string: "password"]!, "password1234", "left password") keychain["password"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertNil(keychain["password"], "removed password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertNil(keychain[string: "password"], "removed password") let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = NSJSONSerialization.dataWithJSONObject(JSONObject, options: nil, error: nil) XCTAssertNil(keychain[data:"JSONData"], "not stored JSON data") keychain[data: "JSONData"] = JSONData XCTAssertEqual(keychain[data:"JSONData"]!, JSONData!, "stored JSON data") } // MARK: #if os(iOS) func testErrorHandling() { if let error = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared").removeAll() { XCTAssertNil(error, "no error occurred") } if let error = Keychain(service: "Twitter").removeAll() { XCTAssertNil(error, "no error occurred") } if let error = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS).removeAll() { XCTAssertNil(error, "no error occurred") } if let error = Keychain().removeAll() { XCTAssertNil(error, "no error occurred") } locally { // Add Keychain items let keychain = Keychain(service: "Twitter") if let error = keychain.set("kishikawa_katsumi", key: "username") { XCTAssertNil(error, "no error occurred") } if let error = keychain.set("password_1234", key: "password") { XCTAssertNil(error, "no error occurred") } let username = keychain.getStringOrError("username") switch username { // enum case .Success: XCTAssertEqual(username.value!, "kishikawa_katsumi") case .Failure: XCTFail("unknown error occurred") } if let error = username.error { // error object XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "kishikawa_katsumi") } if username.succeeded { // check succeeded property XCTAssertEqual(username.value!, "kishikawa_katsumi") } else { XCTFail("unknown error occurred") } if username.failed { // failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "kishikawa_katsumi") } let password = keychain.getStringOrError("password") switch password { // enum case .Success: XCTAssertEqual(password.value!, "password_1234") case .Failure: XCTFail("unknown error occurred") } if let error = password.error { // error object XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "password_1234") } if password.succeeded { // check succeeded property XCTAssertEqual(password.value!, "password_1234") } else { XCTFail("unknown error occurred") } if password.failed { // failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "password_1234") } } locally { // Update Keychain items let keychain = Keychain(service: "Twitter") if let error = keychain.set("katsumi_kishikawa", key: "username") { XCTAssertNil(error, "no error occurred") } if let error = keychain.set("1234_password", key: "password") { XCTAssertNil(error, "no error occurred") } let username = keychain.getStringOrError("username") switch username { // enum case .Success: XCTAssertEqual(username.value!, "katsumi_kishikawa") case .Failure: XCTFail("unknown error occurred") } if let error = username.error { // error object XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "katsumi_kishikawa") } if username.succeeded { // check succeeded property XCTAssertEqual(username.value!, "katsumi_kishikawa") } else { XCTFail("unknown error occurred") } if username.failed { // failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "katsumi_kishikawa") } let password = keychain.getStringOrError("password") switch password { // enum case .Success: XCTAssertEqual(password.value!, "1234_password") case .Failure: XCTFail("unknown error occurred") } if let error = password.error { // check error object XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "1234_password") } if password.succeeded { // check succeeded property XCTAssertEqual(password.value!, "1234_password") } else { XCTFail("unknown error occurred") } if password.failed { // check failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "1234_password") } } locally { // Remove Keychain items let keychain = Keychain(service: "Twitter") if let error = keychain.remove("username") { XCTAssertNil(error, "no error occurred") } if let error = keychain.remove("password") { XCTAssertNil(error, "no error occurred") } XCTAssertNil(keychain.get("username")) XCTAssertNil(keychain.get("password")) } } #endif // MARK: func testSetStringWithCustomService() { let username_1 = "kishikawakatsumi" let password_1 = "password1234" let username_2 = "kishikawa_katsumi" let password_2 = "password_1234" let username_3 = "k_katsumi" let password_3 = "12341234" let service_1 = "" let service_2 = "com.kishikawakatsumi.KeychainAccess" let service_3 = "example.com" Keychain().removeAll() Keychain(service: service_1).removeAll() Keychain(service: service_2).removeAll() Keychain(service: service_3).removeAll() XCTAssertNil(Keychain().get("username"), "not stored username") XCTAssertNil(Keychain().get("password"), "not stored password") XCTAssertNil(Keychain(service: service_1).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_1).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain().set(username_1, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertNil(Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") Keychain(service: service_1).set(username_1, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertNil(Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") Keychain(service: service_2).set(username_2, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "stored username") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") Keychain(service: service_3).set(username_3, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "stored username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "stored username") Keychain().set(password_1, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertNil(Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain(service: service_1).set(password_1, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertNil(Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain(service: service_2).set(password_2, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "stored password") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain(service: service_3).set(password_3, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "stored password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "stored password") Keychain().remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "left username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "left username") Keychain(service: service_1).remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "left username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "left username") Keychain(service: service_2).remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(Keychain(service: service_2).get("username"), "removed username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "left username") Keychain(service: service_3).remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(Keychain(service: service_2).get("username"), "removed username") XCTAssertNil(Keychain(service: service_3).get("username"), "removed username") Keychain().remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "left password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "left password") Keychain(service: service_1).remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "left password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "left password") Keychain(service: service_2).remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_1).get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "left password") Keychain(service: service_3).remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") } }
mit
CaiMiao/CGSSGuide
DereGuide/Toolbox/EventInfo/Model/EventLogItem.swift
1
1162
// // EventLogItem.swift // DereGuide // // Created by zzk on 2017/1/24. // Copyright © 2017年 zzk. All rights reserved. // import Foundation import SwiftyJSON class EventLogItem: NSObject { var date : String! var _storage: [Int: Int] subscript (border: Int) -> Int { return _storage[border] ?? 0 } /** * Instantiate the instance using the passed json values to set the properties values */ init?(fromJson json: JSON, borders: [Int]) { if json.isEmpty { return nil } _storage = [Int: Int]() date = json["date"].stringValue for border in [1, 2, 3] { _storage[border] = json[String(border)].intValue } for border in borders { _storage[border] = json[String(border)].intValue } super.init() // fix remote mismatching if borders.contains(40000) && _storage[40000] == 0 { _storage[40000] = json["50000"].intValue } else if borders.contains(50000) && _storage[50000] == 0 { _storage[50000] = json["40000"].intValue } } }
mit
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/ROGoogleTranslate/Source/ROGoogleTranslate.swift
1
3760
// // ROGoogleTranslate.swift // ROGoogleTranslate // // Created by Robin Oster on 20/10/16. // Copyright © 2016 prine.ch. All rights reserved. // import Foundation public struct ROGoogleTranslateParams { public init() { } public init(source:String, target:String, text:String) { self.source = source self.target = target self.text = text } public var source = "de" public var target = "en" public var text = "Ich glaube, du hast den Text zum Übersetzen vergessen" } /// Offers easier access to the Google Translate API open class ROGoogleTranslate { /// Store here the Google Translate API Key public var apiKey = "" /// /// Initial constructor /// public init() { } /// /// Translate a phrase from one language into another /// /// - parameter params: ROGoogleTranslate Struct contains all the needed parameters to translate with the Google Translate API /// - parameter callback: The translated string will be returned in the callback /// open func translate(params:ROGoogleTranslateParams, callback:@escaping (_ translatedText:String) -> ()) { guard apiKey != "" else { print("Warning: You should set the api key before calling the translate method.") return } if let urlEncodedText = params.text.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { if let url = URL(string: "https://www.googleapis.com/language/translate/v2?key=\(self.apiKey)&q=\(urlEncodedText)&source=\(params.source)&target=\(params.target)&format=text") { let httprequest = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in guard error == nil else { print("Something went wrong: \(error?.localizedDescription)") return } if let httpResponse = response as? HTTPURLResponse { guard httpResponse.statusCode == 200 else { print("Something went wrong: \(data)") return } do { // Pyramid of optional json retrieving. I know with SwiftyJSON it would be easier, but I didn't want to add an external library if let data = data { if let json = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary { if let jsonData = json["data"] as? [String : Any] { if let translations = jsonData["translations"] as? [NSDictionary] { if let translation = translations.first as? [String : Any] { if let translatedText = translation["translatedText"] as? String { callback(translatedText) } } } } } } } catch { print("Serialization failed: \(error.localizedDescription)") } } }) httprequest.resume() } } } }
apache-2.0
ngominhtrint/Twittient
Twittient/TimeAgo.swift
1
1439
// // TimeAgo.swift // Twittient // // Created by TriNgo on 3/25/16. // Copyright © 2016 TriNgo. All rights reserved. // import Foundation public func timeAgoSince(date: NSDate) -> String { let calendar = NSCalendar.currentCalendar() let now = NSDate() let unitFlags: NSCalendarUnit = [.Second, .Minute, .Hour, .Day, .WeekOfYear, .Month, .Year] let components = calendar.components(unitFlags, fromDate: date, toDate: now, options: []) if components.year >= 2 { return "\(components.year)y" } if components.year >= 1 { return "1y" } if components.month >= 2 { return "\(components.month)m" } if components.month >= 1 { return "1m" } if components.weekOfYear >= 2 { return "\(components.weekOfYear)w" } if components.weekOfYear >= 1 { return "1w" } if components.day >= 2 { return "\(components.day)d" } if components.day >= 1 { return "1d" } if components.hour >= 2 { return "\(components.hour)h" } if components.hour >= 1 { return "1h" } if components.minute >= 2 { return "\(components.minute)min" } if components.minute >= 1 { return "1min" } if components.second >= 3 { return "\(components.second)s" } return "now" }
apache-2.0
himadrisj/SiriPay
Client/SiriPay/SiriPay/SPOTPViewController.swift
1
2161
// // SPOTPViewController.swift // SiriPay // // Created by Jatin Arora on 10/09/16. // Copyright // import Foundation class SPOTPViewController : UIViewController { @IBOutlet weak var nextButton: UIBarButtonItem! var otpString: String? @IBOutlet weak var otpField: UITextField! override func viewDidLoad() { if (!UserDefaults.standard.bool(forKey: kDefaults_SignedIn)) { SPPaymentController.sharedInstance.requestOTPForSignIn(email: TEST_EMAIL, mobileNo: TEST_MOBILE) { (result, error) in } } } @IBAction func nextButtonTapped(_ sender: AnyObject) { SPPaymentController.sharedInstance.doSignIn(otp: otpField.text!) { (error) in if error == nil { UserDefaults.standard.set(true, forKey: kDefaults_SignedIn) UserDefaults.standard.synchronize() self.performSegue(withIdentifier: "SiriPaySegueIdentifier", sender: nil) } else { CTSOauthManager.readPasswordSigninOuthData(); print("Wrong OTP with error = \(error)") let alert = UIAlertController(title: "Wrong OTP", message:"Please try again", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } } } } extension SPOTPViewController : UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField.text?.characters.count == 3 { nextButton.isEnabled = true } return true } }
mit
peterlafferty/LuasLife
LuasLifeKit/GetLinesRequest.swift
1
2106
// // GetLinesRequest.swift // LuasLife // // Created by Peter Lafferty on 29/02/2016. // Copyright © 2016 Peter Lafferty. All rights reserved. // import Foundation import Alamofire import Decodable public struct URLs { fileprivate static let bundleIdentifier = "com.peterlafferty.LuasLifeKit" public static var getLines = URL(string: "http://localhost/index.php/lines")! public static var getRoutes = URL(string: "http://localhost/index.php/routes?line-id=1")! //public static var getRoutes = "https://data.dublinked.ie/cgi-bin/rtpi/routeinformation?format=json&operator=LUAS&routeid=RED" // swiftlint:disable:this line_length public static var getStops = URL(string: "http://localhost/index.php/stops?route-id=1")! public static var getRealTimeInfo = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=LUAS21&routeid=RED&maxresults=100&operator=Luas" // swiftlint:disable:this line_length } /// This struct represents the lines on the Luas. public struct GetLinesRequest { let url: URL let completionHandler: (Result<[Line]>) -> Void /** Initialises the request with the url and completion handler - parameter url: the url to use - parameter completionHandler: a closure to call when the request has completed The current routes are: - Green - Red */ public init(url: URL = URLs.getLines, completionHandler: @escaping (Result<[Line]>) -> Void) { self.url = url self.completionHandler = completionHandler } public func start() { Alamofire.request(url).responseJSON { (response) -> Void in switch response.result { case .success(let data): do { let lines = try [Line].decode(data => "results") self.completionHandler(.success(lines)) } catch { self.completionHandler(.error(error)) } case .failure(let error): self.completionHandler(.error(error)) } } } }
mit
a20251313/LTMorphingLabelDemo_formother
LTMorphingLabel/LTMorphingLabel+Burn.swift
1
7213
// // LTMorphingLabel+Burn.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2014 Lex Tang, http://LexTang.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 QuartzCore extension LTMorphingLabel { func _burningImageForCharLimbo(charLimbo: LTCharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect) { let maskedHeight = charLimbo.rect.size.height * max(0.01, progress) let maskedSize = CGSizeMake( charLimbo.rect.size.width, maskedHeight) UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.mainScreen().scale) let rect = CGRectMake(0, 0, charLimbo.rect.size.width, maskedHeight) String(charLimbo.char).drawInRect(rect, withAttributes: [ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.textColor ]) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let newRect = CGRectMake( charLimbo.rect.origin.x, charLimbo.rect.origin.y, charLimbo.rect.size.width, maskedHeight) return (newImage, newRect) } func BurnLoad() { _startClosures["Burn\(LTMorphingPhaseStart)"] = { self.emitterView.removeAllEmit() } _progressClosures["Burn\(LTMorphingPhaseManipulateProgress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.5 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } _effectClosures["Burn\(LTMorphingPhaseDisappear)"] = { (char:Character, index: Int, progress: Float) in return LTCharacterLimbo( char: char, rect: self._originRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0 ) } _effectClosures["Burn\(LTMorphingPhaseAppear)"] = { (char:Character, index: Int, progress: Float) in if char != " " { let rect = self._newRects[index] let emitterPosition = CGPointMake( rect.origin.x + rect.size.width / 2.0, CGFloat(progress) * rect.size.height / 1.6 + rect.origin.y * 1.4) self.emitterView.createEmitter("c\(index)", duration: self.morphingDuration) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 1) layer.renderMode = kCAEmitterLayerAdditive layer.emitterMode = kCAEmitterLayerOutline cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 200.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) cell.contents = UIImage(named: "Fire")?.CGImage cell.emissionLongitude = 0 cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = -1.0 cell.yAcceleration = 10 cell.velocity = CGFloat(10 + Int(arc4random_uniform(3))) cell.velocityRange = 10 cell.spin = 0 cell.spinRange = 0 cell.lifetime = self.morphingDuration }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() self.emitterView.createEmitter("s\(index)", duration: self.morphingDuration) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 10) layer.renderMode = kCAEmitterLayerUnordered layer.emitterMode = kCAEmitterLayerOutline cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 40.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) / Float(arc4random_uniform(10) + 20) cell.contents = UIImage(named: "Smoke")?.CGImage cell.emissionLongitude = 0 cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = self.morphingDuration / -3.0 cell.yAcceleration = 10 cell.velocity = CGFloat(20 + Int(arc4random_uniform(15))) cell.velocityRange = 20 cell.spin = CGFloat(Float(arc4random_uniform(30)) / 10.0) cell.spinRange = 5 cell.lifetime = self.morphingDuration }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() } return LTCharacterLimbo( char: char, rect: self._newRects[index], alpha: 1.0, size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } _drawingClosures["Burn\(LTMorphingPhaseDraw)"] = { (charLimbo: LTCharacterLimbo) in if charLimbo.drawingProgress > 0.0 { let (charImage, rect) = self._burningImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress) charImage.drawInRect(rect) return true } return false } _skipFramesClosures["Burn\(LTMorphingPhaseSkipFrames)"] = { return 1 } } }
mit
4taras4/totp-auth
TOTP/ViperModules/MainList/Module/Router/MainListRouter.swift
1
964
// // MainListMainListRouter.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import UIKit final class MainListRouter: MainListRouterInput { weak var transitionHandler: UIViewController! func openSettings() { let settingsViewController = SettingsViewController.instantiate(useSwinject: true) transitionHandler.navigationController?.pushViewController(settingsViewController, animated: true) } func addItem() { let newItemViewController = AddItemViewController.instantiate(useSwinject: true) transitionHandler.navigationController?.pushViewController(newItemViewController, animated: true) } func openFolder(item: Folder) { let newItemViewController = FolderDetailsViewController.instantiate(with: item) transitionHandler.navigationController?.pushViewController(newItemViewController, animated: true) } }
mit
zhangliangzhi/iosStudyBySwift
SavePassword/SavePassword/AddViewController.swift
1
6375
// // AddViewController.swift // SavePassword // // Created by ZhangLiangZhi on 2016/12/21. // Copyright © 2016年 xigk. All rights reserved. // import UIKit import CloudKit class AddViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate { @IBOutlet weak var localTitle: UILabel! @IBOutlet weak var localURL: UILabel! @IBOutlet weak var localNote: UILabel! @IBOutlet weak var localSave: UIButton! @IBOutlet weak var localCancle: UIButton! @IBOutlet weak var sortID: UITextField! @IBOutlet weak var tfTitle: UITextField! @IBOutlet weak var urltxt: UITextField! @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() sortID.delegate = self tfTitle.delegate = self urltxt.delegate = self textView.delegate = self self.title = NSLocalizedString("Add", comment: "") // 加监听 NotificationCenter.default.addObserver(self, selector: #selector(tvBegin), name: .UITextViewTextDidBeginEditing, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(tvEnd), name: .UITextViewTextDidEndEditing, object: nil) // init data urltxt.text = "www." initLocalize() textView.text = NSLocalizedString("Account", comment: "") + ": \n\n" + NSLocalizedString("Password", comment: "") + ":" initSortID() tfTitle.becomeFirstResponder() } func initSortID() { if arrData.count == 0 { sortID.text = String(1) }else { let lastID:Int64 = arrData[arrData.count-1]["ID"] as! Int64 sortID.text = String( lastID + 1) } } override func viewWillAppear(_ animated: Bool) { // initLocalize() } func initLocalize() { localTitle.text = NSLocalizedString("Title", comment: "") + ":" localURL.text = NSLocalizedString("URL", comment: "") + ":" localNote.text = NSLocalizedString("Note", comment: "") localCancle.setTitle(NSLocalizedString("Cancel", comment: ""), for: .normal) localSave.setTitle(NSLocalizedString("Save", comment: ""), for: .normal) sortID.placeholder = NSLocalizedString("Enter Sort ID", comment: "") tfTitle.placeholder = NSLocalizedString("Enter Title", comment: "") urltxt.placeholder = NSLocalizedString("Enter URL", comment: "") } func tvBegin() { // print("text view begin") } func tvEnd() { // print("text view end") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == sortID { tfTitle.becomeFirstResponder() }else if textField == tfTitle { urltxt.becomeFirstResponder() }else if textField == urltxt { textView.becomeFirstResponder() }else{ } return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { // 延迟1毫秒 执行 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_SEC))/Double(1000*NSEC_PER_SEC) , execute: { self.textView.resignFirstResponder() }) } return true } // 保存数据 @IBAction func saveAction(_ sender: Any) { var id:String = sortID.text! var title:String = tfTitle.text! var url:String = urltxt.text! let spData:String = textView.text! id = id.trimmingCharacters(in: .whitespaces) title = title.trimmingCharacters(in: .whitespaces) url = url.trimmingCharacters(in: .whitespaces) // id 是否为空 if id == "" { self.view.makeToast(NSLocalizedString("IDnot", comment: ""), duration: 3.0, position: .center) initSortID() return } let iID = Int64(id) if iID == nil { self.view.makeToast(NSLocalizedString("IDnot", comment: ""), duration: 3.0, position: .center) initSortID() return } // id是否重复 // for i in 0..<arrData.count { // let getID = arrData[i].value(forKey: "ID") // let igetID:Int64 = getID as! Int64 // if iID == igetID { // self.view.makeToast(NSLocalizedString("IDre", comment: ""), duration: 3.0, position: .center) // return // } // } self.view.isUserInteractionEnabled = false let one = CKRecord(recordType: "SavePassword") one["ID"] = iID as CKRecordValue? one["title"] = title as CKRecordValue? one["url"] = url as CKRecordValue? one["spdata"] = spData as CKRecordValue? CKContainer.default().privateCloudDatabase.save(one) { (record:CKRecord?, err:Error?) in if err == nil { print("save sucess") // 保存成功 DispatchQueue.main.async { arrData.append(one) // self.view.makeToast(NSLocalizedString("savesucess", comment: ""), duration: 3.0, position: .center) self.navigationController!.popViewController(animated: true) } }else { // 保存不成功 print("save fail", err?.localizedDescription) DispatchQueue.main.async { self.view.isUserInteractionEnabled = true // 弹框网络不行 let alert = UIAlertController(title: "⚠️ iCloud ⚠️", message: err?.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { (action:UIAlertAction) in })) self.present(alert, animated: true, completion: nil) } } } } // 取消 @IBAction func cancleAction(_ sender: Any) { navigationController!.popViewController(animated: true) } }
mit
practicalswift/swift
validation-test/stdlib/Slice/Slice_Of_MinimalMutableRangeReplaceableCollection_WithSuffix.swift
16
3849
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<MinimalMutableRangeReplaceableCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = MinimalMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<MinimalMutableRangeReplaceableCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = MinimalMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<MinimalMutableRangeReplaceableCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = MinimalMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addRangeReplaceableSliceTests( "Slice_Of_MinimalMutableRangeReplaceableCollection_WithSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 ) SliceTests.addMutableCollectionTests( "Slice_Of_MinimalMutableRangeReplaceableCollection_WithSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) runAllTests()
apache-2.0
qinting513/Learning-QT
2016 Plan/8月/循环引用之 ContactsDemo - 闭包swift/ContactsDemo/AppDelegate.swift
1
2141
// // AppDelegate.swift // ContactsDemo // // Created by Qinting on 16/9/4. // Copyright © 2016年 Qinting. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/ERC20Kit/Domain/Account/ERC20AssetFactory.swift
1
277
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import PlatformKit final class ERC20AssetFactory: ERC20AssetFactoryAPI { func erc20Asset(erc20AssetModel: AssetModel) -> CryptoAsset { ERC20Asset(erc20Token: erc20AssetModel) } }
lgpl-3.0
huonw/swift
test/IRGen/function-target-features.swift
33
1785
// This test verifies that we produce target-cpu and target-features attributes // on functions. // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx | %FileCheck %s -check-prefix=AVX-FEATURE // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx512f -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx512er | %FileCheck %s -check-prefix=TWO-AVX // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc corei7 | %FileCheck %s -check-prefix=CORE-CPU // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc corei7 -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx | %FileCheck %s -check-prefix=CORE-CPU-AND-FEATURES // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc x86-64 | %FileCheck %s -check-prefix=X86-64-CPU // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc corei7-avx -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc -avx | %FileCheck %s -check-prefix=AVX-MINUS-FEATURE // REQUIRES: CPU=x86_64 func test() { } // AVX-FEATURE: "target-features"{{.*}}+avx // TWO-AVX: "target-features"= // TWO-AVX-DAG: +avx512er // TWO-AVX-DAG: +avx512f // CORE-CPU: "target-cpu"="corei7" // CORE-CPU-AND-FEATURES: "target-cpu"="corei7" "target-features"={{.*}}+avx // X86-64-CPU: "target-cpu"="x86-64" // AVX-MINUS-FEATURE: "target-features"={{.*}}-avx
apache-2.0
abiaoLHB/LHBWeiBo-Swift
LHBWeibo/LHBWeibo/MainWibo/Compose/ComposeTextView.swift
1
1115
// // ComposeTextView.swift // LHBWeibo // // Created by LHB on 16/8/24. // Copyright © 2016年 LHB. All rights reserved. // import UIKit import SnapKit class ComposeTextView: UITextView { //MARK: - 懒加载属性 lazy var placeHolderLabel : UILabel = UILabel() //从xib加载写这个方法里也行 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } //写这个方法里也行 override func awakeFromNib() { addSubview(placeHolderLabel) placeHolderLabel.snp_makeConstraints { (make) in make.top.equalTo(5) make.left.equalTo(10) } placeHolderLabel.textColor = UIColor.lightGrayColor() placeHolderLabel.font = font placeHolderLabel.text = "分享新鲜事..." //设置内容的内边距 textContainerInset = UIEdgeInsets(top: 5, left: 8, bottom: 0, right: 8) } } //MARK: - 设置UI界面 extension ComposeTextView{ private func setupUI(){ font = UIFont.systemFontOfSize(17.0) } }
apache-2.0
YQqiang/Nunchakus
NunchakusTests/NunchakusTests.swift
1
974
// // NunchakusTests.swift // NunchakusTests // // Created by sungrow on 2017/3/21. // Copyright © 2017年 sungrow. All rights reserved. // import XCTest @testable import Nunchakus class NunchakusTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
icecoffin/GlossLite
GlossLite/Views/Base/NavigationController.swift
1
466
// // NavigationController.swift // GlossLite // // Created by Daniel on 03/10/16. // Copyright © 2016 icecoffin. All rights reserved. // import UIKit class NavigationController: UINavigationController { override func viewDidLoad() { navigationBar.titleTextAttributes = [NSFontAttributeName: Fonts.openSansSemibold(size: 18)] UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: Fonts.openSans(size: 16)], for: .normal) } }
mit
xhamr/fave-button
Source/Helpers/Easing.swift
1
4131
// // Easing.swift // FaveButton // // Copyright © 2016 Jansel Valentin. // // 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 typealias Easing = (_ t:CGFloat,_ b:CGFloat,_ c:CGFloat,_ d:CGFloat)-> CGFloat typealias ElasticEasing = (_ t:CGFloat,_ b:CGFloat,_ c:CGFloat,_ d:CGFloat,_ a:CGFloat,_ p:CGFloat)-> CGFloat // ELASTIC EASING struct Elastic{ static var EaseIn :Easing = { (_t,b,c,d) -> CGFloat in var t = _t if t==0{ return b } t/=d if t==1{ return b+c } let p = d * 0.3 let a = c let s = p/4 t -= 1 return -(a*pow(2,10*t) * sin( (t*d-s)*(2*(.pi))/p )) + b; } static var EaseOut :Easing = { (_t,b,c,d) -> CGFloat in var t = _t if t==0{ return b } t/=d if t==1{ return b+c} let p = d * 0.3 let a = c let s = p/4 return (a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p ) + c + b); } static var EaseInOut :Easing = { (_t,b,c,d) -> CGFloat in var t = _t if t==0{ return b} t = t/(d/2) if t==2{ return b+c } let p = d * (0.3*1.5) let a = c let s = p/4 if t < 1 { t -= 1 return -0.5*(a*pow(2,10*t) * sin((t*d-s)*(2*(.pi))/p )) + b; } t -= 1 return a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p )*0.5 + c + b; } } extension Elastic{ static var ExtendedEaseIn :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in var t = _t var a = _a var p = _p var s:CGFloat = 0.0 if t==0{ return b } t /= d if t==1{ return b+c } if a < abs(c) { a=c; s = p/4 }else { s = p/(2*(.pi)) * asin (c/a); } t -= 1 return -(a*pow(2,10*t) * sin( (t*d-s)*(2*(.pi))/p )) + b; } static var ExtendedEaseOut :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in var s:CGFloat = 0.0 var t = _t var a = _a var p = _p if t==0 { return b } t /= d if t==1 {return b+c} if a < abs(c) { a=c; s = p/4; }else { s = p/(2*(.pi)) * asin (c/a) } return (a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p ) + c + b) } static var ExtendedEaseInOut :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in var s:CGFloat = 0.0 var t = _t var a = _a var p = _p if t==0{ return b } t /= d/2 if t==2{ return b+c } if a < abs(c) { a=c; s=p/4; }else { s = p/(2*(.pi)) * asin (c/a) } if t < 1 { t -= 1 return -0.5*(a*pow(2,10*t) * sin( (t*d-s)*(2*(.pi))/p )) + b; } t -= 1 return a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p )*0.5 + c + b; } }
mit
kysonyangs/ysbilibili
ysbilibili/Classes/WebView/YSBilibiliWebViewController.swift
1
2037
// // YSBilibiliWebViewController.swift // ysbilibili // // Created by MOLBASE on 2017/8/5. // Copyright © 2017年 YangShen. All rights reserved. // import UIKit import WebKit class YSBilibiliWebViewController: YSBaseViewController { // 展示的url var urlString:String? // MARK: - 懒加载控件 lazy var contentWebView: WKWebView = { let contentWebView = WKWebView() contentWebView.navigationDelegate = self return contentWebView }() // MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() // 1. 初始化ui setupUI() // 2. 加载url loadRequest() } } extension YSBilibiliWebViewController { fileprivate func setupUI() { view.addSubview(contentWebView) contentWebView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(view) make.top.equalTo(view).offset(kNavBarHeight) } } fileprivate func loadRequest() { guard let urlString = urlString else {return} guard let url = URL(string: urlString) else {return} let request = URLRequest(url: url) contentWebView.load(request) } } //====================================================================== // MARK:- wkwebview delegate //====================================================================== extension YSBilibiliWebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { naviBar.titleLabel.font = UIFont.systemFont(ofSize: 15) naviBar.titleLabel.text = webView.title } } //====================================================================== // MARK:- target action //====================================================================== extension YSBilibiliWebViewController { @objc fileprivate func pravitePopViewController() { _ = navigationController?.popViewController(animated: true) } }
mit
Jnosh/swift
validation-test/compiler_crashers_fixed/02034-swift-optional-swift-diagnostic-operator.swift
65
527
// 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: not %target-swift-frontend %s -typecheck protocol A { } protocol A { protocol a : A { func c(a: ((A) -> Any) { c super.g = b<D>(f<T>: l.c, U) { } } } func a<I : a { retu
apache-2.0
djschilling/SOPA-iOS
SOPA/view/LevelMode/LevelSelectButton.swift
1
2728
// // LevelButton.swift // SOPA // // Created by Raphael Schilling on 01.09.18. // Copyright © 2018 David Schilling. All rights reserved. // import Foundation import SpriteKit class LevelSelectButton: SKSpriteNode { let green = UIColor(red: 169.0 / 255.0, green: 162.0 / 255.0, blue: 121.0 / 255.0, alpha: 1.0) let grey = UIColor(red: 0.5 , green: 0.5, blue: 0.5, alpha: 1.0) let levelInfo: LevelInfo init(levelInfo: LevelInfo, levelButtonPositioner: LevelButtonPositioner) { self.levelInfo = levelInfo if !levelInfo.locked { let texture = SKTexture(imageNamed: "Level") super.init(texture: texture, color: UIColor.clear, size: levelButtonPositioner.getLevelSize()) position = levelButtonPositioner.getLevelPosition(id: levelInfo.levelId) addStars(stars: levelInfo.stars) addLable(id: levelInfo.levelId, color: green) } else { let texture = SKTexture(imageNamed: "LevelSW") super.init(texture: texture, color: UIColor.clear, size: levelButtonPositioner.getLevelSize()) position = levelButtonPositioner.getLevelPosition(id: levelInfo.levelId) addLable(id: levelInfo.levelId, color: grey) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addStars(stars: Int) { let star1: SKSpriteNode = generateStar(achieved: stars >= 1) let star2: SKSpriteNode = generateStar(achieved: stars >= 2) let star3: SKSpriteNode = generateStar(achieved: stars >= 3) star1.position = CGPoint(x: -size.width * 0.25, y: -size.height * 0.2) star2.position = CGPoint(x: 0, y: -size.height * 0.27 ) star3.position = CGPoint(x: size.width * 0.25, y: -size.height * 0.2) addChild(star1) addChild(star2) addChild(star3) } func addLable(id: Int, color: UIColor) { let idLable = SKLabelNode(fontNamed: "Optima-Bold") idLable.text = String(id) idLable.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center idLable.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center idLable.fontSize = size.height * 0.34 idLable.fontColor = color idLable.zPosition = zPosition + 1 addChild(idLable) } func generateStar(achieved: Bool) -> SKSpriteNode { var star = SKSpriteNode(imageNamed: "starSW") if achieved { star = SKSpriteNode(imageNamed: "star") } star.size = CGSize(width: size.width/3, height: size.height/3) star.zPosition = zPosition + 1 return star } }
apache-2.0
swiftde/Udemy-Swift-Kurs
AlamoApp/AlamoApp/AppDelegate.swift
1
6109
// // AppDelegate.swift // AlamoApp // // Created by Udemy on 25.02.15. // Copyright (c) 2015 benchr. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "de.benchr.AlamoApp" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("AlamoApp", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("AlamoApp.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
apache-2.0
Miguel-Herrero/Swift
Landmarks/Landmarks/PageView.swift
1
880
// // PageView.swift // Landmarks // // Created by Miguel Herrero Baena on 20/06/2019. // Copyright © 2019 Miguel Herrero Baena. All rights reserved. // import SwiftUI struct PageView<Page: View>: View { var viewControllers: [UIHostingController<Page>] @State var currentPage = 0 init(_ views: [Page]) { self.viewControllers = views.map { UIHostingController(rootView: $0) } } var body: some View { ZStack(alignment: .bottomTrailing) { PageViewController(controllers: viewControllers, currentPage: $currentPage) PageControl(numberOfPages: viewControllers.count, currentPage: $currentPage) .padding(.trailing) } } } #if DEBUG struct PageView_Previews: PreviewProvider { static var previews: some View { PageView(features.map { FeatureCard(landmark: $0) }) } } #endif
gpl-3.0
SusanDoggie/DoggieGP
Sources/Metal/mtlFunction.swift
1
3829
// // mtlFunction.swift // // The MIT License // Copyright (c) 2015 - 2018 Susan Cheng. 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 Metal extension Metal { public final class Library : LibraryProtocol { let library: MTLLibrary fileprivate init(library: MTLLibrary) { self.library = library } } public final class Function : FunctionProtocol { let function: MTLFunction let pipelineState: MTLComputePipelineState fileprivate init(function: MTLFunction) { self.function = function do { self.pipelineState = try function.device.makeComputePipelineState(function: function) } catch let error { print(error) fatalError() } } public func maxTotalThreadsPerThreadgroup(with device: Device) -> Int { return pipelineState.maxTotalThreadsPerThreadgroup } public func preferredThreadgroupSizeMultiple(with device: Device) -> Int { return pipelineState.threadExecutionWidth } } public var defaultLibrary: Library? { return device.makeDefaultLibrary().map(Library.init) } @available(iOS 10.0, tvOS 10.0, OSX 10.12, *) public func defaultLibrary(bundle: Bundle) throws -> Library { return Library(library: try device.makeDefaultLibrary(bundle: bundle)) } public func loadLibrary(path: String) throws -> Library { return Library(library: try device.makeLibrary(filepath: path)) } public func library(source: String) throws -> Library { return Library(library: try device.makeLibrary(source: source, options: nil)) } public func library(source: String, options: MTLCompileOptions) throws -> Library { return Library(library: try device.makeLibrary(source: source, options: options)) } } extension Metal.Library { public var functionNames: [String] { return library.functionNames } public func function(name: String) -> Metal.Function { return Metal.Function(function: library.makeFunction(name: name)!) } @available(iOS 10.0, tvOS 10.0, OSX 10.12, *) public func function(name: String, constantValues: MTLFunctionConstantValues) -> Metal.Function { do { return Metal.Function(function: try library.makeFunction(name: name, constantValues: constantValues)) } catch let error { print(error) fatalError() } } }
mit
konduruvijaykumar/ios-sample-apps
MapsDemoApp/MapsDemoApp/AppDelegate.swift
1
2171
// // AppDelegate.swift // MapsDemoApp // // Created by Vijay Konduru on 06/02/17. // Copyright © 2017 PJay. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
orta/eidolon
KioskTests/Bid Fulfillment/UserCreationViewControllerTests.swift
1
305
import Quick import Nimble class UserCreationViewControllerTests: QuickSpec { override func spec() { it("looks right by default") { let sut = UserCreationViewController.instantiateFromStoryboard() expect(sut).to(haveValidSnapshot(named:"default")) } } }
mit
tkester/swift-algorithm-club
Dijkstra Algorithm/VisualizedDijkstra.playground/Sources/Window.swift
1
12128
import Foundation import UIKit public protocol GraphDelegate: class { func willCompareVertices(startVertexPathLength: Double, edgePathLength: Double, endVertexPathLength: Double) func didFinishCompare() func didCompleteGraphParsing() func didTapWrongVertex() func didStop() func willStartVertexNeighborsChecking() func didFinishVertexNeighborsChecking() } public class Window: UIView, GraphDelegate { public var graphView: GraphView! private var topView: UIView! private var createGraphButton: RoundedButton! private var startVisualizationButton: RoundedButton! private var startInteractiveVisualizationButton: RoundedButton! private var startButton: UIButton! private var pauseButton: UIButton! private var stopButton: UIButton! private var comparisonLabel: UILabel! private var activityIndicator: UIActivityIndicatorView! private var graph: Graph! private var numberOfVertices: UInt! private var graphColors = GraphColors.sharedInstance public override init(frame: CGRect) { super.init(frame: frame) self.frame = frame backgroundColor = graphColors.mainWindowBackgroundColor } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func configure(graph: Graph) { self.graph = graph graph.createNewGraph() graph.delegate = self let frame = CGRect(x: 10, y: 170, width: self.frame.width - 20, height: self.frame.height - 180) graphView = GraphView(frame: frame, graph: graph) graphView.createNewGraph() addSubview(graphView) configureCreateGraphButton() configureStartVisualizationButton() configureStartInteractiveVisualizationButton() configureStartButton() configurePauseButton() configureStopButton() configureComparisonLabel() configureActivityIndicator() topView = UIView(frame: CGRect(x: 10, y: 10, width: frame.width - 20, height: 150)) topView.backgroundColor = graphColors.topViewBackgroundColor topView.layer.cornerRadius = 15 addSubview(topView) topView.addSubview(createGraphButton) topView.addSubview(startVisualizationButton) topView.addSubview(startInteractiveVisualizationButton) topView.addSubview(startButton) topView.addSubview(pauseButton) topView.addSubview(stopButton) topView.addSubview(comparisonLabel) topView.addSubview(activityIndicator) } private func configureCreateGraphButton() { let frame = CGRect(x: center.x - 200, y: 12, width: 100, height: 34) createGraphButton = RoundedButton(frame: frame) createGraphButton.setTitle("New graph", for: .normal) createGraphButton.addTarget(self, action: #selector(createGraphButtonTap), for: .touchUpInside) } private func configureStartVisualizationButton() { let frame = CGRect(x: center.x - 50, y: 12, width: 100, height: 34) startVisualizationButton = RoundedButton(frame: frame) startVisualizationButton.setTitle("Auto", for: .normal) startVisualizationButton.addTarget(self, action: #selector(startVisualizationButtonDidTap), for: .touchUpInside) } private func configureStartInteractiveVisualizationButton() { let frame = CGRect(x: center.x + 100, y: 12, width: 100, height: 34) startInteractiveVisualizationButton = RoundedButton(frame: frame) startInteractiveVisualizationButton.setTitle("Interactive", for: .normal) startInteractiveVisualizationButton.addTarget(self, action: #selector(startInteractiveVisualizationButtonDidTap), for: .touchUpInside) } private func configureStartButton() { let frame = CGRect(x: center.x - 65, y: 56, width: 30, height: 30) startButton = UIButton(frame: frame) let playImage = UIImage(named: "Start.png") startButton.setImage(playImage, for: .normal) startButton.isEnabled = false startButton.addTarget(self, action: #selector(didTapStartButton), for: .touchUpInside) } private func configurePauseButton() { let frame = CGRect(x: center.x - 15, y: 56, width: 30, height: 30) pauseButton = UIButton(frame: frame) let pauseImage = UIImage(named: "Pause.png") pauseButton.setImage(pauseImage, for: .normal) pauseButton.isEnabled = false pauseButton.addTarget(self, action: #selector(didTapPauseButton), for: .touchUpInside) } private func configureStopButton() { let frame = CGRect(x: center.x + 35, y: 56, width: 30, height: 30) stopButton = UIButton(frame: frame) let stopImage = UIImage(named: "Stop.png") stopButton.setImage(stopImage, for: .normal) stopButton.isEnabled = false stopButton.addTarget(self, action: #selector(didTapStopButton), for: .touchUpInside) } private func configureComparisonLabel() { let size = CGSize(width: 250, height: 42) let origin = CGPoint(x: center.x - 125, y: 96) let frame = CGRect(origin: origin, size: size) comparisonLabel = UILabel(frame: frame) comparisonLabel.textAlignment = .center comparisonLabel.text = "Have fun!" } private func configureActivityIndicator() { let size = CGSize(width: 50, height: 42) let origin = CGPoint(x: center.x - 25, y: 100) let activityIndicatorFrame = CGRect(origin: origin, size: size) activityIndicator = UIActivityIndicatorView(frame: activityIndicatorFrame) activityIndicator.activityIndicatorViewStyle = .whiteLarge } @objc private func createGraphButtonTap() { comparisonLabel.text = "" graphView.removeGraph() graph.removeGraph() graph.createNewGraph() graphView.createNewGraph() graph.state = .initial } @objc private func startVisualizationButtonDidTap() { comparisonLabel.text = "" pauseButton.isEnabled = true stopButton.isEnabled = true createGraphButton.isEnabled = false startVisualizationButton.isEnabled = false startInteractiveVisualizationButton.isEnabled = false createGraphButton.alpha = 0.5 startVisualizationButton.alpha = 0.5 startInteractiveVisualizationButton.alpha = 0.5 if graph.state == .completed { graphView.reset() graph.reset() } graph.state = .autoVisualization DispatchQueue.global(qos: .background).async { self.graph.findShortestPathsWithVisualization { self.graph.state = .completed DispatchQueue.main.async { self.startButton.isEnabled = false self.pauseButton.isEnabled = false self.stopButton.isEnabled = false self.createGraphButton.isEnabled = true self.startVisualizationButton.isEnabled = true self.startInteractiveVisualizationButton.isEnabled = true self.createGraphButton.alpha = 1 self.startVisualizationButton.alpha = 1 self.startInteractiveVisualizationButton.alpha = 1 self.comparisonLabel.text = "Completed!" } } } } @objc private func startInteractiveVisualizationButtonDidTap() { comparisonLabel.text = "" pauseButton.isEnabled = true stopButton.isEnabled = true createGraphButton.isEnabled = false startVisualizationButton.isEnabled = false startInteractiveVisualizationButton.isEnabled = false createGraphButton.alpha = 0.5 startVisualizationButton.alpha = 0.5 startInteractiveVisualizationButton.alpha = 0.5 if graph.state == .completed { graphView.reset() graph.reset() } guard let startVertex = graph.startVertex else { assertionFailure("startVertex is nil") return } startVertex.pathLengthFromStart = 0 startVertex.pathVerticesFromStart.append(startVertex) graph.state = .parsing graph.parseNeighborsFor(vertex: startVertex) { self.graph.state = .interactiveVisualization DispatchQueue.main.async { self.comparisonLabel.text = "Pick next vertex" } } } @objc private func didTapStartButton() { startButton.isEnabled = false pauseButton.isEnabled = true DispatchQueue.global(qos: .utility).async { self.graph.pauseVisualization = false } } @objc private func didTapPauseButton() { startButton.isEnabled = true pauseButton.isEnabled = false DispatchQueue.global(qos: .utility).async { self.graph.pauseVisualization = true } } @objc private func didTapStopButton() { startButton.isEnabled = false pauseButton.isEnabled = false comparisonLabel.text = "" activityIndicator.startAnimating() if graph.state == .parsing || graph.state == .autoVisualization { graph.stopVisualization = true } else if graph.state == .interactiveVisualization { didStop() } } private func setButtonsToInitialState() { createGraphButton.isEnabled = true startVisualizationButton.isEnabled = true startInteractiveVisualizationButton.isEnabled = true startButton.isEnabled = false pauseButton.isEnabled = false stopButton.isEnabled = false createGraphButton.alpha = 1 startVisualizationButton.alpha = 1 startInteractiveVisualizationButton.alpha = 1 } private func showError(error: String) { DispatchQueue.main.async { let size = CGSize(width: 250, height: 42) let origin = CGPoint(x: self.topView.center.x - 125, y: 96) let frame = CGRect(origin: origin, size: size) let errorView = ErrorView(frame: frame) errorView.setText(text: error) self.topView.addSubview(errorView) UIView.animate(withDuration: 2, animations: { errorView.alpha = 0 }, completion: { _ in errorView.removeFromSuperview() }) } } // MARK: GraphDelegate public func didCompleteGraphParsing() { graph.state = .completed setButtonsToInitialState() comparisonLabel.text = "Completed!" } public func didTapWrongVertex() { if !subviews.contains { $0 is ErrorView } { showError(error: "You have picked wrong next vertex") } } public func willCompareVertices(startVertexPathLength: Double, edgePathLength: Double, endVertexPathLength: Double) { DispatchQueue.main.async { if startVertexPathLength + edgePathLength < endVertexPathLength { self.comparisonLabel.text = "\(startVertexPathLength) + \(edgePathLength) < \(endVertexPathLength) 👍" } else { self.comparisonLabel.text = "\(startVertexPathLength) + \(edgePathLength) >= \(endVertexPathLength) 👎" } } } public func didFinishCompare() { DispatchQueue.main.async { self.comparisonLabel.text = "" } } public func didStop() { graph.state = .initial graph.stopVisualization = false graph.pauseVisualization = false graphView.reset() graph.reset() setButtonsToInitialState() activityIndicator.stopAnimating() } public func willStartVertexNeighborsChecking() { DispatchQueue.main.async { self.comparisonLabel.text = "" } } public func didFinishVertexNeighborsChecking() { DispatchQueue.main.async { self.comparisonLabel.text = "Pick next vertex" } } }
mit
IMcD23/Proton
Templates/Proton Page.xctemplate/Table/___FILEBASENAME___.swift
1
469
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import Proton class ___FILEBASENAMEASIDENTIFIER___: Page { private var items = TableData<<#ModelClassName#>>() override func layout() -> ProtonView { return Table(data: items, cells: []) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/13301-getselftypeforcontainer.swift
11
279
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { protocol B { class A : d { { } class d } protocol A : A { } } { } protocol g { func a typealias e : e
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/15031-swift-sourcemanager-getmessage.swift
11
237
// 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 { { { } } { } deinit { return m( [Void{ } { class case ,
mit
mike4aday/SwiftlySalesforce
Sources/SwiftlySalesforce/Services/Resource+SObjects.swift
1
4243
import Foundation extension Resource { struct SObjects { struct Create<E: Encodable>: DataService { let type: String let fields: [String: E] func createRequest(with credential: Credential) throws -> URLRequest { let method = HTTP.Method.post let path = Resource.path(for: "sobjects/\(type)") let body = try JSONEncoder().encode(fields) return try URLRequest(credential: credential, method: method, path: path, body: body) } func transform(data: Data) throws -> String { let result = try JSONDecoder(dateFormatter: .salesforce(.long)).decode(Result.self, from: data) return result.id } private struct Result: Decodable { var id: String } } //MARK: - Read record - struct Read<D: Decodable>: DataService { typealias Output = D let type: String let id: String var fields: [String]? = nil func createRequest(with credential: Credential) throws -> URLRequest { let method = HTTP.Method.get let path = Resource.path(for: "sobjects/\(type)/\(id)") let queryItems = fields.map { ["fields": $0.joined(separator: ",")] } return try URLRequest(credential: credential, method: method, path: path, queryItems: queryItems) } } //MARK: - Update record - struct Update<E: Encodable>: DataService { typealias Output = Void let type: String let id: String let fields: [String: E] public func createRequest(with credential: Credential) throws -> URLRequest { let method = HTTP.Method.patch let encoder = JSONEncoder() let path = Resource.path(for: "sobjects/\(type)/\(id)") let body = try encoder.encode(fields) return try URLRequest(credential: credential, method: method, path: path, body: body) } } //MARK: - Delete record - struct Delete: DataService { typealias Output = Void let type: String let id: String func createRequest(with credential: Credential) throws -> URLRequest { let method = HTTP.Method.delete let path = Resource.path(for: "sobjects/\(type)/\(id)") return try URLRequest(credential: credential, method: method, path: path) } } //MARK: - Describe SObject - struct Describe: DataService { typealias Output = ObjectDescription let type: String func createRequest(with credential: Credential) throws -> URLRequest { let method = HTTP.Method.get let path = Resource.path(for: "sobjects/\(type)/describe") return try URLRequest(credential: credential, method: method, path: path) } } //MARK: - Describe all SObjects - struct DescribeGlobal: DataService { func createRequest(with credential: Credential) throws -> URLRequest { let method = HTTP.Method.get let path = Resource.path(for: "sobjects") return try URLRequest(credential: credential, method: method, path: path) } func transform(data: Data) throws -> [ObjectDescription] { struct Result: Decodable { var sobjects: [ObjectDescription] } let result = try JSONDecoder(dateFormatter: .salesforce(.long)).decode(Result.self, from: data) return result.sobjects } } } }
mit
shial4/api-loltracker
Sources/App/Models/ChampionStats.swift
1
2094
// // ChampionStats.swift // lolTracker-API // // Created by Shial on 13/01/2017. // // import Foundation import Vapor import Fluent final class ChampionStats: Model { var exists: Bool = false public var id: Node? var championId: Node? var season: String var kills: Int = 0 var deaths: Int = 0 var assists: Int = 0 var cs: Int = 0 var gold: Int = 0 init(season: String, championId: Node? = nil) { self.id = nil self.season = season self.championId = championId } required init(node: Node, in context: Context) throws { id = try node.extract("id") championId = try node.extract("champion_id") season = try node.extract("season") kills = try node.extract("kills") deaths = try node.extract("deaths") assists = try node.extract("assists") cs = try node.extract("cs") gold = try node.extract("gold") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "champion_id": championId, "season": season, "kills": kills, "deaths": deaths, "assists": assists, "cs": cs, "gold": gold ]) } } extension ChampionStats: Preparation { static func prepare(_ database: Database) throws { try database.create(entity, closure: { (stats) in stats.id() stats.string("season") stats.int("kills") stats.int("deaths") stats.int("assists") stats.int("cs") stats.int("gold") stats.parent(Summoner.self, optional: false) }) } static func revert(_ database: Database) throws { try database.delete(entity) } } extension ChampionStats { func champion() throws -> Champions? { return try parent(championId, nil, Champions.self).get() } func stats() throws -> [ChampionStats] { return try children(nil, ChampionStats.self).all() } }
mit
weipin/Cycles
Tests/HelperTests.swift
1
3762
// // HelperTests.swift // // Copyright (c) 2014 Weipin Xia // // 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 CyclesTouch class HelperTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testParseContentTypeLikeHeaderShouldWork() { var (type, parameters) = ParseContentTypeLikeHeader("text/html; charset=UTF-8") XCTAssertEqual(type!, "text/html"); XCTAssertEqual(parameters["charset"]!, "UTF-8"); (type, parameters) = ParseContentTypeLikeHeader("text/html; charset=\"UTF-8\"") XCTAssertEqual(type!, "text/html"); XCTAssertEqual(parameters["charset"]!, "UTF-8"); (type, parameters) = ParseContentTypeLikeHeader("text/html; charset='UTF-8'") XCTAssertEqual(type!, "text/html"); XCTAssertEqual(parameters["charset"]!, "UTF-8"); } func testFormencodeDictionaryShouldWork() { var dict = ["k1": ["v1"], "k2": ["&;", "hello"], "k3": ["world"]] var str = FormencodeDictionary(dict) XCTAssertEqual(str, "k1=v1&k2=%26%3B&k2=hello&k3=world") } func testParseURLWithQueryParametersShouldWork() { var (base, parameters) = ParseURLWithQueryParameters("http://mydomain.com?k1=v1&k1=v11&k2=v2") XCTAssertEqual(base!, "http://mydomain.com") XCTAssertEqual(FormencodeDictionary(parameters), "k1=v1&k1=v11&k2=v2") (base, parameters) = ParseURLWithQueryParameters("k1=v1&k1=v11&k2=v2") XCTAssertNil(base) XCTAssertEqual(FormencodeDictionary(parameters), "k1=v1&k1=v11&k2=v2") (base, parameters) = ParseURLWithQueryParameters("http://mydomain.com") XCTAssertEqual(base!, "http://mydomain.com") XCTAssertEqual(FormencodeDictionary(parameters), "") } func testMergeParametersToURLShouldWork() { var URL = MergeParametersToURL("http://domain.com?k1=v1&K2=v2", ["k3": ["v3"]]); XCTAssertEqual(URL, "http://domain.com?k1=v1&k2=v2&k3=v3") // keys in both URL and parameters ("k1") URL = MergeParametersToURL("http://domain.com?k1=v1&K2=v2", ["k3": ["v3"], "k1": ["v11"]]); XCTAssertEqual(URL, "http://domain.com?k1=v1&k1=v11&k2=v2&k3=v3") // escapsed characters URL = MergeParametersToURL("http://domain.com?k1=Content-Type%3Atext", ["k1": ["v1"]]); XCTAssertEqual(URL, "http://domain.com?k1=Content-Type%3Atext&k1=v1") } }
mit
NghiaTranUIT/Titan
TitanCore/TitanCore/TableSchemeContextMenuView.swift
2
1990
// // TableSchemeContextMenuView.swift // TitanCore // // Created by Nghia Tran on 4/24/17. // Copyright © 2017 nghiatran. All rights reserved. // import Cocoa import SwiftyPostgreSQL public protocol TableSchemeContextMenuViewDelegate: class { func TableSchemeContextMenuViewDidTapAction(_ action: TableSchemmaContextAction, table: Table) } // // MARK: - Action public enum TableSchemmaContextAction { case openNewtab case copyTableName case truncate case delete } open class TableSchemeContextMenuView: NSMenu { // // MARK: - Variable public weak var contextDelegate: TableSchemeContextMenuViewDelegate? public weak var currentItem: Table? public weak var selectedRow: TableRowCell? // // MARK: - Public public func configureContextView(with table: Table, selectedRow: TableRowCell) { self.currentItem = table self.selectedRow = selectedRow } // // MARK: - OUTLET @IBAction func openInNewTapBtnTapped(_ sender: Any) { guard let table = self.currentItem else {return} self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.openNewtab, table: table) } @IBAction func copyNameBtnTapped(_ sender: Any) { guard let table = self.currentItem else {return} self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.copyTableName, table: table) } @IBAction func truncateTableBtnTapped(_ sender: Any) { guard let table = self.currentItem else {return} self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.truncate, table: table) } @IBAction func deleteTableBtnTapped(_ sender: Any) { guard let table = self.currentItem else {return} self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.delete, table: table) } } // // MARK: - XIBInitializable extension TableSchemeContextMenuView: XIBInitializable { public typealias T = TableSchemeContextMenuView }
mit
apple/swift
validation-test/compiler_crashers_fixed/01303-swift-type-walk.swift
65
519
// 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: not %target-swift-frontend %s -typecheck func a<T>() -> (T, T -> T) -> T { k : w { func v <h: h m h.p == k>(l: h.p) { } } protocol h { n func w(w: a) func a<b:a
apache-2.0
apple/swift
validation-test/stdlib/MicroStdlib/MicroStdlib.swift
2
731
// RUN: %empty-directory(%t) // RUN: %target-build-swift -c -whole-module-optimization -parse-as-library -parse-stdlib -Xllvm -basic-dynamic-replacement -module-name Swift -emit-module -runtime-compatibility-version none -emit-module-path %t/Swift.swiftmodule -o %t/Swift.o %S/Inputs/Swift.swift // RUN: ls %t/Swift.swiftmodule // RUN: ls %t/Swift.swiftdoc // RUN: ls %t/Swift.o // RUN: %target-clang -x c -c %S/Inputs/RuntimeStubs.c -o %t/RuntimeStubs.o // RUN: %target-build-swift -I %t -runtime-compatibility-version none -module-name main -o %t/hello %S/Inputs/main.swift %t/Swift.o %t/RuntimeStubs.o // RUN: %target-codesign %t/hello // RUN: %target-run %t/hello | %FileCheck %s // REQUIRES: executable_test // CHECK: Hello
apache-2.0
cnoon/swift-compiler-crashes
fixed/25564-swift-astprinter-printtextimpl.swift
7
265
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A{ class A{class a{enum b{ enum b{class a struct Q<T where g:d{typealias F=a.h protocol a
mit
cnoon/swift-compiler-crashes
crashes-duplicates/07665-void.swift
11
312
// 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 : BooleanType, A { protocol A : BooleanType, A : BooleanType, A : Int -> { var b: e)"\([Void{ protocol c { } typealias e : e typeal
mit
mmisesin/github_client
Github Client/CommitsTableViewController.swift
1
6455
// // CommitsTableViewController.swift // Github Client // // Created by Artem Misesin on 3/18/17. // Copyright © 2017 Artem Misesin. All rights reserved. // import UIKit import OAuthSwift import SwiftyJSON class CommitsTableViewController: UITableViewController { var repoTitle: String = "" var commits: [(message: String, author: String, date: String)] = [] var spinner = UIActivityIndicatorView() override func viewDidLoad() { super.viewDidLoad() test(SingleOAuth.shared.oAuthSwift as! OAuth2Swift) self.tableView.allowsSelection = false self.tableView.separatorStyle = .none self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) self.spinner.frame = CGRect(x: self.tableView.bounds.midX - 10, y: self.tableView.bounds.midY - 10, width: 20.0, height: 20.0) // (or wherever you want it in the button) self.tableView.addSubview(self.spinner) self.spinner.startAnimating() self.spinner.alpha = 1.0 //self.parent. // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } func test(_ oauthswift: OAuth2Swift) { let url :String = "https://api.github.com/repos/" + SingleOAuth.shared.owner! + "/\(repoTitle)/commits" let parameters :Dictionary = Dictionary<String, AnyObject>() let _ = oauthswift.client.get( url, parameters: parameters, success: { response in let jsonDict = try? JSON(response.jsonObject()) if let arrayMessages = jsonDict?.arrayValue.map({$0["commit"].dictionaryValue}).map({$0["message"]?.stringValue}){ if let arrayAuthors = jsonDict?.arrayValue.map({$0["commit"].dictionaryValue}).map({$0["committer"]?.dictionaryValue}).map({$0?["name"]?.stringValue}){ if let arrayDates = jsonDict?.arrayValue.map({$0["commit"].dictionaryValue}).map({$0["committer"]?.dictionaryValue}).map({$0?["date"]?.stringValue}){ for i in 0..<arrayMessages.count{ let range = arrayDates[i]?.range(of: "T") let date = arrayDates[i]?.substring(to: (range?.lowerBound)!) self.commits.append((arrayMessages[i]!, arrayAuthors[i]!, date!)) } } } } //print(jsonDict) self.spinner.stopAnimating() self.spinner.alpha = 0.0 self.tableView.separatorStyle = .singleLine self.tableView.reloadData() }, failure: { error in print(error.localizedDescription) var message = "" if error.localizedDescription == "The operation couldn’t be completed. (OAuthSwiftError error -11.)"{ message = "No internet connection" } else { message = "No commits found" } let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil)}) } func close(){ self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return commits.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = commits[indexPath.row].message cell.detailTextLabel?.text = commits[indexPath.row].author + ", " + commits[indexPath.row].date return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
masters3d/xswift
exercises/prime-factors/Sources/PrimeFactorsExample.swift
3
548
struct PrimeFactors { var number: Int64 var toArray = [Int64]() private func primesFor( _ number: Int64) -> [Int64] { var number = number var primes = [Int64]() var divisor: Int64 = 2 while number > 1 { while number % divisor == 0 { primes.append(divisor) number /= divisor } divisor += 1 } return primes } init(_ value: Int64) { self.number = value self.toArray = primesFor(value) } }
mit
digoreis/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0040.xcplaygroundpage/Contents.swift
1
3683
/*: # Replacing Equal Signs with Colons For Attribute Arguments * Proposal: [SE-0040](0040-attributecolons.md) * Author: [Erica Sadun](http://github.com/erica) * Review Manager: [Chris Lattner](https://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160307/012100.html) * Pull Request: [apple/swift#1537](https://github.com/apple/swift/pull/1537) ## Introduction Attribute arguments are unlike other Swift language arguments. At the call site, they use `=` instead of colons to distinguish argument names from passed values. This proposal brings attributes into compliance with Swift standard practices by replacing the use of "=" with ":" in this one-off case. *Discussion took place on the Swift Evolution mailing list in the [\[Discussion\] Replacing Equal Signs with Colons For Attribute Arguments](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160215/010448.html) thread. Thanks to [Doug Gregor](https://github.com/DougGregor) for suggesting this enhancement.* ## Motivation Attributes enable developers to annotate declarations and types with keywords that constrain behavior. Recognizable by their [at-sign](http://foldoc.org/strudel) "@" prefix, attributes communicate features, characteristics, restrictions, and expectations of types and declarations to the Swift compiler. Common attributes include `@noescape` for parameters that cannot outlive the lifetime of a call, `@convention`, to indicates whether a type's calling conventions follows a Swift, C, or (Objective-C) block model, and `@available` to enumerate a declaration's compatibility with platform and OS versions. Swift currently offers about a dozen distinct attributes, and is likely to expand this vocabulary in future language updates. Some attributes accept arguments: `@attribute-name(attribute-arguments)` including, at this time, `@available`, `@warn_unused_result` and `@swift3_migration`. In the current grammar, an equal sign separates attribute argument keywords from values. ```swift introduced=version-number deprecated=version-number obsoleted=version-number message=message renamed=new-name mutable_variant=method-name ``` Using `=` is out of step with other Swift parameterization call-site patterns. Although the scope of this proposal is quite small, tweaking the grammar to match the rest of Swift introduces a small change that adds consistency across the language. ```swift parameter name: parameter value ``` ## Detail Design This proposal replaces the use of `=` with `:` in the balanced tokens used to compose an attribute argument clause along the following lines: ```swift attribute → @ attribute-name attribute-argument-clause<sub>opt</sub> attribute-name → identifier attribute-argument-clause → ( balanced-tokens<sub>opt<opt> ) balanced-tokens → balanced-token balanced-tokens → balanced-token, balanced-tokens balanced-token → attribute-argument-label : attribute argument-value ``` This design can be summarized as "wherever current Swift attributes use `=`, use `:` instead", for example: ```swift @available(*, unavailable, renamed: "MyRenamedProtocol") typealias MyProtocol = MyRenamedProtocol @warn_unused_result(mutable_variant: "sortInPlace") public func sort() -> [Self.Generator.Element] @available(*, deprecated, message: "it will be removed in Swift 3. Use the 'generate()' method on the collection.") public init(_ bounds: Range<Element>) ``` ## Alternatives Considered There are no alternatives to put forth other than not accepting this proposal. ---------- [Previous](@previous) | [Next](@next) */
mit
oisdk/SwiftDataStructures
SwiftDataStructures/Deque.swift
1
15120
// MARK: Definition /** A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised of two queues. This implementation has a front queue, which is reversed, and a back queue, which is not. Operations at either end of the Deque have the same complexity as operations on the end of either queue. Three structs conform to the `DequeType` protocol: `Deque`, `DequeSlice`, and `ContiguousDeque`. These correspond to the standard library array types. */ public protocol DequeType : MutableCollectionType, RangeReplaceableCollectionType, CustomDebugStringConvertible, ArrayLiteralConvertible { /// The type that represents the queues. associatedtype Container : RangeReplaceableCollectionType, MutableCollectionType /// The front queue. It is stored in reverse. var front: Container { get set } /// The back queue. var back : Container { get set } /// Constructs an empty `Deque` init() } // MARK: DebugDescription extension DequeType { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { let fStr = front.reverse().map { String(reflecting: $0) }.joinWithSeparator(", ") let bStr = back.map { String(reflecting: $0) }.joinWithSeparator(", ") return "[" + fStr + " | " + bStr + "]" } } // MARK: Initializers extension DequeType { internal init(balancedF: Container, balancedB: Container) { self.init() front = balancedF back = balancedB } /// Construct from a collection public init< C : CollectionType where C.Index : RandomAccessIndexType, C.SubSequence.Generator.Element == Container.Generator.Element, C.Index.Distance == Container.Index.Distance >(col: C) { self.init() let mid = col.count / 2 let midInd = col.startIndex.advancedBy(mid) front.reserveCapacity(mid) back.reserveCapacity(mid.successor()) front.appendContentsOf(col[col.startIndex..<midInd].reverse()) back.appendContentsOf(col[midInd..<col.endIndex]) } } extension DequeType where Container.Index.Distance == Int { /// Create an instance containing `elements`. public init(arrayLiteral elements: Container.Generator.Element...) { self.init(col: elements) } /// Initialise from a sequence. public init< S : SequenceType where S.Generator.Element == Container.Generator.Element >(_ seq: S) { self.init(col: Array(seq)) } } // MARK: Indexing private enum IndexLocation<I> { case Front(I), Back(I) } extension DequeType where Container.Index : RandomAccessIndexType, Container.Index.Distance : ForwardIndexType { private func translate(i: Container.Index.Distance) -> IndexLocation<Container.Index> { return i < front.count ? .Front(front.endIndex.predecessor().advancedBy(-i)) : .Back(back.startIndex.advancedBy(i - front.count)) } /** The position of the first element in a non-empty `Deque`. In an empty `Deque`, `startIndex == endIndex`. */ public var startIndex: Container.Index.Distance { return 0 } /** The `Deque`'s "past the end" position. `endIndex` is not a valid argument to `subscript`, and is always reachable from `startIndex` by zero or more applications of `successor()`. */ public var endIndex : Container.Index.Distance { return front.count + back.count } public subscript(i: Container.Index.Distance) -> Container.Generator.Element { get { switch translate(i) { case let .Front(i): return front[i] case let .Back(i): return back[i] } } set { switch translate(i) { case let .Front(i): front[i] = newValue case let .Back(i): back[i] = newValue } } } } // MARK: Index Ranges private enum IndexRangeLocation<I : ForwardIndexType> { case Front(Range<I>), Over(Range<I>, Range<I>), Back(Range<I>), Between } extension DequeType where Container.Index : RandomAccessIndexType, Container.Index.Distance : BidirectionalIndexType { private func translate (i: Range<Container.Index.Distance>) -> IndexRangeLocation<Container.Index> { if i.endIndex <= front.count { let s = front.endIndex.advancedBy(-i.endIndex) if s == front.startIndex && i.isEmpty { return .Between } let e = front.endIndex.advancedBy(-i.startIndex) return .Front(s..<e) } if i.startIndex >= front.count { let s = back.startIndex.advancedBy(i.startIndex - front.count) let e = back.startIndex.advancedBy(i.endIndex - front.count) return .Back(s..<e) } let f = front.startIndex..<front.endIndex.advancedBy(-i.startIndex) let b = back.startIndex..<back.startIndex.advancedBy(i.endIndex - front.count) return .Over(f, b) } } extension DequeType where Container.Index : RandomAccessIndexType, Container.Index.Distance : BidirectionalIndexType, SubSequence : DequeType, SubSequence.Container == Container.SubSequence, SubSequence.Generator.Element == Container.Generator.Element { public subscript(idxs: Range<Container.Index.Distance>) -> SubSequence { set { for (index, value) in zip(idxs, newValue) { self[index] = value } } get { switch translate(idxs) { case .Between: return SubSequence() case let .Over(f, b): return SubSequence( balancedF: front[f], balancedB: back[b] ) case let .Front(i): if i.isEmpty { return SubSequence() } return SubSequence( balancedF: front[i.startIndex.successor()..<i.endIndex], balancedB: front[i.startIndex...i.startIndex] ) case let .Back(i): if i.isEmpty { return SubSequence() } return SubSequence( balancedF: back[i.startIndex..<i.startIndex.successor()], balancedB: back[i.startIndex.successor()..<i.endIndex] ) } } } } // MARK: Balance private enum Balance { case FrontEmpty, BackEmpty, Balanced } extension DequeType { private var balance: Balance { let (f, b) = (front.count, back.count) if f == 0 { if b > 1 { return .FrontEmpty } } else if b == 0 { if f > 1 { return .BackEmpty } } return .Balanced } internal var isBalanced: Bool { return balance == .Balanced } } extension DequeType where Container.Index : BidirectionalIndexType { private mutating func check() { switch balance { case .FrontEmpty: let newBack = back.removeLast() front.reserveCapacity(back.count) front.replaceRange(front.indices, with: back.reverse()) back.replaceRange(back.indices, with: [newBack]) case .BackEmpty: let newFront = front.removeLast() back.reserveCapacity(front.count) back.replaceRange(back.indices, with: front.reverse()) front.replaceRange(front.indices, with: [newFront]) case .Balanced: return } } } // MARK: ReserveCapacity extension DequeType { /** Reserve enough space to store `minimumCapacity` elements. - Postcondition: `capacity >= minimumCapacity` and the `Deque` has mutable contiguous storage. - Complexity: O(`count`). */ public mutating func reserveCapacity(n: Container.Index.Distance) { front.reserveCapacity(n / 2) back.reserveCapacity(n / 2) } } // MARK: ReplaceRange extension DequeType where Container.Index : RandomAccessIndexType, Container.Index.Distance : BidirectionalIndexType { /** Replace the given `subRange` of elements with `newElements`. Invalidates all indices with respect to `self`. - Complexity: O(`subRange.count`) if `subRange.endIndex == self.endIndex` and `isEmpty(newElements)`, O(`self.count + newElements.count`) otherwise. */ public mutating func replaceRange< C : CollectionType where C.Generator.Element == Container.Generator.Element >(subRange: Range<Container.Index.Distance>, with newElements: C) { defer { check() } switch translate(subRange) { case .Between: back.replaceRange(back.startIndex..<back.startIndex, with: newElements) case let .Front(r): front.replaceRange(r, with: newElements.reverse()) case let .Back(r): back.replaceRange(r, with: newElements) case let .Over(f, b): front.removeRange(f) back.replaceRange(b, with: newElements) } } } extension RangeReplaceableCollectionType where Index : BidirectionalIndexType { private mutating func popLast() -> Generator.Element? { return isEmpty ? nil : removeLast() } } // MARK: StackLike extension DequeType where Container.Index : BidirectionalIndexType { /** If `!self.isEmpty`, remove the first element and return it, otherwise return `nil`. - Complexity: Amortized O(1) */ public mutating func popFirst() -> Container.Generator.Element? { defer { check() } return front.popLast() ?? back.popLast() } /** If `!self.isEmpty`, remove the last element and return it, otherwise return `nil`. - Complexity: Amortized O(1) */ public mutating func popLast() -> Container.Generator.Element? { defer { check() } return back.popLast() ?? front.popLast() } } // MARK: SequenceType /// :nodoc: public struct DequeGenerator< Container : RangeReplaceableCollectionType where Container.Index : BidirectionalIndexType > : GeneratorType { private let front, back: Container private var i: Container.Index private var onBack: Bool /** Advance to the next element and return it, or `nil` if no next element exists. - Requires: `next()` has not been applied to a copy of `self`. */ public mutating func next() -> Container.Generator.Element? { if onBack { if i == back.endIndex { return nil } defer { i._successorInPlace() } return back[i] } guard i == front.startIndex else { i._predecessorInPlace() return front[i] } onBack = true i = back.startIndex return next() } } extension DequeType where Container.Index : BidirectionalIndexType { /** Return a `DequeGenerator` over the elements of this `Deque`. - Complexity: O(1) */ public func generate() -> DequeGenerator<Container> { return DequeGenerator(front: front, back: back, i: front.endIndex, onBack: false) } } // MARK: Rotations extension DequeType where Container.Index : BidirectionalIndexType { /** Removes an element from the end of `self`, and prepends it to `self` ```swift var deque: Deque = [1, 2, 3, 4, 5] deque.rotateRight() // deque == [5, 1, 2, 3, 4] ``` - Complexity: Amortized O(1) */ public mutating func rotateRight() { if back.isEmpty { return } front.append(back.removeLast()) check() } /** Removes an element from the start of `self`, and appends it to `self` ```swift var deque: Deque = [1, 2, 3, 4, 5] deque.rotateLeft() // deque == [2, 3, 4, 5, 1] ``` - Complexity: Amortized O(1) */ public mutating func rotateLeft() { if front.isEmpty { return } back.append(front.removeLast()) check() } /** Removes an element from the end of `self`, and prepends `x` to `self` ```swift var deque: Deque = [1, 2, 3, 4, 5] deque.rotateRight(0) // deque == [0, 1, 2, 3, 4] ``` - Complexity: Amortized O(1) */ public mutating func rotateRight(x: Container.Generator.Element) { let _ = back.popLast() ?? front.popLast() front.append(x) check() } /** Removes an element from the start of `self`, and appends `x` to `self` ```swift var deque: Deque = [1, 2, 3, 4, 5] deque.rotateLeft(0) // deque == [2, 3, 4, 5, 0] ``` - Complexity: Amortized O(1) */ public mutating func rotateLeft(x: Container.Generator.Element) { let _ = front.popLast() ?? back.popLast() back.append(x) check() } } // MARK: Reverse extension DequeType { /** Return a `Deque` containing the elements of `self` in reverse order. */ public func reverse() -> Self { return Self(balancedF: back, balancedB: front) } } // MARK: -ending extension DequeType where Container.Index : BidirectionalIndexType { /** Prepend `x` to `self`. The index of the new element is `self.startIndex`. - Complexity: Amortized O(1). */ public mutating func prepend(x: Container.Generator.Element) { front.append(x) check() } /** Prepend the elements of `newElements` to `self`. - Complexity: O(*length of result*). */ public mutating func prextend< S : SequenceType where S.Generator.Element == Container.Generator.Element >(x: S) { front.appendContentsOf(x.reverse()) check() } } // MARK: Underestimate Count extension DequeType { /** Return a value less than or equal to the number of elements in `self`, **nondestructively**. */ public func underestimateCount() -> Int { return front.underestimateCount() + back.underestimateCount() } } // MARK: Structs /** A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised of two queues. This implementation has a front queue, which is a reversed array, and a back queue, which is an array. Operations at either end of the Deque have the same complexity as operations on the end of either array. */ public struct Deque<Element> : DequeType { /// The front and back queues. The front queue is stored in reverse. public var front, back: [Element] public typealias SubSequence = DequeSlice<Element> /// Initialise an empty `Deque` public init() { (front, back) = ([], []) } } /** A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised of two queues. This implementation has a front queue, which is a reversed ArraySlice, and a back queue, which is an ArraySlice. Operations at either end of the Deque have the same complexity as operations on the end of either ArraySlice. Because an `ArraySlice` presents a view onto the storage of some larger array even after the original array's lifetime ends, storing the slice may prolong the lifetime of elements that are no longer accessible, which can manifest as apparent memory and object leakage. To prevent this effect, use `DequeSlice` only for transient computation. */ public struct DequeSlice<Element> : DequeType { /// The front and back queues. The front queue is stored in reverse public var front, back: ArraySlice<Element> public typealias SubSequence = DequeSlice /// Initialise an empty `DequeSlice` public init() { (front, back) = ([], []) } } /** A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised of two queues. This implementation has a front queue, which is a reversed ContiguousArray, and a back queue, which is a ContiguousArray. Operations at either end of the Deque have the same complexity as operations on the end of either ContiguousArray. */ public struct ContiguousDeque<Element> : DequeType { /// The front and back queues. The front queue is stored in reverse public var front, back: ContiguousArray<Element> public typealias SubSequence = DequeSlice<Element> /// Initialise an empty `ContiguousDeque` public init() { (front, back) = ([], []) } }
mit
mrgerych/Cuckoo
Generator/Source/CuckooGeneratorFramework/Tokens/Key.swift
1
678
// // Key.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // public enum Key: String { case Substructure = "key.substructure" case Kind = "key.kind" case Accessibility = "key.accessibility" case SetterAccessibility = "key.setter_accessibility" case Name = "key.name" case TypeName = "key.typename" case InheritedTypes = "key.inheritedtypes" case Length = "key.length" case Offset = "key.offset" case NameLength = "key.namelength" case NameOffset = "key.nameoffset" case BodyLength = "key.bodylength" case BodyOffset = "key.bodyoffset" }
mit
zisko/swift
test/IRGen/protocol_conformance_records.swift
1
5597
// RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s // RUN: %target-swift-frontend %s -emit-ir -num-threads 8 -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s import resilient_struct import resilient_protocol public protocol Runcible { func runce() } // CHECK-LABEL: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE:@"\$S28protocol_conformance_records8RuncibleMp"]] // -- type metadata // CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVMn" // -- witness table // CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAWP" // -- flags // CHECK-SAME: i32 0 // CHECK-SAME: }, public struct NativeValueType: Runcible { public func runce() {} } // CHECK-LABEL: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- class metadata // CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCMn" // -- witness table // CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAWP" // -- flags // CHECK-SAME: i32 0 // CHECK-SAME: }, public class NativeClassType: Runcible { public func runce() {} } // CHECK-LABEL: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- nominal type descriptor // CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVMn" // -- witness table // CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAWP" // -- flags // CHECK-SAME: i32 0 // CHECK-SAME: }, public struct NativeGenericType<T>: Runcible { public func runce() {} } // CHECK-LABEL: @"$SSi28protocol_conformance_records8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- type metadata // CHECK-SAME: @"got.$SSiMn" // -- witness table // CHECK-SAME: @"$SSi28protocol_conformance_records8RuncibleAAWP" // -- reserved // CHECK-SAME: i32 8 // CHECK-SAME: } extension Int: Runcible { public func runce() {} } // For a resilient struct, reference the NominalTypeDescriptor // CHECK-LABEL: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- nominal type descriptor // CHECK-SAME: @"got.$S16resilient_struct4SizeVMn" // -- witness table // CHECK-SAME: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADWP" // -- reserved // CHECK-SAME: i32 8 // CHECK-SAME: } extension Size: Runcible { public func runce() {} } // CHECK-LABEL: @"\01l_protocols" // CHECK-SAME: @"$S28protocol_conformance_records8RuncibleMp" // CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp" // TODO: conformances that need lazy initialization public protocol Spoon { } // Conditional conformances // CHECK-LABEL: {{^}}@"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" ={{ protected | }}constant // -- protocol descriptor // CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp" // -- nominal type descriptor // CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVMn" // -- witness table accessor // CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlWa // -- flags // CHECK-SAME: i32 258 // -- conditional requirement #1 // CHECK-SAME: i32 64, // CHECK-SAME: i32 0, // CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp" // CHECK-SAME: } extension NativeGenericType : Spoon where T: Spoon { public func runce() {} } // Retroactive conformance // CHECK-LABEL: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc" ={{ protected | }}constant // -- protocol descriptor // CHECK-SAME: @"got.$S18resilient_protocol22OtherResilientProtocolMp" // -- nominal type descriptor // CHECK-SAME: @"got.$SSiMn" // -- witness table accessor // CHECK-SAME: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsWa" // -- flags // CHECK-SAME: i32 73, // -- module context for retroactive conformance // CHECK-SAME: @"$S28protocol_conformance_recordsMXM" // CHECK-SAME: } extension Int : OtherResilientProtocol { } // CHECK-LABEL: @"\01l_protocol_conformances" = private constant // CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" // CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" // CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" // CHECK-SAME: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" // CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" // CHECK-SAME: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc"
apache-2.0
atl009/WordPress-iOS
WordPress/WordPressTest/PostEditorStateTests.swift
1
9758
import XCTest @testable import WordPress class PostEditorStateTests: XCTestCase { var context: PostEditorStateContext! override func setUp() { super.setUp() } override func tearDown() { super.tearDown() context = nil } func testContextNoContentPublishButtonDisabled() { context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self) context.updated(hasContent: false) XCTAssertFalse(context.isPublishButtonEnabled) } func testContextChangedNewPostToDraft() { context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self) context.updated(postStatus: .draft) XCTAssertEqual(PostEditorAction.save, context.action, "New posts switched to draft should show Save button.") } func testContextExistingDraft() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self) XCTAssertEqual(PostEditorAction.update, context.action, "Existing draft posts should show Update button.") } func testContextPostSwitchedBetweenFutureAndCurrent() { context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self) XCTAssertEqual(PostEditorAction.publish, context.action) context.updated(publishDate: Date.distantFuture) XCTAssertEqual(PostEditorAction.schedule, context.action) context.updated(publishDate: nil) XCTAssertEqual(PostEditorAction.publish, context.action) } func testContextScheduledPost() { context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self) XCTAssertEqual(PostEditorAction.update, context.action, "Scheduled posts should show Update") } func testContextScheduledPostUpdated() { context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self) context.updated(postStatus: .scheduled) XCTAssertEqual(PostEditorAction.update, context.action, "Scheduled posts that get updated should still show Update") } } // These tests are all based off of Calypso unit tests // https://github.com/Automattic/wp-calypso/blob/master/client/post-editor/editor-publish-button/test/index.jsx extension PostEditorStateTests { func testContextChangedPublishedPostStaysPublished() { context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self) XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post was originally published and is still slated to be published") } func testContextChangedPublishedPostToDraft() { context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self) context.updated(postStatus: .draft) XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post was originally published and is currently reverted to non-published status") } func testContextPostFutureDatedButNotYetScheduled() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self) context.updated(postStatus: .publish) context.updated(publishDate: Date.distantFuture) XCTAssertEqual(PostEditorAction.schedule, context.action, "should return Schedule if the post is dated in the future and not scheduled") } func testContextPostFutureDatedAlreadyPublished() { context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self) context.updated(postStatus: .publish) context.updated(publishDate: Date.distantFuture) XCTAssertEqual(PostEditorAction.schedule, context.action, "should return Schedule if the post is dated in the future and published") } func testContextPostFutureDatedAlreadyScheduled() { context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self) context.updated(postStatus: .scheduled) context.updated(publishDate: Date.distantFuture) XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post is scheduled and dated in the future") } func testContextUpdatingAlreadyScheduledToDraft() { context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self) context.updated(publishDate: Date.distantFuture) context.updated(postStatus: .draft) XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post is scheduled, dated in the future, and next status is draft") } func testContextPostPastDatedAlreadyScheduled() { context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self) context.updated(publishDate: Date.distantPast) context.updated(postStatus: .scheduled) XCTAssertEqual(PostEditorAction.publish, context.action, "should return Publish if the post is scheduled and dated in the past") } func testContextDraftPost() { context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self) XCTAssertEqual(PostEditorAction.publish, context.action, "should return Publish if the post is a draft") } func testContextUserCannotPublish() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: false, delegate: self) XCTAssertEqual(PostEditorAction.submitForReview, context.action, "should return 'Submit for Review' if the post is a draft and user can't publish") } func testPublishEnabledHasContentAndChangesNotPublishing() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self) context.updated(hasContent: true) context.updated(hasChanges: true) context.updated(isBeingPublished: false) XCTAssertTrue(context.isPublishButtonEnabled, "should return true if form is not publishing and post is not empty") } func testPublishDisabledHasContentAndNoChangesNotPublishing() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self) context.updated(hasContent: true) context.updated(hasChanges: false) context.updated(isBeingPublished: false) XCTAssertFalse(context.isPublishButtonEnabled, "should return true if form is not publishing and post is not empty") } // Missing test: should return false if form is not publishing and post is not empty, but user is not verified // Missing test: should return true if form is not published and post is new and has content, but is not dirty func testPublishDisabledDuringPublishing() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self) context.updated(isBeingPublished: true) XCTAssertFalse(context.isPublishButtonEnabled, "should return false if form is publishing") } // Missing test: should return false if saving is blocked // Missing test: should return false if not dirty and has no content func testPublishDisabledNoContent() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self) context.updated(hasContent: false) XCTAssertFalse(context.isPublishButtonEnabled, "should return false if post has no content") } } extension PostEditorStateTests { func testPublishSecondaryDisabledNoContent() { context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self) context.updated(hasContent: false) XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false if post has no content") } func testPublishSecondaryAlreadyPublishedPosts() { context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self) context.updated(hasContent: true) XCTAssertEqual(PostEditorAction.update, context.action) XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false for already published posts") } func testPublishSecondaryAlreadyDraftedPosts() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self) context.updated(hasContent: true) XCTAssertTrue(context.isSecondaryPublishButtonShown, "should return true for existing drafts (publish now)") } func testPublishSecondaryExistingFutureDatedDrafts() { context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, publishDate: Date.distantFuture, delegate: self) context.updated(hasContent: true) XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false for existing future-dated drafts (no publish now)") } func testPublishSecondaryAlreadyScheduledPosts() { context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, publishDate: Date.distantFuture, delegate: self) context.updated(hasContent: true) XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false for existing scheduled drafts (no publish now)") } } extension PostEditorStateTests: PostEditorStateContextDelegate { func context(_ context: PostEditorStateContext, didChangeAction: PostEditorAction) { } func context(_ context: PostEditorStateContext, didChangeActionAllowed: Bool) { } }
gpl-2.0
lorentey/swift
test/Driver/Dependencies/driver-show-incremental-arguments.swift
2
1504
// REQUIRES: shell // Test that when: // // 1. Using -incremental -v -driver-show-incremental, and... // 2. ...the arguments passed to the Swift compiler version differ from the ones // used in the original compilation... // // ...then the driver prints a message indicating that incremental compilation // is disabled. // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/one-way-with-swiftdeps/* %t // RUN: %{python} %S/Inputs/touch.py 443865900 %t/* // RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": [443865900, 0]}}' > %t/main~buildrecord.swiftdeps // RUN: cd %t && %swiftc_driver -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -c ./main.swift ./other.swift -module-name main -incremental -v -driver-show-incremental -output-file-map %t/output.json | %FileCheck --check-prefix CHECK-INCREMENTAL %s // CHECK-INCREMENTAL-NOT: Incremental compilation has been disabled // CHECK-INCREMENTAL: Queuing (initial): {compile: main.o <= main.swift} // RUN: cd %t && %swiftc_driver -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -g -c ./main.swift ./other.swift -module-name main -incremental -v -driver-show-incremental -output-file-map %t/output.json | %FileCheck --check-prefix CHECK-ARGS-MISMATCH %s // CHECK-ARGS-MISMATCH: Incremental compilation has been disabled{{.*}}different arguments // CHECK-ARGS-MISMATCH-NOT: Queuing (initial): {compile: main.o <= main.swift}
apache-2.0
lorentey/swift
validation-test/compiler_crashers_fixed/28726-nominaltypedecl-hasfixedlayout.swift
56
442
// 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: not %target-swift-frontend %s -emit-ir // non-fuzz struct T<b{typealias a=(}let:T.a=
apache-2.0
christ776/CDMSegmentedControl
Example/Tests/Tests.swift
1
774
import UIKit import XCTest import CDMSegmentedControl class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit