repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
devpunk/punknote
punknote/View/Home/VHome.swift
1
5532
import UIKit class VHome:View, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private weak var spinner:VSpinner! private weak var collectionView:VCollection! private let kBarHeight:CGFloat = 64 private let kInterItem:CGFloat = 80 private let kCollectionBottom:CGFloat = 30 private let kCellHeight:CGFloat = 340 private let kFooterHeight:CGFloat = 40 required init(controller:UIViewController) { super.init(controller:controller) guard let controller:CHome = controller as? CHome else { return } let spinner:VSpinner = VSpinner() self.spinner = spinner let viewBar:VHomeBar = VHomeBar(controller:controller) let collectionView:VCollection = VCollection() collectionView.isHidden = true collectionView.alwaysBounceVertical = true collectionView.delegate = self collectionView.dataSource = self collectionView.registerCell(cell:VHomeCell.self) collectionView.registerFooter(footer:VHomeFooter.self) self.collectionView = collectionView if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { flow.minimumLineSpacing = kInterItem flow.sectionInset = UIEdgeInsets( top:kBarHeight, left:0, bottom:kCollectionBottom, right:0) } addSubview(spinner) addSubview(collectionView) addSubview(viewBar) NSLayoutConstraint.equals( view:spinner, toView:self) NSLayoutConstraint.topToTop( view:viewBar, toView:self) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) NSLayoutConstraint.equalsHorizontal( view:viewBar, toView:self) NSLayoutConstraint.equals( view:collectionView, toView:self) } required init?(coder:NSCoder) { return nil } deinit { spinner.stopAnimating() } override func layoutSubviews() { collectionView.collectionViewLayout.invalidateLayout() super.layoutSubviews() } //MARK: public func stopLoading() { spinner.stopAnimating() collectionView.isHidden = false collectionView.reloadData() } //MARK: private private func modelAtIndex(index:IndexPath) -> MHomeItem { let controller:CHome = self.controller as! CHome let item:MHomeItem = controller.model.items[index.item] return item } //MARK: collectionView delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, referenceSizeForFooterInSection section:Int) -> CGSize { guard let controller:CHome = self.controller as? CHome else { return CGSize.zero } let size:CGSize if controller.model.items.count > 0 { size = CGSize.zero } else { size = CGSize(width:0, height:kFooterHeight) } return size } func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let width:CGFloat = collectionView.bounds.size.width let size:CGSize = CGSize(width:width, height:kCellHeight) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { guard let controller:CHome = self.controller as? CHome else { return 0 } let count:Int = controller.model.items.count return count } func collectionView(_ collectionView:UICollectionView, viewForSupplementaryElementOfKind kind:String, at indexPath:IndexPath) -> UICollectionReusableView { let footer:UICollectionReusableView = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier:VHomeFooter.reusableIdentifier, for:indexPath) return footer } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let controller:CHome = self.controller as! CHome let item:MHomeItem = modelAtIndex(index:indexPath) let cell:VHomeCell = collectionView.dequeueReusableCell( withReuseIdentifier: VHomeCell.reusableIdentifier, for:indexPath) as! VHomeCell cell.config(controller:controller, model:item) return cell } func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool { return false } func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool { return false } }
mit
ed77855bdd36d12206408fdd83f92109
27.081218
165
0.610268
5.961207
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/NaturalLanguageUnderstandingV1/Models/EmotionOptions.swift
1
1622
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** Whether or not to return emotion analysis of the content. */ public struct EmotionOptions: Encodable { /// Set this to false to hide document-level emotion results. public var document: Bool? /// Emotion results will be returned for each target string that is found in the document. public var targets: [String]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case document = "document" case targets = "targets" } /** Initialize a `EmotionOptions` with member variables. - parameter document: Set this to false to hide document-level emotion results. - parameter targets: Emotion results will be returned for each target string that is found in the document. - returns: An initialized `EmotionOptions`. */ public init(document: Bool? = nil, targets: [String]? = nil) { self.document = document self.targets = targets } }
mit
93a8e86b40ee350dd46a09b5d5c22397
33.510638
112
0.705919
4.543417
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Common/CustomViews/Conicoin/Button/ResponsiveButton.swift
1
752
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class ResponsiveButton: UIButton { struct Const { static var duration = 0.05 static var alpha: CGFloat = 0.9 static var scale: CGFloat = 0.95 } var shouldTransform: Bool = true var shouldChangeAlpha: Bool = true override var isHighlighted: Bool { didSet { UIView.animate(withDuration: Const.duration) { if self.shouldTransform { let scale = self.isHighlighted ? Const.scale : 1 self.transform = CGAffineTransform(scaleX: scale, y: scale) } if self.shouldChangeAlpha { self.alpha = self.isHighlighted ? Const.alpha : 1 } } } } }
gpl-3.0
c26e96bc3a86d82a781c396e65ed5944
23.225806
69
0.627164
4.391813
false
false
false
false
yeahdongcn/RSBarcodes_Swift
Source/UIColorExtension.swift
1
4999
// // UIColorExtension.swift // HEXColor // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit /** MissingHashMarkAsPrefix: "Invalid RGB string, missing '#' as prefix" UnableToScanHexValue: "Scan hex error" MismatchedHexStringLength: "Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8" */ public enum UIColorInputError : Error { case missingHashMarkAsPrefix, unableToScanHexValue, mismatchedHexStringLength } extension UIColor { /** The shorthand three-digit hexadecimal representation of color. #RGB defines to the color #RRGGBB. - parameter hex3: Three-digit hexadecimal value. - parameter alpha: 0.0 - 1.0. The default is 1.0. */ @objc public convenience init(hex3: UInt16, alpha: CGFloat = 1) { let divisor = CGFloat(15) let red = CGFloat((hex3 & 0xF00) >> 8) / divisor let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor let blue = CGFloat( hex3 & 0x00F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The shorthand four-digit hexadecimal representation of color with alpha. #RGBA defines to the color #RRGGBBAA. - parameter hex4: Four-digit hexadecimal value. */ @objc public convenience init(hex4: UInt16) { let divisor = CGFloat(15) let red = CGFloat((hex4 & 0xF000) >> 12) / divisor let green = CGFloat((hex4 & 0x0F00) >> 8) / divisor let blue = CGFloat((hex4 & 0x00F0) >> 4) / divisor let alpha = CGFloat( hex4 & 0x000F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color of the form #RRGGBB. - parameter hex6: Six-digit hexadecimal value. */ @objc public convenience init(hex6: UInt32, alpha: CGFloat = 1) { let divisor = CGFloat(255) let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor let blue = CGFloat( hex6 & 0x0000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color with alpha of the form #RRGGBBAA. - parameter hex8: Eight-digit hexadecimal value. */ @objc public convenience init(hex8: UInt32) { let divisor = CGFloat(255) let red = CGFloat((hex8 & 0xFF000000) >> 24) / divisor let green = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / divisor let alpha = CGFloat( hex8 & 0x000000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, throws error. - parameter rgba: String value. */ @objc public convenience init(rgba_throws rgba: String) throws { guard rgba.hasPrefix("#") else { throw UIColorInputError.missingHashMarkAsPrefix } let index = rgba.index(rgba.startIndex, offsetBy: 1) let hexString = String(rgba[index...]) var hexValue: UInt32 = 0 guard Scanner(string: hexString).scanHexInt32(&hexValue) else { throw UIColorInputError.unableToScanHexValue } switch (hexString.count) { case 3: self.init(hex3: UInt16(hexValue)) case 4: self.init(hex4: UInt16(hexValue)) case 6: self.init(hex6: hexValue) case 8: self.init(hex8: hexValue) default: throw UIColorInputError.mismatchedHexStringLength } } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, fails to default color. - parameter rgba: String value. */ @objc public convenience init(_ rgba: String, defaultColor: UIColor = UIColor.clear) { guard let color = try? UIColor(rgba_throws: rgba) else { self.init(cgColor: defaultColor.cgColor) return } self.init(cgColor: color.cgColor) } /** Hex string of a UIColor instance. - parameter includeAlpha: Whether the alpha should be included. */ @objc public func hexString(_ includeAlpha: Bool = true) -> String { 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) if includeAlpha { return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255)) } else { return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } } }
mit
f712283a89817f38b1955189a47a7f98
33.958042
110
0.589318
3.933124
false
false
false
false
lachlanhurst/perlin-swift
Perlin-Swift/ViewController.swift
1
6622
// // ViewController.swift // Perlin-Swift // // Created by Lachlan Hurst on 24/08/2015. // Copyright (c) 2015 Lachlan Hurst. All rights reserved. // import UIKit import Foundation class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var zoomLabel: UILabel! @IBOutlet var persistenceLabel: UILabel! @IBOutlet var octavesLabel: UILabel! @IBOutlet var zoomSlider: UISlider! @IBOutlet var persistenceSlider: UISlider! @IBOutlet var octavesSlider: UISlider! @IBOutlet var sizeXtext: UITextField! @IBOutlet var sizeYtext: UITextField! @IBOutlet var imageView: UIImageView! fileprivate var generator = PerlinGenerator() @IBAction func aSliderChanged(_ sender: AnyObject) { let slider = sender as! UISlider if slider === zoomSlider { zoomLabel.textAlignment = NSTextAlignment.left zoomLabel.text = String(format: "Z = %.2f", slider.value) } else if slider === persistenceSlider { persistenceLabel.textAlignment = NSTextAlignment.left persistenceLabel.text = String(format: "P = %.2f", slider.value) } else if slider === octavesSlider { octavesLabel.textAlignment = NSTextAlignment.left octavesLabel.text = "O = \(Int(slider.value))" } updateNoiseImage() } @IBAction func newPressed(_ sender: AnyObject) { generator = PerlinGenerator() updateNoiseImage() } func updateNoiseImage() { generator.octaves = Int(octavesSlider.value) generator.zoom = zoomSlider.value generator.persistence = persistenceSlider.value let sizeX = CGFloat(NSString(string: sizeXtext.text!).floatValue) let sizeY = CGFloat(NSString(string: sizeYtext.text!).floatValue) let size = CGSize(width: sizeX, height: sizeY) let noise = generateNoiseImage(generator, size: size) imageView.image = noise } func generateNoiseImage(_ generator:PerlinGenerator, size:CGSize) -> UIImage { let width = Int(size.width) let height = Int(size.height) let startTime = CFAbsoluteTimeGetCurrent(); var pixelArray = [PixelData](repeating: PixelData(a: 255, r:0, g: 0, b: 0), count: width * height) for i in 0 ..< height { for j in 0 ..< width { var val = abs(generator.perlinNoise(Float(j), y: Float(i), z: 0, t: 0)) if val > 1 { val = 1 } let index = i * width + j let u_I = UInt8(val * 255) pixelArray[index].r = u_I pixelArray[index].g = u_I pixelArray[index].b = 0 } } let outputImage = imageFromARGB32Bitmap(pixelArray, width: width, height: height) print(" R RENDER:" + String(format: "%.4f", CFAbsoluteTimeGetCurrent() - startTime)); return outputImage /* let bounds = CGRect(origin: CGPoint.zeroPoint, size: size) let opaque = false let scale: CGFloat = 0 UIGraphicsBeginImageContextWithOptions(size, opaque, scale) let ctx = UIGraphicsGetCurrentContext() CGContextSetRGBFillColor(ctx, 1.000, 0.0, 0.000, 1.000); // light blue CGContextFillRect(ctx, CGRectMake(0.0, 0.0, size.width, size.height)); for (var x:CGFloat = 0.0; x < size.width; x+=1.0) { for (var y:CGFloat=0.0; y < size.height; y+=1.0) { let val = generator.perlinNoise(Float(x), y: Float(y), z: 0, t: 0) CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, CGFloat(abs(val))) CGContextFillRect(ctx, CGRectMake(x, y, 1.0, 1.0)); } } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image*/ } override func viewDidLoad() { super.viewDidLoad() sizeXtext.delegate = self sizeYtext.delegate = self //strech to fit but maintain aspect ratio imageView.contentMode = UIViewContentMode.scaleAspectFit //use nearest neighbour, we want to see the pixels (not blur them) imageView.layer.magnificationFilter = kCAFilterNearest } override func viewDidLayoutSubviews() { if sizeXtext.text == "" { let size = self.imageView.bounds.size sizeXtext.text = "\(Int(size.width/5))" sizeYtext.text = "\(Int(size.height/5))" } } override func viewDidAppear(_ animated: Bool) { updateNoiseImage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // // UITextFieldDelegate funcs // func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { updateNoiseImage() } // // drawing images from pixel data // http://blog.human-friendly.com/drawing-images-from-pixel-data-in-swift // struct PixelData { var a:UInt8 = 255 var r:UInt8 var g:UInt8 var b:UInt8 } fileprivate let rgbColorSpace = CGColorSpaceCreateDeviceRGB() fileprivate let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue) func imageFromARGB32Bitmap(_ pixels:[PixelData], width:Int, height:Int)->UIImage { let bitsPerComponent:Int = 8 let bitsPerPixel:Int = 32 assert(pixels.count == Int(width * height)) var data = pixels // Copy to mutable [] let bdata = Data(bytes: &data, count: data.count * MemoryLayout<PixelData>.size) let providerRef = CGDataProvider(data: bdata as CFData) let cgim = CGImage( width: width, height: height, bitsPerComponent: bitsPerComponent, bitsPerPixel: bitsPerPixel, bytesPerRow: width * Int(MemoryLayout<PixelData>.size), space: rgbColorSpace, bitmapInfo: bitmapInfo, provider: providerRef!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent ) return UIImage(cgImage: cgim!) } }
mit
b434b38cb83e1cc0af5655a7488fbab7
31.945274
114
0.593476
4.656821
false
false
false
false
robconrad/fledger-common
FledgerCommon/services/models/location/Location.swift
1
3925
// // Item.swift // fledger-ios // // Created by Robert Conrad on 4/9/15. // Copyright (c) 2015 TwoSpec Inc. All rights reserved. // import CoreLocation import Foundation import SQLite #if os(iOS) import Parse #elseif os(OSX) import ParseOSX #endif public func ==(a: Location, b: Location) -> Bool { let x = a.id == b.id && a.name == b.name && a.coordinate.latitude == b.coordinate.latitude let y = a.coordinate.longitude == b.coordinate.longitude && a.address == b.address && a.distance == b.distance return x && y } public class Location: Model, PFModel, SqlModel, CustomStringConvertible { public let modelType = ModelType.Location public let id: Int64? public let name: String? public let coordinate: CLLocationCoordinate2D public let address: String public let distance: Double? let pf: PFObject? public var description: String { return "Location(id: \(id), name: \(name), coordinate: \(coordinate), address: \(address), distance: \(distance), pf: \(pf))" } public required init(id: Int64?, name: String?, coordinate: CLLocationCoordinate2D, address: String, distance: Double? = nil, pf: PFObject? = nil) { self.id = id self.name = name self.coordinate = coordinate self.address = address self.distance = distance self.pf = pf } public convenience init(id: Int64?, name: String?, latitude: Double, longitude: Double, address: String, distance: Double? = nil, pf: PFObject? = nil) { self.init( id: id, name: name, coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude), address: address, distance: distance, pf: pf) } convenience init(row: Row) { self.init( id: row.get(Fields.id), name: row.get(Fields.nameOpt), latitude: row.get(Fields.latitude), longitude: row.get(Fields.longitude), address: row.get(Fields.address)) } convenience init(pf: PFObject) { self.init( id: pf.objectId.flatMap { ParseSvc().withParseId($0, ModelType.Location) }?.modelId, name: pf["name"] as? String, latitude: pf["latitude"] as! Double, longitude: pf["longitude"] as! Double, address: pf["address"] as! String, pf: pf) } func toSetters() -> [Setter] { return [ Fields.nameOpt <- name, Fields.latitude <- coordinate.latitude, Fields.longitude <- coordinate.longitude, Fields.address <- address ] } func toPFObject() -> PFObject? { if id != nil { let npf = PFObject(withoutDataWithClassName: modelType.rawValue, objectId: pf?.objectId ?? parse()?.parseId) npf["name"] = name ?? NSNull() npf["latitude"] = coordinate.latitude.datatypeValue npf["longitude"] = coordinate.longitude.datatypeValue npf["address"] = address return npf } return nil } func parse() -> ParseModel? { return id.flatMap { ParseSvc().withModelId($0, modelType) } } public func copy(name: String? = nil, coordinate: CLLocationCoordinate2D? = nil, address: String? = nil) -> Location { return Location( id: id, name: name ?? self.name, coordinate: coordinate ?? self.coordinate, address: address ?? self.address) } public func withId(id: Int64?) -> Location { return Location( id: id, name: name, coordinate: coordinate, address: address, distance: distance) } public func title() -> String { return name ?? address } }
mit
a03e24f81ccfdb9073dcfe7deee2e146
29.2
156
0.570446
4.303728
false
false
false
false
libretro/RetroArch
pkg/apple/MouseEmulation/EmulatorTouchMouse.swift
1
7435
// // EmulatorTouchMouse.swift // RetroArchiOS // // Created by Yoshi Sugawara on 12/27/21. // Copyright © 2021 RetroArch. All rights reserved. // /** Touch mouse behavior: - Mouse movement: Pan finger around screen - Left click: Tap with one finger - Right click: Tap with two fingers (or hold with one finger and tap with another) - Click-and-drag: Double tap and hold for 1 second, then pan finger around screen to drag mouse Code adapted from iDOS/dospad: https://github.com/litchie/dospad */ import Combine import UIKit @objc public protocol EmulatorTouchMouseHandlerDelegate: AnyObject { func handleMouseClick(isLeftClick: Bool, isPressed: Bool) func handleMouseMove(x: CGFloat, y: CGFloat) func handlePointerMove(x: CGFloat, y: CGFloat) } @objcMembers public class EmulatorTouchMouseHandler: NSObject, UIPointerInteractionDelegate { enum MouseHoldState { case notHeld, wait, held } struct MouseClick { var isRightClick = false var isPressed = false } struct TouchInfo { let touch: UITouch let origin: CGPoint let holdState: MouseHoldState } var enabled = false let view: UIView weak var delegate: EmulatorTouchMouseHandlerDelegate? private let positionChangeThreshold: CGFloat = 20.0 private let mouseHoldInterval: TimeInterval = 1.0 private var pendingMouseEvents = [MouseClick]() private var mouseEventPublisher: AnyPublisher<MouseClick, Never> { mouseEventSubject.eraseToAnyPublisher() } private let mouseEventSubject = PassthroughSubject<MouseClick, Never>() private var subscription: AnyCancellable? private var primaryTouch: TouchInfo? private var secondaryTouch: TouchInfo? private let mediumHaptic = UIImpactFeedbackGenerator(style: .medium) public init(view: UIView, delegate: EmulatorTouchMouseHandlerDelegate? = nil) { self.view = view self.delegate = delegate super.init() setup() } private func setup() { subscription = mouseEventPublisher .sink(receiveValue: {[weak self] value in self?.pendingMouseEvents.append(value) self?.processMouseEvents() }) if #available(iOS 13.4, *) { // get pointer interactions let pointerInteraction = UIPointerInteraction(delegate: self) self.view.addInteraction(pointerInteraction) self.view.isUserInteractionEnabled=true } } private func processMouseEvents() { guard let event = pendingMouseEvents.first else { return } delegate?.handleMouseClick(isLeftClick: !event.isRightClick, isPressed: event.isPressed) if event.isPressed { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.mouseEventSubject.send(MouseClick(isRightClick: event.isRightClick, isPressed: false)) } } pendingMouseEvents.removeFirst() processMouseEvents() } @objc private func beginHold() { guard let primaryTouch = primaryTouch, primaryTouch.holdState == .wait else { return } self.primaryTouch = TouchInfo(touch: primaryTouch.touch, origin: primaryTouch.origin, holdState: .held) mediumHaptic.impactOccurred() delegate?.handleMouseClick(isLeftClick: true, isPressed: true) } private func endHold() { guard let primaryTouch = primaryTouch else { return } if primaryTouch.holdState == .notHeld { return } if primaryTouch.holdState == .wait { Thread.cancelPreviousPerformRequests(withTarget: self, selector: #selector(beginHold), object: self) } else { delegate?.handleMouseClick(isLeftClick: true, isPressed: false) } self.primaryTouch = TouchInfo(touch: primaryTouch.touch, origin: primaryTouch.origin, holdState: .notHeld) } public func touchesBegan(touches: Set<UITouch>, event: UIEvent?) { guard enabled, let touch = touches.first else { if #available(iOS 13.4, *), let _ = touches.first { let isLeftClick=(event?.buttonMask == UIEvent.ButtonMask.button(1)) delegate?.handleMouseClick(isLeftClick: isLeftClick, isPressed: true) } return } if primaryTouch == nil { primaryTouch = TouchInfo(touch: touch, origin: touch.location(in: view), holdState: .wait) if touch.tapCount == 2 { self.perform(#selector(beginHold), with: nil, afterDelay: mouseHoldInterval) } } else if secondaryTouch == nil { secondaryTouch = TouchInfo(touch: touch, origin: touch.location(in: view), holdState: .notHeld) } } public func touchesEnded(touches: Set<UITouch>, event: UIEvent?) { guard enabled else { if #available(iOS 13.4, *) { let isLeftClick=(event?.buttonMask == UIEvent.ButtonMask.button(1)) DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in self?.delegate?.handleMouseClick(isLeftClick: isLeftClick, isPressed: false) } } return } for touch in touches { if touch == primaryTouch?.touch { if touch.tapCount > 0 { for _ in 1...touch.tapCount { mouseEventSubject.send(MouseClick(isRightClick: false, isPressed: true)) } } endHold() primaryTouch = nil secondaryTouch = nil } else if touch == secondaryTouch?.touch { if touch.tapCount > 0 { mouseEventSubject.send(MouseClick(isRightClick: true, isPressed: true)) endHold() } secondaryTouch = nil } } delegate?.handleMouseMove(x: 0, y: 0) } public func touchesMoved(touches: Set<UITouch>) { guard enabled else { return } for touch in touches { if touch == primaryTouch?.touch { let a = touch.previousLocation(in: view) let b = touch.location(in: view) if primaryTouch?.holdState == .wait && (distanceBetween(pointA: a, pointB: b) > positionChangeThreshold) { endHold() } delegate?.handleMouseMove(x: b.x-a.x, y: b.y-a.y) } } } public func touchesCancelled(touches: Set<UITouch>, event: UIEvent?) { guard enabled else { if #available(iOS 13.4, *) { let isLeftClick=(event?.buttonMask == UIEvent.ButtonMask.button(1)) delegate?.handleMouseClick(isLeftClick: isLeftClick, isPressed: false) } return } for touch in touches { if touch == primaryTouch?.touch { endHold() } } primaryTouch = nil secondaryTouch = nil } func distanceBetween(pointA: CGPoint, pointB: CGPoint) -> CGFloat { let dx = pointA.x - pointB.x let dy = pointA.y - pointB.y return sqrt(dx*dx*dy*dy) } @available(iOS 13.4, *) public func pointerInteraction( _ interaction: UIPointerInteraction, regionFor request: UIPointerRegionRequest, defaultRegion: UIPointerRegion ) -> UIPointerRegion? { guard !enabled else { return defaultRegion } let location = request.location; delegate?.handlePointerMove(x: location.x, y: location.y) return defaultRegion } }
gpl-3.0
a87b93c4e894b8ae6af37ad4c4d31fea
33.100917
118
0.635055
4.451497
false
false
false
false
yonasstephen/swift-of-airbnb
airbnb-main/airbnb-main/ImageExpandAnimationController.swift
1
5997
// // ImageExpandAnimationController.swift // airbnb-main // // Created by Yonas Stephen on 10/4/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit protocol ImageExpandAnimationControllerProtocol { func getImageDestinationFrame() -> CGRect } class ImageExpandAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var originFrame = CGRect.zero func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to), toVC is ImageExpandAnimationControllerProtocol else { return } let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height let containerView = transitionContext.containerView containerView.backgroundColor = UIColor.white containerView.addSubview(toVC.view) // setup cell image snapshot let initialFrame = originFrame let finalFrame = (toVC as! ImageExpandAnimationControllerProtocol).getImageDestinationFrame() let snapshot = toVC.view.resizableSnapshotView(from: finalFrame, afterScreenUpdates: true, withCapInsets: .zero)! snapshot.frame = initialFrame containerView.addSubview(snapshot) let widthDiff = finalFrame.width - initialFrame.width // setup snapshot to the left of selected cell image let leftInitialFrame = CGRect(x: 0, y: initialFrame.origin.y, width: initialFrame.origin.x, height: initialFrame.height) let leftFinalFrameWidth = leftInitialFrame.width + widthDiff let leftFinalFrame = CGRect(x: finalFrame.origin.x - leftFinalFrameWidth, y: finalFrame.origin.y, width: leftFinalFrameWidth, height: finalFrame.height) let leftSnapshot = fromVC.view.resizableSnapshotView(from: leftInitialFrame, afterScreenUpdates: false, withCapInsets: .zero)! leftSnapshot.frame = leftInitialFrame containerView.addSubview(leftSnapshot) // setup snapshot to the right of selected cell image let rightInitialFrameX = initialFrame.origin.x + initialFrame.width let rightInitialFrame = CGRect(x: rightInitialFrameX, y: initialFrame.origin.y, width: screenWidth - rightInitialFrameX, height: initialFrame.height) let rightFinalFrame = CGRect(x: screenWidth, y: finalFrame.origin.y, width: rightInitialFrame.width + widthDiff, height: finalFrame.height) let rightSnapshot = fromVC.view.resizableSnapshotView(from: rightInitialFrame, afterScreenUpdates: false, withCapInsets: .zero)! rightSnapshot.frame = rightInitialFrame containerView.addSubview(rightSnapshot) // setup snapshot to the bottom of selected cell image let bottomInitialFrameY = initialFrame.origin.y + initialFrame.height let bottomInitialFrame = CGRect(x: 0, y: bottomInitialFrameY, width: screenWidth, height: screenHeight - bottomInitialFrameY) let bottomFinalFrame = CGRect(x: 0, y: screenHeight, width: bottomInitialFrame.width, height: bottomInitialFrame.height) let bottomSnapshot = fromVC.view.resizableSnapshotView(from: bottomInitialFrame, afterScreenUpdates: false, withCapInsets: .zero)! bottomSnapshot.frame = bottomInitialFrame containerView.addSubview(bottomSnapshot) // setup snapshot to the top of selected cell image let topInitialFrame = CGRect(x: 0, y: 0, width: screenWidth, height: initialFrame.origin.y) let topFinalFrame = CGRect(x: 0, y: -topInitialFrame.height, width: topInitialFrame.width, height: topInitialFrame.height) let topSnapshot = fromVC.view.resizableSnapshotView(from: topInitialFrame, afterScreenUpdates: false, withCapInsets: .zero)! topSnapshot.frame = topInitialFrame containerView.addSubview(topSnapshot) // setup the bottom component of the destination view let toVCBottomFinalFrameY = finalFrame.origin.y + finalFrame.height let toVCBottomFinalFrame = CGRect(x: 0, y: toVCBottomFinalFrameY, width: screenWidth, height: screenHeight - toVCBottomFinalFrameY) let toVCBottomInitialFrame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: toVCBottomFinalFrame.height) let toVCBottomSnapshot = toVC.view.resizableSnapshotView(from: toVCBottomFinalFrame, afterScreenUpdates: true, withCapInsets: .zero)! toVCBottomSnapshot.frame = toVCBottomInitialFrame containerView.addSubview(toVCBottomSnapshot) fromVC.view.isHidden = true toVC.view.isHidden = true let duration = transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseInOut], animations: { snapshot.frame = finalFrame leftSnapshot.frame = leftFinalFrame rightSnapshot.frame = rightFinalFrame bottomSnapshot.frame = bottomFinalFrame topSnapshot.frame = topFinalFrame toVCBottomSnapshot.frame = toVCBottomFinalFrame }, completion: { _ in toVC.view.isHidden = false fromVC.view.isHidden = false snapshot.removeFromSuperview() leftSnapshot.removeFromSuperview() rightSnapshot.removeFromSuperview() bottomSnapshot.removeFromSuperview() topSnapshot.removeFromSuperview() toVCBottomSnapshot.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } }
mit
585aa8aff99680ea4ed99704908cfef8
48.553719
160
0.700133
5.436083
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/NSRegularExpression.swift
5
10524
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /* NSRegularExpression is a class used to represent and apply regular expressions. An instance of this class is an immutable representation of a compiled regular expression pattern and various option flags. */ public struct NSRegularExpressionOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let CaseInsensitive = NSRegularExpressionOptions(rawValue: 1 << 0) /* Match letters in the pattern independent of case. */ public static let AllowCommentsAndWhitespace = NSRegularExpressionOptions(rawValue: 1 << 1) /* Ignore whitespace and #-prefixed comments in the pattern. */ public static let IgnoreMetacharacters = NSRegularExpressionOptions(rawValue: 1 << 2) /* Treat the entire pattern as a literal string. */ public static let DotMatchesLineSeparators = NSRegularExpressionOptions(rawValue: 1 << 3) /* Allow . to match any character, including line separators. */ public static let AnchorsMatchLines = NSRegularExpressionOptions(rawValue: 1 << 4) /* Allow ^ and $ to match the start and end of lines. */ public static let UseUnixLineSeparators = NSRegularExpressionOptions(rawValue: 1 << 5) /* Treat only \n as a line separator (otherwise, all standard line separators are used). */ public static let UseUnicodeWordBoundaries = NSRegularExpressionOptions(rawValue: 1 << 6) /* Use Unicode TR#29 to specify word boundaries (otherwise, traditional regular expression word boundaries are used). */ } public class NSRegularExpression : NSObject, NSCopying, NSCoding { public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } /* An instance of NSRegularExpression is created from a regular expression pattern and a set of options. If the pattern is invalid, nil will be returned and an NSError will be returned by reference. The pattern syntax currently supported is that specified by ICU. */ public init(pattern: String, options: NSRegularExpressionOptions) throws { NSUnimplemented() } public var pattern: String { NSUnimplemented() } public var options: NSRegularExpressionOptions { NSUnimplemented() } public var numberOfCaptureGroups: Int { NSUnimplemented() } /* This class method will produce a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as pattern metacharacters. */ public class func escapedPatternForString(string: String) -> String { NSUnimplemented() } } public struct NSMatchingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let ReportProgress = NSMatchingOptions(rawValue: 1 << 0) /* Call the block periodically during long-running match operations. */ public static let ReportCompletion = NSMatchingOptions(rawValue: 1 << 1) /* Call the block once after the completion of any matching. */ public static let Anchored = NSMatchingOptions(rawValue: 1 << 2) /* Limit matches to those at the start of the search range. */ public static let WithTransparentBounds = NSMatchingOptions(rawValue: 1 << 3) /* Allow matching to look beyond the bounds of the search range. */ public static let WithoutAnchoringBounds = NSMatchingOptions(rawValue: 1 << 4) /* Prevent ^ and $ from automatically matching the beginning and end of the search range. */ } public struct NSMatchingFlags : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let Progress = NSMatchingFlags(rawValue: 1 << 0) /* Set when the block is called to report progress during a long-running match operation. */ public static let Completed = NSMatchingFlags(rawValue: 1 << 1) /* Set when the block is called after completion of any matching. */ public static let HitEnd = NSMatchingFlags(rawValue: 1 << 2) /* Set when the current match operation reached the end of the search range. */ public static let RequiredEnd = NSMatchingFlags(rawValue: 1 << 3) /* Set when the current match depended on the location of the end of the search range. */ public static let InternalError = NSMatchingFlags(rawValue: 1 << 4) /* Set when matching failed due to an internal error. */ } extension NSRegularExpression { /* The fundamental matching method on NSRegularExpression is a block iterator. There are several additional convenience methods, for returning all matches at once, the number of matches, the first match, or the range of the first match. Each match is specified by an instance of NSTextCheckingResult (of type NSTextCheckingTypeRegularExpression) in which the overall match range is given by the range property (equivalent to rangeAtIndex:0) and any capture group ranges are given by rangeAtIndex: for indexes from 1 to numberOfCaptureGroups. {NSNotFound, 0} is used if a particular capture group does not participate in the match. */ public func enumerateMatchesInString(string: String, options: NSMatchingOptions, range: NSRange, usingBlock block: (NSTextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func matchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> [NSTextCheckingResult] { NSUnimplemented() } public func numberOfMatchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> Int { NSUnimplemented() } public func firstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult? { NSUnimplemented() } public func rangeOfFirstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSRange { NSUnimplemented() } } /* By default, the block iterator method calls the block precisely once for each match, with a non-nil result and appropriate flags. The client may then stop the operation by setting the contents of stop to YES. If the NSMatchingReportProgress option is specified, the block will also be called periodically during long-running match operations, with nil result and NSMatchingProgress set in the flags, at which point the client may again stop the operation by setting the contents of stop to YES. If the NSMatchingReportCompletion option is specified, the block will be called once after matching is complete, with nil result and NSMatchingCompleted set in the flags, plus any additional relevant flags from among NSMatchingHitEnd, NSMatchingRequiredEnd, or NSMatchingInternalError. NSMatchingReportProgress and NSMatchingReportCompletion have no effect for methods other than the block iterator. NSMatchingHitEnd is set in the flags passed to the block if the current match operation reached the end of the search range. NSMatchingRequiredEnd is set in the flags passed to the block if the current match depended on the location of the end of the search range. NSMatchingInternalError is set in the flags passed to the block if matching failed due to an internal error (such as an expression requiring exponential memory allocations) without examining the entire search range. NSMatchingAnchored, NSMatchingWithTransparentBounds, and NSMatchingWithoutAnchoringBounds can apply to any match or replace method. If NSMatchingAnchored is specified, matches are limited to those at the start of the search range. If NSMatchingWithTransparentBounds is specified, matching may examine parts of the string beyond the bounds of the search range, for purposes such as word boundary detection, lookahead, etc. If NSMatchingWithoutAnchoringBounds is specified, ^ and $ will not automatically match the beginning and end of the search range (but will still match the beginning and end of the entire string). NSMatchingWithTransparentBounds and NSMatchingWithoutAnchoringBounds have no effect if the search range covers the entire string. NSRegularExpression is designed to be immutable and threadsafe, so that a single instance can be used in matching operations on multiple threads at once. However, the string on which it is operating should not be mutated during the course of a matching operation (whether from another thread or from within the block used in the iteration). */ extension NSRegularExpression { /* NSRegularExpression also provides find-and-replace methods for both immutable and mutable strings. The replacement is treated as a template, with $0 being replaced by the contents of the matched range, $1 by the contents of the first capture group, and so on. Additional digits beyond the maximum required to represent the number of capture groups will be treated as ordinary characters, as will a $ not followed by digits. Backslash will escape both $ and itself. */ public func stringByReplacingMatchesInString(string: String, options: NSMatchingOptions, range: NSRange, withTemplate templ: String) -> String { NSUnimplemented() } public func replaceMatchesInString(string: NSMutableString, options: NSMatchingOptions, range: NSRange, withTemplate templ: String) -> Int { NSUnimplemented() } /* For clients implementing their own replace functionality, this is a method to perform the template substitution for a single result, given the string from which the result was matched, an offset to be added to the location of the result in the string (for example, in case modifications to the string moved the result since it was matched), and a replacement template. */ public func replacementStringForResult(result: NSTextCheckingResult, inString string: String, offset: Int, template templ: String) -> String { NSUnimplemented() } /* This class method will produce a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as template metacharacters. */ public class func escapedTemplateForString(string: String) -> String { NSUnimplemented() } }
apache-2.0
03d1a92f7b7ea625b154efeb1552bea4
92.964286
901
0.772805
5.243647
false
false
false
false
LoveAlwaysYoung/EnjoyUniversity
EnjoyUniversity/EnjoyUniversity/Classes/Tools/NetWork/EUNetworkManager.swift
1
3397
// // EUNetworkManager.swift // EnjoyUniversity // // Created by lip on 17/3/28. // Copyright © 2017年 lip. All rights reserved. // import Foundation import Alamofire class EUNetworkManager{ /// 用户账户信息 lazy var userAccount = EUserAccount() let manager = Alamofire.SessionManager.default // 创建单例 static let shared:EUNetworkManager = { // 可以在这里配置网络请求参数 return EUNetworkManager() }() init() { manager.session.configuration.timeoutIntervalForRequest = 10 } /// 封装网络请求 /// /// - Parameters: /// - urlString: 请求地址 /// - method: 请求方式,默认 GET 方式 /// - parameters: 请求参数 /// - completion: 完成回调 返回数据的 data 部分/网络请求是否成功/状态码 func request(urlString:String,method:HTTPMethod = .get,parameters:Parameters?,completion:@escaping (Any?,Bool,Int)->()) { // let request = Alamofire.request(urlString, method:method, parameters: parameters, encoding: URLEncoding.default, headers: nil) let datarequest = manager.request(urlString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: nil) // 设置超时时间 print("请求网址:\(datarequest)") datarequest.responseJSON { (response) in if response.result.isSuccess { guard let dict = response.result.value as? [String:Any],let statuscode = dict["status"] as? Int,let json = dict["data"] else{ completion(nil,false,400) return } if statuscode == 403{ SwiftyProgressHUD.showBigFaildHUD(text: "登陆信息失效", duration: 2) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: { self.userAccount.outLogin() UIApplication.shared.keyWindow?.rootViewController?.present(EULoginViewController(), animated: true, completion: nil) }) return } completion(json,true,statuscode) }else{ completion(nil, false,0) } } } /// 带有 Access Token 的请求 /// /// - Parameters: /// - urlString: 请求地址 /// - method: 请求方式 /// - parameters: 请求参数 [Sting:Any]类型 /// - completion: 完成回调 func tokenRequest(urlString:String,method:HTTPMethod = .get,parameters:Parameters?,completion:@escaping (Any?,Bool,Int)->()){ // 判断 Token 是否存在,不存在则不做请求 guard let token = userAccount.accesstoken else { completion(nil, false,0) return } var parameters = parameters if parameters == nil{ parameters = Parameters() } parameters!["accesstoken"] = token request(urlString: urlString, method: method, parameters: parameters, completion: completion) } }
mit
e3f50cecab2e08252a98893572dffe1a
27.563636
142
0.532782
4.917058
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/Services/PeopleService.swift
1
3426
import Foundation struct PeopleService { let remote: PeopleRemote let siteID: Int private let context = ContextManager.sharedInstance().mainContext init(blog: Blog) { remote = PeopleRemote(api: blog.restApi()) siteID = blog.dotComID as Int } func refreshTeam(completion: (Bool) -> Void) { remote.getTeamFor(siteID, success: { (people) -> () in self.mergeTeam(people) completion(true) }, failure: { (error) -> () in DDLogSwift.logError(String(error)) completion(false) }) } private func mergeTeam(people: People) { let remotePeople = people let localPeople = allPeople() let remoteIDs = Set(remotePeople.map({ $0.ID })) let localIDs = Set(localPeople.map({ $0.ID })) let removedIDs = localIDs.subtract(remoteIDs) removeManagedPeopleWithIDs(removedIDs) // Let's try to only update objects that have changed let remoteChanges = remotePeople.filter { return !localPeople.contains($0) } for remotePerson in remoteChanges { if let existingPerson = managedPersonWithID(remotePerson.ID) { existingPerson.updateWith(remotePerson) DDLogSwift.logDebug("Updated person \(existingPerson)") } else { createManagedPerson(remotePerson) } } ContextManager.sharedInstance().saveContext(context) } private func allPeople() -> People { let request = NSFetchRequest(entityName: "Person") request.predicate = NSPredicate(format: "siteID = %@", NSNumber(integer: siteID)) let results: [ManagedPerson] do { results = try context.executeFetchRequest(request) as! [ManagedPerson] } catch { DDLogSwift.logError("Error fetching all people: \(error)") results = [] } return results.map { return Person(managedPerson: $0) } } private func managedPersonWithID(id: Int) -> ManagedPerson? { let request = NSFetchRequest(entityName: "Person") request.predicate = NSPredicate(format: "siteID = %@ AND userID = %@", NSNumber(integer: siteID), NSNumber(integer: id)) request.fetchLimit = 1 let results = (try? context.executeFetchRequest(request) as! [ManagedPerson]) ?? [] return results.first } private func removeManagedPeopleWithIDs(ids: Set<Int>) { if ids.isEmpty { return } let numberIDs = ids.map { return NSNumber(integer: $0) } let request = NSFetchRequest(entityName: "Person") request.predicate = NSPredicate(format: "siteID = %@ AND userID IN %@", NSNumber(integer: siteID), numberIDs) let objects = (try? context.executeFetchRequest(request) as! [NSManagedObject]) ?? [] for object in objects { DDLogSwift.logDebug("Removing person: \(object)") context.deleteObject(object) } } private func createManagedPerson(person: Person) { let managedPerson = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: context) as! ManagedPerson managedPerson.updateWith(person) DDLogSwift.logDebug("Created person \(managedPerson)") } }
gpl-2.0
ad16d87959732ab3388f6da09059c220
33.969388
140
0.609749
4.936599
false
false
false
false
ewhitley/CDAKit
CDAKit/health-data-standards/swift_helpers/NSDate+Formatters.swift
1
5131
// // NSDate+Formatters.swift // CDAKit // // Created by Eric Whitley on 12/2/15. // Copyright © 2015 Eric Whitley. All rights reserved. // import Foundation extension NSDate { var stringFormattedAsRFC3339: String { return rfc3339formatter.stringFromDate(self) } //http://stackoverflow.com/questions/24089999/how-do-you-create-a-swift-date-object //NSDate(dateString:"2014-06-06") //https://gist.github.com/algal/09b08515460b7bd229fa class func dateFromRFC3339FormattedString(rfc3339FormattedString:String) -> NSDate? { /* NOTE: will replace this with a failible initializer when Apple fixes the bug that requires the initializer to initialize all stored properties before returning nil, even when this is impossible. */ if let d = rfc3339formatter.dateFromString(rfc3339FormattedString) { return NSDate(timeInterval:0,sinceDate:d) } else { return nil } } var stringFormattedAsHDSDate: String { return hdsDateformatter.stringFromDate(self).stringByReplacingOccurrencesOfString(",", withString: daySuffix(self)+",") } var stringFormattedAsHDSDateNumber: String { return hdsDateNumberformatter.stringFromDate(self) } class func dateFromHDSFormattedString(hdsFormattedString:String) -> NSDate? { //we're abusing the possible formats here // if we have "December 31, 2009" we're OK for date formatter // if we have "December 31st, 2009" then we have to rip out st, nd, rd, th day suffixes if let d = hdsDateformatter.dateFromString(CDAKCommonUtility.Regex.replaceMatches("(\\d)(st|nd|rd|th)(,)", inString: hdsFormattedString, withString: "$1$3")!) { return NSDate(timeInterval:0,sinceDate:d) } else if let d = hdsDateNumberformatter.dateFromString(hdsFormattedString) { return NSDate(timeInterval: 0, sinceDate: d) } else if let d = hdsDateNumberFormatterShort.dateFromString(hdsFormattedString) { return NSDate(timeInterval: 0, sinceDate: d) } else if let d = hdsDateNumberFormatterYearOnly.dateFromString(hdsFormattedString) { return NSDate(timeInterval: 0, sinceDate: d) } else { return nil } } //http://stackoverflow.com/questions/7416865/date-formatter-for-converting-14-sept-2011-in-14th-sept //http://stackoverflow.com/questions/1283045/ordinal-month-day-suffix-option-for-nsdateformatter-setdateformat func daySuffix(date: NSDate) -> String { //let calendar = NSCalendar.currentCalendar() let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)! calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0) let dayOfMonth = calendar.component(.Day, fromDate: date) switch dayOfMonth { case 1, 21, 31: return "st" case 2, 22: return "nd" case 3, 23: return "rd" default: return "th" } } } private var rfc3339formatter:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)! formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter }() // http://apidock.com/rails/ActiveSupport/CoreExtensions/DateTime/Conversions/to_formatted_s // datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00" // http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/ private var hdsDateformatter:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "MMMM d, yyyy HH:mm" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)! formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter }() //20070118061017 //http://apidock.com/rails/Time/to_formatted_s private var hdsDateNumberformatter:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyyMMddHHmmss" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)! formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter }() //we've seen some files not following spec and failing to include HHmmss //200701180 private var hdsDateNumberFormatterShort:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyyMMdd" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)! formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter }() //as well as just years.... social history with just "1947" //200701180 private var hdsDateNumberFormatterYearOnly:NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)! formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter }()
mit
49b9c7bf817387dce853902919aab4e8
36.452555
162
0.747173
4.087649
false
false
false
false
meteochu/Alamofire
Source/ParameterEncoding.swift
1
11356
// // ParameterEncoding.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case URL case URLEncodedInURL case JSON case PropertyList(PropertyListSerialization.PropertyListFormat, PropertyListSerialization.WriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (URLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied. - parameter parameters: The parameters to apply. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( urlRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (URLRequest, NSError?) { var mutableURLRequest = urlRequest.urlRequest guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil switch self { case .URL, .URLEncodedInURL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(isOrderedBefore: <) { let value = parameters[key]! components += queryComponents(key: key, value) } return (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&") } func encodesParametersInURL(method: Method) -> Bool { switch self { case .URLEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: mutableURLRequest.httpMethod!) where encodesParametersInURL(method: method) { if var URLComponents = URLComponents(url: mutableURLRequest.url!, resolvingAgainstBaseURL: false) where !parameters.isEmpty { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters: parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.url = URLComponents.url } } else { if mutableURLRequest.value(forHTTPHeaderField: "Content-Type") == nil { mutableURLRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } mutableURLRequest.httpBody = query(parameters: parameters).data( using: String.Encoding.utf8, allowLossyConversion: false ) } case .JSON: do { let options = JSONSerialization.WritingOptions() let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if mutableURLRequest.value(forHTTPHeaderField: "Content-Type") == nil { mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } mutableURLRequest.httpBody = data } catch { encodingError = error as NSError } case .PropertyList(let format, let options): do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if mutableURLRequest.value(forHTTPHeaderField: "Content-Type") == nil { mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } mutableURLRequest.httpBody = data } catch { encodingError = error as NSError } case .Custom(let closure): (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents(key: "\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents(key: "\(key)[]", value) } } else { components.append((escape(string: key), escape(string: "\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, OSX 10.10, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) let range = startIndex..<endIndex! let substring = string.substring(with: range) escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring index = endIndex! } } return escaped } }
mit
232aa043e1d3cee2e29b01e034900734
42.676923
136
0.587091
5.528724
false
false
false
false
AlanEnjoy/Live
Live/Live/Classes/Home/Controller/RecommendViewController.swift
1
3720
// // RecommendViewController.swift // Live // // Created by Alan's Macbook on 2017/7/4. // Copyright © 2017年 zhushuai. All rights reserved. // import UIKit fileprivate let kCycleViewH = kScreenW * 3 / 8 fileprivate let kGameViewH : CGFloat = 90 class RecommendViewController: BaseAnchorViewController { //MARK:- 懒加载属性 fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() fileprivate lazy var recommandVM: RecommendViewModel = RecommendViewModel() } //MARK:- 设置UI界面内容 extension RecommendViewController { override func setupUI() { super.setupUI() //1.调用父类的setupUI方法 super.setupUI() //2.将CycleView添加到UICollectionView中 collectionView.addSubview(cycleView) //3.将GameView添加到CollectionView中 collectionView.addSubview(gameView) //4.设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) } } //MARK:- 发送网络请求 extension RecommendViewController { override func loadData() { //0.给父类中的ViewModel进行赋值 baseVM = recommandVM //1.请求推荐数据 recommandVM.requestData { //1.1. 展示推荐数据 self.collectionView.reloadData() //1.2 将数据传递给GameView var groups = self.recommandVM.anchorGroups //1.3 移除前两组数据 groups.removeFirst() groups.removeFirst() groups.remove(at: 1) groups.remove(at: 4) //1.4 添加“更多”组 let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" groups.append(moreGroup) self.gameView.groups = groups //2.数据请求完成 self.loadDataFinished() } //2.请求轮播数据 recommandVM.requestCycleData { self.cycleView.cycleModels = self.recommandVM.cycleModels } } } extension RecommendViewController : UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { //1.取出PrettyCell let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! PrettyCell //2.设置数据 prettyCell.anchor = recommandVM.anchorGroups[indexPath.section].anchors[indexPath.item] return prettyCell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } }
mit
7e4d02f232ba30b2210cd85f6ebc1674
30.383929
160
0.621053
5.358232
false
false
false
false
tunespeak/AlamoRecord
Example/AlamoRecord/PostCell.swift
1
4453
// // PostCell.swift // AlamoRecord // // Created by Dalton Hinterscher on 7/6/17. // Copyright © 2017 CocoaPods. All rights reserved. // protocol PostCellDelegate: class { func commentsButtonPressed(at index: Int) func destroyButtonPressed(at index: Int) } import UIKit class PostCell: BaseTableViewCell { weak var delegate: PostCellDelegate? private var titleLabel: UILabel! private var bodyLabel: UILabel! required init() { super.init() selectionStyle = .none titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.font = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize * 1.25) resizableView.addSubview(titleLabel) bodyLabel = UILabel() bodyLabel.numberOfLines = 0 bodyLabel.font = UIFont.systemFont(ofSize: UIFont.systemFontSize) resizableView.addSubview(bodyLabel) let footerView = UIView() footerView.backgroundColor = resizableView.backgroundColor resizableView.addSubview(footerView) let footerViewTopBorderView = UIView() footerViewTopBorderView.backgroundColor = .lightGray footerView.addSubview(footerViewTopBorderView) let commentsButton = UIButton() commentsButton.setTitle("COMMENTS", for: .normal) commentsButton.setTitleColor(.blue, for: .normal) commentsButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize) commentsButton.addTarget(self, action: #selector(commentsButtonPressed), for: .touchUpInside) footerView.addSubview(commentsButton) let seperatorView = UIView() seperatorView.backgroundColor = footerViewTopBorderView.backgroundColor footerView.addSubview(seperatorView) let destroyButton = UIButton() destroyButton.setTitle("DESTROY", for: .normal) destroyButton.setTitleColor(.red, for: .normal) destroyButton.titleLabel?.font = commentsButton.titleLabel?.font destroyButton.addTarget(self, action: #selector(destroyButtonPressed), for: .touchUpInside) footerView.addSubview(destroyButton) titleLabel.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(10) make.left.equalToSuperview().offset(10) make.right.equalToSuperview().offset(-10) } bodyLabel.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom).offset(5) make.left.equalTo(titleLabel) make.right.equalTo(titleLabel) } footerView.snp.makeConstraints { (make) in make.top.equalTo(bodyLabel.snp.bottom).offset(20) make.left.equalTo(titleLabel) make.right.equalTo(titleLabel) make.height.equalTo(35) } footerViewTopBorderView.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview() make.right.equalToSuperview() make.height.equalTo(1) } commentsButton.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview() make.width.equalToSuperview().multipliedBy(0.5) make.height.equalToSuperview() } seperatorView.snp.makeConstraints { (make) in make.top.equalToSuperview() make.bottom.equalToSuperview() make.width.equalTo(footerViewTopBorderView.snp.height) make.centerX.equalToSuperview() } destroyButton.snp.makeConstraints { (make) in make.top.equalToSuperview() make.right.equalToSuperview() make.width.equalToSuperview().multipliedBy(0.5) make.height.equalToSuperview() } autoResize(under: footerView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bind(post: Post) { titleLabel.text = post.title bodyLabel.text = post.body } @objc private dynamic func commentsButtonPressed() { delegate?.commentsButtonPressed(at: indexPath.row) } @objc private dynamic func destroyButtonPressed() { delegate?.destroyButtonPressed(at: indexPath.row) } }
mit
cf4ed6bfcbef22a664d53da62a10ec47
33.78125
101
0.638814
5.12313
false
false
false
false
SanctionCo/pilot-ios
pilot/Publishable.swift
1
2208
// // Publishable.swift // pilot // // Created by Nick Eckert on 8/28/17. // Copyright © 2017 sanction. All rights reserved. // import Alamofire import AVFoundation import Foundation // The publishable protocol allows an object to be published through lightning's publish endpoint. protocol Publishable { } extension Publishable { typealias SuccessHandler = () -> Void typealias ErrorHandler = (Error) -> Void typealias ProgressHandler = (Double) -> Void static func publish(post: Post, with request: URLRequestConvertible, onProgress: @escaping ProgressHandler, onSuccess: @escaping SuccessHandler, onError: @escaping ErrorHandler) { NetworkManager.sharedInstance.upload(multipartFormData: { multipartFormData in switch post.type { case .photo: // Encode an image into the request if let image = post.image, let imageData = UIImageJPEGRepresentation(image, 1) { multipartFormData.append(imageData, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg") } case .video: // Encode a video into the request // Because a video can exceed memory limits a file URL is used instead guard let fileURL = post.video else { return } multipartFormData.append(fileURL, withName: "file", fileName: "video.mov", mimeType: "video/quicktime") case .text: // Encode an empty string into the request multipartFormData.append("".data(using: .utf8)!, withName: "file") } }, with: request, encodingCompletion: { encodingResult in switch encodingResult { case .success(let uploadRequest, _, _): uploadRequest.uploadProgress { progress in let percentage = progress.fractionCompleted onProgress(percentage) }.responseJSON { response in switch response.result { case .success: onSuccess() case .failure(let error): onError(error) } } case .failure(let encodingError): debugPrint(encodingError) onError(encodingError) } }) } }
mit
8d7171471c174bbeae5cf8f7e4d62546
31.455882
111
0.63208
5.061927
false
false
false
false
DeepLearningKit/DeepLearningKit
tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/tvOSDeepLearningKitApp/ImageUtilityFunctions.swift
2
2959
// // ImageUtilityFunctions.swift // iOSDeepLearningKitApp // // This code is a contribution from Maciej Szpakowski - https://github.com/several27 // with a minor fix by Stanislav Ashmanov https://github.com/ashmanov // ref: issue - https://github.com/DeepLearningKit/DeepLearningKit/issues/8 // // Copyright © 2016 DeepLearningKit. All rights reserved. // import Foundation import UIKit import Accelerate func imageToMatrix(image: UIImage) -> ([Float], [Float], [Float], [Float]) { let imageRef = image.CGImage let width = CGImageGetWidth(imageRef) let height = CGImageGetHeight(imageRef) let colorSpace = CGColorSpaceCreateDeviceRGB() let bytesPerPixel = 4 let bytesPerRow:UInt = UInt(bytesPerPixel) * UInt(width) let bitsPerComponent:UInt = 8 let pix = Int(width) * Int(height) let count:Int = 4 * Int(pix) // Pulling the color out of the image let rawData = UnsafeMutablePointer<UInt8>.alloc(4 * width * height) let temp = CGImageAlphaInfo.PremultipliedLast.rawValue let context = CGBitmapContextCreate(rawData, Int(width), Int(height), Int(bitsPerComponent), Int(bytesPerRow), colorSpace, temp) CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef) // Unsigned char to double conversion var rawDataArray: [Float] = Array(count: count, repeatedValue: 0.0) vDSP_vfltu8(rawData, vDSP_Stride(1), &rawDataArray, 1, vDSP_Length(count)) // Indices matrix var i: [Float] = Array(count: pix, repeatedValue: 0.0) var min: Float = 0.0 var step: Float = 4.0 vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count)) func increaseMatrix(var matrix: [Float]) -> [Float] { var increaser: Float = 1.0 vDSP_vsadd(&matrix, vDSP_Stride(1), &increaser, &matrix, vDSP_Stride(1), vDSP_Length(i.count)) return matrix } // Red matrix var r: [Float] = Array(count: pix, repeatedValue: 0.0) vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &r, vDSP_Stride(1), vDSP_Length(r.count)) increaseMatrix(i) min = 1.0 vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count)) // Green matrix var g: [Float] = Array(count: pix, repeatedValue: 0.0) vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &g, vDSP_Stride(1), vDSP_Length(g.count)) increaseMatrix(i) min = 2.0 vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count)) // Blue matrix var b: [Float] = Array(count: pix, repeatedValue: 0.0) vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &b, vDSP_Stride(1), vDSP_Length(b.count)) increaseMatrix(i) min = 3.0 vDSP_vramp(&min, &step, &i, vDSP_Stride(1), vDSP_Length(i.count)) // Alpha matrix var a: [Float] = Array(count: pix, repeatedValue: 0.0) vDSP_vindex(&rawDataArray, &i, vDSP_Stride(1), &a, vDSP_Stride(1), vDSP_Length(a.count)) return (r, g, b, a) }
apache-2.0
23492cb216e2a8c8dcf87a69e2cbd5f3
36.935897
132
0.658553
3.4
false
false
false
false
novi/mysql-swift
Sources/MySQL/Connection.swift
1
4365
// // Database.swift // MySQL // // Created by ito on 2015/10/24. // Copyright © 2015年 Yusuke Ito. All rights reserved. // import CMySQL import CoreFoundation import Foundation internal struct MySQLUtil { internal static func getMySQLError(_ mysql: UnsafeMutablePointer<MYSQL>) -> String { guard let strPtr = mysql_error(mysql) else { return "unknown error. could not get error with `mysql_error()`." } guard let errorString = String(validatingUTF8: strPtr) else { return "unknown error. could not get error as string." } return errorString } } public protocol ConnectionOption { var host: String { get } var port: Int { get } var user: String { get } var password: String { get } var database: String { get } var timeZone: TimeZone { get } var encoding: Connection.Encoding { get } var timeout: Int { get } var reconnect: Bool { get } var omitDetailsOnError: Bool { get } } fileprivate let defaultTimeZone = TimeZone(identifier: "UTC")! public extension ConnectionOption { // Provide default options var timeZone: TimeZone { return defaultTimeZone } var encoding: Connection.Encoding { return .UTF8MB4 } var timeout: Int { return 10 } var reconnect: Bool { return true } var omitDetailsOnError: Bool { return true } } extension Connection { public enum Encoding: String { case UTF8 = "utf8" case UTF8MB4 = "utf8mb4" } } public enum ConnectionError: Error { case connectionError(String) case connectionPoolGetConnectionTimeoutError } public final class Connection { internal var isInUse: Bool = false private var mysql_: UnsafeMutablePointer<MYSQL>? internal let pool: ConnectionPool public let option: ConnectionOption internal init(option: ConnectionOption, pool: ConnectionPool) { self.option = option self.pool = pool self.mysql_ = nil } internal func release() { pool.releaseConnection(self) } internal static func setReconnect(_ reconnect: Bool, mysql: UnsafeMutablePointer<MYSQL>) { let reconnectPtr = UnsafeMutablePointer<my_bool>.allocate(capacity: 1) reconnectPtr.pointee = reconnect == false ? 0 : 1 mysql_options(mysql, MYSQL_OPT_RECONNECT, reconnectPtr) reconnectPtr.deallocate() } func setReconnect(_ reconnect: Bool) { if let mysql = mysql { Connection.setReconnect(reconnect, mysql: mysql) } } internal func connect() throws -> UnsafeMutablePointer<MYSQL> { dispose() guard let mysql = mysql_init(nil) else { fatalError("mysql_init() failed.") } do { let timeoutPtr = UnsafeMutablePointer<Int>.allocate(capacity: 1) timeoutPtr.pointee = option.timeout mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, timeoutPtr) timeoutPtr.deallocate() } Connection.setReconnect(option.reconnect, mysql: mysql) if mysql_real_connect(mysql, option.host, option.user, option.password, option.database, UInt32(option.port), nil, 0) == nil { // error throw ConnectionError.connectionError(MySQLUtil.getMySQLError(mysql)) } mysql_set_character_set(mysql, option.encoding.rawValue) self.mysql_ = mysql return mysql } internal func connectIfNeeded() throws -> UnsafeMutablePointer<MYSQL> { guard let mysql = self.mysql_ else { return try connect() } return mysql } private var mysql: UnsafeMutablePointer<MYSQL>? { guard mysql_ != nil else { return nil } return mysql_ } internal func ping() -> Bool { _ = try? connectIfNeeded() guard let mysql = mysql else { return false } return mysql_ping(mysql) == 0 } private func dispose() { guard let mysql = mysql else { return } mysql_close(mysql) self.mysql_ = nil } deinit { dispose() } }
mit
41650742037023cafbaace30d6428dab
24.810651
94
0.594911
4.630573
false
false
false
false
szk-atmosphere/SAParallaxViewControllerSwift
SAParallaxViewControllerSwift/SAParallaxViewCell.swift
2
1769
// // SAParallaxViewCell.swift // SAParallaxViewControllerSwift // // Created by 鈴木大貴 on 2015/01/30. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit open class SAParallaxViewCell: UICollectionViewCell { open var containerView = SAParallaxContainerView() fileprivate var previousImageOffset = CGPoint.zero public convenience init() { self.init(frame: .zero) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } public override init(frame: CGRect) { super.init(frame: frame) initialize() } open override func prepareForReuse() { containerView.removeFromSuperview() initialize() } //MARK: - SAParallaxViewCell Private Methods fileprivate func initialize() { containerView.frame = bounds addSubview(containerView) } //MARK: - SAParallaxViewCell Public Methods open func setImage(_ image: UIImage) { containerView.setImage(image) } open func setImageOffset(_ offset: CGPoint) { if isSelected { return } containerView.setImageOffset(offset) } open func screenShot() -> UIImageView { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(self.frame.size, false, scale) containerView.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageView = UIImageView(frame: containerView.bounds) imageView.image = image return imageView } }
mit
67b10dd61182a15597743c9bc6674811
24.75
77
0.634495
5.29003
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/Buttons/ButtonView/ButtonView.swift
1
6514
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxCocoa import RxSwift import UIKit /// The standard wallet button. /// Typically located at the bottom of a context, used as primary / secondary CTA buttons. /// - see also: [ButtonViewModel](x-source-tag://ButtonViewModel). public final class ButtonView: UIView { // MARK: - UI Properties private let button = UIButton(type: .system) private let imageView = UIImageView(image: nil) private let label = UILabel(frame: .zero) // Constraints for scenario with title only, and no image private var labelToImageViewLeadingConstraint: NSLayoutConstraint! private var labelToSuperviewLeadingConstraint: NSLayoutConstraint! private var labelToSuperviewBottomConstraint: NSLayoutConstraint! private var labelToSuperviewTopConstraint: NSLayoutConstraint! private var labelToSuperviewTrailingConstraint: NSLayoutConstraint! // MARK: - Rx private var disposeBag = DisposeBag() // MARK: - Dependencies public var viewModel: ButtonViewModel! { willSet { disposeBag = DisposeBag() } didSet { guard let viewModel = viewModel else { button.isEnabled = false label.text = nil imageView.image = nil return } // Set non-reactive properties layer.cornerRadius = viewModel.cornerRadius label.font = viewModel.font // Set accessibility accessibility = viewModel.accessibility // Bind background color viewModel.backgroundColor .drive(rx.backgroundColor) .disposed(by: disposeBag) // Bind border color viewModel.borderColor .drive(layer.rx.borderColor) .disposed(by: disposeBag) // bind label color viewModel.contentColor .drive(label.rx.textColor) .disposed(by: disposeBag) // Bind label text color viewModel.text .drive(label.rx.text) .disposed(by: disposeBag) // Bind image view tint color viewModel.contentColor .drive(imageView.rx.tintColor) .disposed(by: disposeBag) // Bind image view's image viewModel.image .drive(imageView.rx.image) .disposed(by: disposeBag) // Bind view model enabled indication to button viewModel.isEnabled .drive(button.rx.isEnabled) .disposed(by: disposeBag) // Bind opacity viewModel.alpha .drive(rx.alpha) .disposed(by: disposeBag) // bind contains image viewModel.containsImage .bind { [weak self] containsImage in guard let self = self else { return } if containsImage { self.label.textAlignment = .natural self.labelToImageViewLeadingConstraint.priority = .penultimateHigh self.labelToSuperviewLeadingConstraint.priority = .penultimateLow } else { self.label.textAlignment = .center self.labelToImageViewLeadingConstraint.priority = .penultimateLow self.labelToSuperviewLeadingConstraint.priority = .penultimateHigh } self.layoutIfNeeded() } .disposed(by: disposeBag) // Bind button taps button.rx.tap .throttle( .milliseconds(200), latest: false, scheduler: ConcurrentDispatchQueueScheduler(qos: .background) ) .observe(on: MainScheduler.instance) .bindAndCatch(to: viewModel.tapRelay) .disposed(by: disposeBag) viewModel.contentInset .drive(onNext: { [weak self] contentInset in self?.updateContentInset(to: contentInset) }) .disposed(by: disposeBag) } } private func updateContentInset(to contentInset: UIEdgeInsets) { labelToSuperviewLeadingConstraint.constant = contentInset.left labelToSuperviewBottomConstraint.constant = -contentInset.bottom labelToSuperviewTopConstraint.constant = contentInset.top labelToSuperviewTrailingConstraint.constant = -contentInset.right layoutIfNeeded() } // MARK: - Setup override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { clipsToBounds = true layer.borderWidth = 1 addSubview(imageView) addSubview(button) addSubview(label) // Button button.layoutToSuperview(.leading, .trailing, .top, .bottom) button.addTargetForTouchUp(self, selector: #selector(touchUp)) button.addTargetForTouchDown(self, selector: #selector(touchDown)) // ImageView imageView.contentMode = .left imageView.layoutToSuperview(.top, .bottom) imageView.layoutToSuperview(.leading, offset: 16) imageView.layout(edge: .trailing, to: .centerX, of: self, relation: .equal, offset: -10, priority: .penultimateHigh) // Label label.numberOfLines = 0 labelToSuperviewLeadingConstraint = label.layoutToSuperview(.leading, priority: .penultimateHigh) labelToSuperviewTrailingConstraint = label.layoutToSuperview(.trailing) labelToSuperviewTopConstraint = label.layoutToSuperview(.top) labelToSuperviewBottomConstraint = label.layoutToSuperview(.bottom) labelToImageViewLeadingConstraint = label.layout(edge: .leading, to: .trailing, of: imageView, priority: .penultimateLow) } // MARK: - User Interactions @objc private func touchUp() { alpha = 1 } @objc private func touchDown() { alpha = 0.85 } } extension Reactive where Base: ButtonView { public var viewModel: Binder<ButtonViewModel> { Binder(base) { buttonView, viewModel in buttonView.viewModel = viewModel } } }
lgpl-3.0
64cc43081af1e8d9f47753b65274d10c
33.099476
129
0.598035
5.510152
false
false
false
false
DrabWeb/Azusa
Source/Azusa/Azusa/View Controllers/Preferences/PluginsPreferencesController.swift
1
4249
// // PluginsPreferencesController.swift // Azusa // // Created by Ushio on 2/14/17. // import Cocoa import Yui class PluginsPreferencesController: NSViewController { // MARK: - Properties // MARK: - Private Properties @IBOutlet internal weak var tableView : NSTableView! @IBOutlet private weak var preferencesContainerView: NSView! @IBOutlet private weak var enabledCheckbox: NSButton! @IBAction private func enabledCheckbox(_ sender: NSButton) { currentPlugin?.toggleEnabled(); refresh(); Preferences.global.postUpdatedNotification(); } @IBAction func applyButton(_ sender: NSButton) { if currentPlugin != nil && currentPlugin?.isEnabled ?? false { Preferences.global.pluginSettings[currentPlugin!.bundleIdentifier] = preferencesController!.getSettings(); Preferences.global.postUpdatedNotification(); } } @IBAction func makeDefaultButton(_ sender: NSButton) { currentPlugin?.makeDefault(); refresh(recreateSettingsView: false); Preferences.global.postUpdatedNotification(); } private var preferencesController : PluginPreferencesController? = nil; private var currentPlugin : PluginInfo? = nil; // MARK: - Methods // MARK: Public Methods override func viewDidAppear() { super.viewDidAppear(); // Called here instead of `viewDidLoad` because `viewDidLoad` is also called for child controllers, so there's an infinite loop from creating the plugin's preferences controller refresh(); } // MARK: Private Methods internal func refresh(recreateSettingsView : Bool = true) { if PluginManager.global.plugins.count > 0 { // Refresh the cells without resetting selection and scroll position for i in 0...PluginManager.global.plugins.count - 1 { (tableView.rowView(atRow: i, makeIfNecessary: false)?.view(atColumn: i) as? PluginsPreferencesCellView)?.display(plugin: PluginManager.global.plugins[i]); } if recreateSettingsView { if currentPlugin != nil { display(plugin: currentPlugin!); } else { display(plugin: PluginManager.global.plugins[tableView.selectedRow < 0 ? 0 : tableView.selectedRow]); } } } } // TODO: Test this with multiple plugins internal func display(plugin : PluginInfo) { currentPlugin = plugin; enabledCheckbox.state = plugin.isEnabled ? NSOnState : NSOffState; preferencesController?.view.removeFromSuperview(); preferencesController?.removeFromParentViewController(); if (plugin.isEnabled) { preferencesController = plugin.getPlugin!.getPreferencesController(); self.addChildViewController(preferencesController!); preferencesContainerView.addSubview(preferencesController!.view); preferencesController!.view.frame = preferencesContainerView.bounds; preferencesController!.view.autoresizingMask = [.viewWidthSizable, .viewHeightSizable]; preferencesController!.view.translatesAutoresizingMaskIntoConstraints = true; preferencesController!.display(settings: currentPlugin!.settings); } } } // MARK: - NSTableViewDataSource extension PluginsPreferencesController: NSTableViewDataSource { func numberOfRows(in aTableView: NSTableView) -> Int { return PluginManager.global.plugins.count; } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if let cellView = tableView.make(withIdentifier: "DataColumn", owner: nil) as? PluginsPreferencesCellView { cellView.display(plugin: PluginManager.global.plugins[row]); return cellView; } return nil; } } // MARK: - NSTableViewDelegate extension PluginsPreferencesController: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { refresh(); } }
gpl-3.0
3382f658a9431f474ef6ffc46e559677
35.316239
185
0.654507
5.605541
false
false
false
false
huonw/swift
test/IDE/print_ast_tc_function_bodies.swift
6
6204
// This file should not have any syntax or type checker errors. // RUN: %target-typecheck-verify-swift // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false > %t.printed.txt // RUN: %FileCheck %s -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -strict-whitespace < %t.printed.txt struct FooStruct { // CHECK-LABEL: {{^}}struct FooStruct {{{$}} var instanceVar: Int // CHECK-NEXT: {{^}} var instanceVar: Int{{$}} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } // CHECK-NEXT: {{^}} subscript(i: Int) -> Double {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(v) {{{$}} // CHECK: {{^}} }{{$}} // CHECK: {{^}} }{{$}} subscript(i: Int, j: Int) -> Double { get { return Double(i + j) } set(v) { instanceVar = i + j } } // CHECK-NEXT: {{^}} subscript(i: Int, j: Int) -> Double {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(v) {{{$}} // CHECK: {{^}} }{{$}} // CHECK: {{^}} }{{$}} } extension FooStruct { // CHECK-LABEL: {{^}}extension FooStruct {{{$}} var extProp: Int { get { return 42 } set(v) {} } // CHECK-NEXT: {{^}} var extProp: Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(v) {}{{$}} // CHECK-NEXT: {{^}} }{{$}} } //===--- //===--- Variable declaration printing. //===--- var topLevelVar1: Int { get { return 42 } } // CHECK: {{^}}var topLevelVar1: Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}}}{{$}} // CHECK-NOT: topLevelVar1 var topLevelVar2: Int { get { return 22 } set { if true {} } } // CHECK: {{^}}var topLevelVar2: Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}}}{{$}} // CHECK-NOT: topLevelVar2 var topLevelVar3: Int { get { return 42 } set(foo) { if true {} } } // CHECK: {{^}}var topLevelVar3: Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(foo) {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}}}{{$}} // CHECK-NOT: topLevelVar3 class InClassVar1 { // CHECK-LABEL: InClassVar1 var instanceVar1: Int { get { return 12 } } // CHECK: {{^}} var instanceVar1: Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NOT: instanceVar1 var instanceVar2: Int { get { return 42 } set { if true {} } } // CHECK-NEXT: {{^}} var instanceVar2: Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NOT: instanceVar2 var instanceVar3: Int { get { return 42 } set(foo) { if true {} } } // CHECK: {{^}} var instanceVar3: Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(foo) {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NOT: instanceVar3 } //===--- //===--- Subscript declaration printing. //===--- class InClassSubscript1 { // CHECK-LABEL: InClassSubscript1 subscript(i: Int) -> Int { get { return 42 } set { if true {} } } // CHECK: {{^}} subscript(i: Int) -> Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK: {{^}} set {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NOT: subscript } class InClassSubscript2 { // CHECK-LABEL: InClassSubscript2 subscript(i: Int) -> Int { get { return 42 } set(value) { if true {} } } // CHECK: {{^}} subscript(i: Int) -> Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(value) {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NOT: subscript } class InClassSubscript3 { // CHECK-LABEL: InClassSubscript3 subscript(i: Int) -> Int { get { return 42 } set(foo) { if true {} } } // CHECK: {{^}} subscript(i: Int) -> Int {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(foo) {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NOT: subscript } class InClassSubscript4 { // CHECK-LABEL: InClassSubscript4 subscript<T>(i: T) -> T where T: Equatable { get { return i } set(foo) { if true {} } } // CHECK: {{^}} subscript<T>(i: T) -> T where T : Equatable {{{$}} // CHECK-NEXT: {{^}} get {{{$}} // CHECK-NEXT: {{^}} return {{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK: {{^}} set(foo) {{{$}} // CHECK-NEXT: {{^}} if {{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NEXT: {{^}} }{{$}} // CHECK-NOT: subscript }
apache-2.0
73df2757e22d06fbde61b3786ef6d77a
22.5
141
0.440683
3.458194
false
false
false
false
onebytecode/krugozor-iOSVisitors
Pods/SwiftyBeaver/Sources/BaseDestination.swift
1
17050
// // BaseDestination.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger (Twitter @skreutzb) on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation import Dispatch // store operating system / platform #if os(iOS) let OS = "iOS" #elseif os(OSX) let OS = "OSX" #elseif os(watchOS) let OS = "watchOS" #elseif os(tvOS) let OS = "tvOS" #elseif os(Linux) let OS = "Linux" #elseif os(FreeBSD) let OS = "FreeBSD" #elseif os(Windows) let OS = "Windows" #elseif os(Android) let OS = "Android" #else let OS = "Unknown" #endif /// destination which all others inherit from. do not directly use open class BaseDestination: Hashable, Equatable { /// output format pattern, see documentation for syntax open var format = "$DHH:mm:ss.SSS$d $C$L$c $N.$F:$l - $M" /// runs in own serial background thread for better performance open var asynchronously = true /// do not log any message which has a lower level than this one open var minLevel = SwiftyBeaver.Level.verbose /// set custom log level words for each level open var levelString = LevelString() /// set custom log level colors for each level open var levelColor = LevelColor() public struct LevelString { public var verbose = "VERBOSE" public var debug = "DEBUG" public var info = "INFO" public var warning = "WARNING" public var error = "ERROR" } // For a colored log level word in a logged line // empty on default public struct LevelColor { public var verbose = "" // silver public var debug = "" // green public var info = "" // blue public var warning = "" // yellow public var error = "" // red } var reset = "" var escape = "" var filters = [FilterType]() let formatter = DateFormatter() // each destination class must have an own hashValue Int lazy public var hashValue: Int = self.defaultHashValue open var defaultHashValue: Int {return 0} // each destination instance must have an own serial queue to ensure serial output // GCD gives it a prioritization between User Initiated and Utility var queue: DispatchQueue? //dispatch_queue_t? var debugPrint = false // set to true to debug the internal filter logic of the class public init() { let uuid = NSUUID().uuidString let queueLabel = "swiftybeaver-queue-" + uuid queue = DispatchQueue(label: queueLabel, target: queue) } /// send / store the formatted log message to the destination /// returns the formatted log message for processing by inheriting method /// and for unit tests (nil if error) open func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { if format.hasPrefix("$J") { return messageToJSON(level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) } else { return formatMessage(format, level: level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) } } //////////////////////////////// // MARK: Format //////////////////////////////// /// returns the log message based on the format pattern func formatMessage(_ format: String, level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String { var text = "" let phrases: [String] = format.components(separatedBy: "$") for phrase in phrases where !phrase.isEmpty { let firstChar = phrase[phrase.startIndex] let rangeAfterFirstChar = phrase.index(phrase.startIndex, offsetBy: 1)..<phrase.endIndex let remainingPhrase = phrase[rangeAfterFirstChar] switch firstChar { case "L": text += levelWord(level) + remainingPhrase case "M": text += msg + remainingPhrase case "T": text += thread + remainingPhrase case "N": // name of file without suffix text += fileNameWithoutSuffix(file) + remainingPhrase case "n": // name of file with suffix text += fileNameOfFile(file) + remainingPhrase case "F": text += function + remainingPhrase case "l": text += String(line) + remainingPhrase case "D": // start of datetime format #if swift(>=3.2) text += formatDate(String(remainingPhrase)) #else text += formatDate(remainingPhrase) #endif case "d": text += remainingPhrase case "Z": // start of datetime format in UTC timezone #if swift(>=3.2) text += formatDate(String(remainingPhrase), timeZone: "UTC") #else text += formatDate(remainingPhrase, timeZone: "UTC") #endif case "z": text += remainingPhrase case "C": // color code ("" on default) text += escape + colorForLevel(level) + remainingPhrase case "c": text += reset + remainingPhrase case "X": // add the context if let cx = context { text += String(describing: cx).trimmingCharacters(in: .whitespacesAndNewlines) + remainingPhrase } /* if let contextString = context as? String { text += contextString + remainingPhrase }*/ default: text += phrase } } return text } /// returns the log payload as optional JSON string func messageToJSON(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { var dict: [String: Any] = [ "timestamp": Date().timeIntervalSince1970, "level": level.rawValue, "message": msg, "thread": thread, "file": file, "function": function, "line": line ] if let cx = context { dict["context"] = cx } return jsonStringFromDict(dict) } /// returns the string of a level func levelWord(_ level: SwiftyBeaver.Level) -> String { var str = "" switch level { case SwiftyBeaver.Level.debug: str = levelString.debug case SwiftyBeaver.Level.info: str = levelString.info case SwiftyBeaver.Level.warning: str = levelString.warning case SwiftyBeaver.Level.error: str = levelString.error default: // Verbose is default str = levelString.verbose } return str } /// returns color string for level func colorForLevel(_ level: SwiftyBeaver.Level) -> String { var color = "" switch level { case SwiftyBeaver.Level.debug: color = levelColor.debug case SwiftyBeaver.Level.info: color = levelColor.info case SwiftyBeaver.Level.warning: color = levelColor.warning case SwiftyBeaver.Level.error: color = levelColor.error default: color = levelColor.verbose } return color } /// returns the filename of a path func fileNameOfFile(_ file: String) -> String { let fileParts = file.components(separatedBy: "/") if let lastPart = fileParts.last { return lastPart } return "" } /// returns the filename without suffix (= file ending) of a path func fileNameWithoutSuffix(_ file: String) -> String { let fileName = fileNameOfFile(file) if !fileName.isEmpty { let fileNameParts = fileName.components(separatedBy: ".") if let firstPart = fileNameParts.first { return firstPart } } return "" } /// returns a formatted date string /// optionally in a given abbreviated timezone like "UTC" func formatDate(_ dateFormat: String, timeZone: String = "") -> String { if !timeZone.isEmpty { formatter.timeZone = TimeZone(abbreviation: timeZone) } formatter.dateFormat = dateFormat //let dateStr = formatter.string(from: NSDate() as Date) let dateStr = formatter.string(from: Date()) return dateStr } /// returns the json-encoded string value /// after it was encoded by jsonStringFromDict func jsonStringValue(_ jsonString: String?, key: String) -> String { guard let str = jsonString else { return "" } // remove the leading {"key":" from the json string and the final } let offset = key.characters.count + 5 let endIndex = str.index(str.startIndex, offsetBy: str.characters.count - 2) let range = str.index(str.startIndex, offsetBy: offset)..<endIndex #if swift(>=3.2) return String(str[range]) #else return str[range] #endif } /// turns dict into JSON-encoded string func jsonStringFromDict(_ dict: [String: Any]) -> String? { var jsonString: String? // try to create JSON string do { let jsonData = try JSONSerialization.data(withJSONObject: dict, options: []) jsonString = String(data: jsonData, encoding: .utf8) } catch { print("SwiftyBeaver could not create JSON from dict.") } return jsonString } //////////////////////////////// // MARK: Filters //////////////////////////////// /// Add a filter that determines whether or not a particular message will be logged to this destination public func addFilter(_ filter: FilterType) { filters.append(filter) } /// Remove a filter from the list of filters public func removeFilter(_ filter: FilterType) { let index = filters.index { return ObjectIdentifier($0) == ObjectIdentifier(filter) } guard let filterIndex = index else { return } filters.remove(at: filterIndex) } /// Answer whether the destination has any message filters /// returns boolean and is used to decide whether to resolve /// the message before invoking shouldLevelBeLogged func hasMessageFilters() -> Bool { return !getFiltersTargeting(Filter.TargetType.Message(.Equals([], true)), fromFilters: self.filters).isEmpty } /// checks if level is at least minLevel or if a minLevel filter for that path does exist /// returns boolean and can be used to decide if a message should be logged or not func shouldLevelBeLogged(_ level: SwiftyBeaver.Level, path: String, function: String, message: String? = nil) -> Bool { if filters.isEmpty { if level.rawValue >= minLevel.rawValue { if debugPrint { print("filters is empty and level >= minLevel") } return true } else { if debugPrint { print("filters is empty and level < minLevel") } return false } } let (matchedExclude, allExclude) = passedExcludedFilters(level, path: path, function: function, message: message) if allExclude > 0 && matchedExclude != allExclude { if debugPrint { print("filters is not empty and message was excluded") } return false } let (matchedRequired, allRequired) = passedRequiredFilters(level, path: path, function: function, message: message) let (matchedNonRequired, allNonRequired) = passedNonRequiredFilters(level, path: path, function: function, message: message) // If required filters exist, we should validate or invalidate the log if all of them pass or not if allRequired > 0 { return matchedRequired == allRequired } // If a non-required filter matches, the log is validated if allNonRequired > 0 && matchedNonRequired > 0 { return true } if level.rawValue < minLevel.rawValue { if debugPrint { print("filters is not empty and level < minLevel") } return false } return true } func getFiltersTargeting(_ target: Filter.TargetType, fromFilters: [FilterType]) -> [FilterType] { return fromFilters.filter { filter in return filter.getTarget() == target } } /// returns a tuple of matched and all filters func passedRequiredFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let requiredFilters = self.filters.filter { filter in return filter.isRequired() && !filter.isExcluded() } let matchingFilters = applyFilters(requiredFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(requiredFilters.count) required filters") } return (matchingFilters, requiredFilters.count) } /// returns a tuple of matched and all filters func passedNonRequiredFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let nonRequiredFilters = self.filters.filter { filter in return !filter.isRequired() && !filter.isExcluded() } let matchingFilters = applyFilters(nonRequiredFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(nonRequiredFilters.count) non-required filters") } return (matchingFilters, nonRequiredFilters.count) } /// returns a tuple of matched and all exclude filters func passedExcludedFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let excludeFilters = self.filters.filter { filter in return filter.isExcluded() } let matchingFilters = applyFilters(excludeFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(excludeFilters.count) exclude filters") } return (matchingFilters, excludeFilters.count) } func applyFilters(_ targetFilters: [FilterType], level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Int { return targetFilters.filter { filter in let passes: Bool if !filter.reachedMinLevel(level) { return false } switch filter.getTarget() { case .Path(_): passes = filter.apply(path) case .Function(_): passes = filter.apply(function) case .Message(_): guard let message = message else { return false } passes = filter.apply(message) } return passes }.count } /** Triggered by main flush() method on each destination. Runs in background thread. Use for destinations that buffer log items, implement this function to flush those buffers to their final destination (web server...) */ func flush() { // no implementation in base destination needed } } public func == (lhs: BaseDestination, rhs: BaseDestination) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
apache-2.0
4b0ef7b1ff1f7d21fb0b438d5611f1a5
33.936475
120
0.557511
5.158548
false
false
false
false
dbart01/Rigid
Rigid/IfElseWritable.swift
1
2694
// // IfElseWritable.swift // Rigid // // Copyright (c) 2015 Dima Bart // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. import Foundation struct IfElseWritable: Writable { typealias IfElsePair = (ifBlock: Writable, elseBlock: Writable) var indent: Int = 0 let condition: String let pair: IfElsePair let useLineBreaks: Bool // ---------------------------------- // MARK: - Init - // init(condition: String, pair: IfElsePair, useLineBreaks: Bool = false) { self.condition = condition self.pair = pair self.useLineBreaks = useLineBreaks } // ---------------------------------- // MARK: - Writable - // func content() -> String { var content = "\n" content += "#if \(self.condition)" if self.useLineBreaks { content += "\n" } content += pair.ifBlock.content() content += "#else" if self.useLineBreaks { content += "\n" } content += pair.elseBlock.content() content += "#endif\n" return content } }
bsd-2-clause
15740605b967f052ca5004a1c0394182
35.418919
83
0.648478
4.550676
false
false
false
false
tlax/GaussSquad
GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemSin.swift
1
863
import UIKit class MCalculatorFunctionsItemSin:MCalculatorFunctionsItem { init() { let icon:UIImage = #imageLiteral(resourceName: "assetFunctionSin") let title:String = NSLocalizedString("MCalculatorFunctionsItemSin_title", comment:"") super.init( icon:icon, title:title) } override func processFunction( currentValue:Double, currentString:String, modelKeyboard:MKeyboard, view:UITextView) { let sinValue:Double = sin(currentValue) let sinString:String = modelKeyboard.numberAsString(scalar:sinValue) let descr:String = "rad sin(\(currentString)) = \(sinString)" applyUpdate( modelKeyboard:modelKeyboard, view:view, newEditing:sinString, descr:descr) } }
mit
37e1d7298c6d8f1f9735845167141b1e
26.83871
93
0.612978
4.715847
false
false
false
false
EvanJq/JQNavigationController
Example/JQNavigationController/ViewController2.swift
1
3869
// // ViewController2.swift // JQNavigationController // // Created by Evan on 2017/7/10. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import JQNavigationController let kScreenWidth = UIScreen.main.bounds.width let kScreenHeight = UIScreen.main.bounds.height let kNavBarBottom = 64 private let IMAGE_HEIGHT:CGFloat = kScreenWidth*1080/1920 private let NAVBAR_COLORCHANGE_POINT:CGFloat = -IMAGE_HEIGHT private let SCROLL_DOWN_LIMIT:CGFloat = 0 private let LIMIT_OFFSET_Y:CGFloat = -(IMAGE_HEIGHT + SCROLL_DOWN_LIMIT) class ViewController2: UIViewController { var tableView: UITableView! var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "列表标题" navBarBackgroundAlpha = 0 navBarBarTintColor = .white navBarShadowImageHidden = true tableView = UITableView(frame: self.view.bounds, style: .plain) tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") tableView.contentInset = UIEdgeInsetsMake(IMAGE_HEIGHT-CGFloat(kNavBarBottom), 0, 0, 0) self.view.addSubview(tableView) imageView = UIImageView(frame: CGRect(x: 0, y: -IMAGE_HEIGHT, width: kScreenWidth, height: IMAGE_HEIGHT)) imageView.image = UIImage(named: "20141113105823721") tableView.addSubview(imageView) } } extension ViewController2: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "Index: \(indexPath.row)" return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // print(self.navigationController?.wrapRootViewController) // print(self.navigationController?.wrapViewController) // self.navigationController?.popToWrapViewController((self.navigationController?.wrapViewController?[0])!, animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetY = scrollView.contentOffset.y if (offsetY > NAVBAR_COLORCHANGE_POINT) { let alpha = (offsetY - NAVBAR_COLORCHANGE_POINT) / CGFloat(kNavBarBottom) navBarBackgroundAlpha = alpha if (alpha > 0.5) { navBarBarTintColor = UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1.0) navBarTitleColor = .black statusBarStyle = .default } else { navBarBarTintColor = .white navBarTitleColor = .white statusBarStyle = .lightContent } navBarShadowImageHidden = false } else { navBarBackgroundAlpha = 0 navBarBarTintColor = .white navBarTitleColor = .white statusBarStyle = .lightContent navBarShadowImageHidden = true } // 限制下拉距离 if (offsetY < LIMIT_OFFSET_Y) { scrollView.contentOffset = CGPoint.init(x: 0, y: LIMIT_OFFSET_Y) } // 改变图片框的大小 (上滑的时候不改变) // 这里不能使用offsetY,因为当(offsetY < LIMIT_OFFSET_Y)的时候,y = LIMIT_OFFSET_Y 不等于 offsetY let newOffsetY = scrollView.contentOffset.y if (newOffsetY < -IMAGE_HEIGHT) { imageView.frame = CGRect(x: 0, y: newOffsetY, width: kScreenWidth, height: -newOffsetY) } } }
mit
61e85c5623648893c2f0052b41b4c7ae
34.28972
128
0.655191
4.638821
false
false
false
false
wangCanHui/weiboSwift
weiboSwift/Classes/Module/Message/Controller/CZMessageViewController.swift
1
3242
// // CZMessageViewController.swift // weiboSwift // // Created by 王灿辉 on 15/10/26. // Copyright © 2015年 王灿辉. All rights reserved. // import UIKit class CZMessageViewController: CZBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
2c65b4c3e3f2c782c3acd18b845f52b6
32.968421
157
0.686706
5.525685
false
false
false
false
joehour/JImageLoader
JImageLoader/CacheManager.swift
1
1836
// // CacheManager.swift // JImageLoader // // Created by JoeJoe on 2016/7/25. // Copyright © 2016年 Joe. All rights reserved. // import Foundation public let JImageLoaderCache:NSCache<NSString, CacheInfo>? = NSCache<NSString, CacheInfo>() public func set_cache(object: CacheInfo){ //let cache: NSCache = NSCache() JImageLoaderCache!.setObject(object, forKey: object.key! as NSString) //cache_list.addObject(cache) } public func set_cache(data: NSData, key: String ){ let info: CacheInfo = CacheInfo() info.data = data info.key = key JImageLoaderCache!.setObject(info, forKey: info.key! as NSString) } public func find_cache(key: String)-> CacheInfo?{ if let item = JImageLoaderCache!.object(forKey: key as NSString) { guard let _item: CacheInfo = item else{ return nil } return _item } else{ return nil } } public func find_cache(key: String, completion: (_ cache_info: CacheInfo?)->()){ if let item = JImageLoaderCache!.object(forKey: key as NSString) { guard let _item: CacheInfo = item else{ completion(nil) return } completion(_item) } else{ completion(nil) } } public func delect_cache(key: String){ if find_cache(key: key) != nil { JImageLoaderCache!.removeObject(forKey: key as NSString) } } public func delect_all_cache(){ if JImageLoaderCache != nil { JImageLoaderCache?.removeAllObjects() } } public func get_size(){ if JImageLoaderCache != nil { } } public class CacheInfo: NSObject { public var data: NSData? public var data_type: String? public var key: String? }
mit
2de11e77fc5799d8bdf5b29c65dd92b8
19.142857
91
0.593562
3.984783
false
false
false
false
CatchChat/Yep
Yep/Views/ActionSheet/ActionSheetView.swift
1
18044
// // ActionSheetView.swift // Yep // // Created by NIX on 16/3/2. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit import YepKit // MARK: - ActionSheetDefaultCell final private class ActionSheetDefaultCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var colorTitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) return label }() var colorTitleLabelTextColor: UIColor = UIColor.yepTintColor() { willSet { colorTitleLabel.textColor = newValue } } func makeUI() { contentView.addSubview(colorTitleLabel) colorTitleLabel.translatesAutoresizingMaskIntoConstraints = false let centerY = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let centerX = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([centerY, centerX]) } } // MARK: - ActionSheetDetailCell final private class ActionSheetDetailCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) accessoryType = .DisclosureIndicator layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) textLabel?.textColor = UIColor.darkGrayColor() textLabel?.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - ActionSheetSwitchCell final private class ActionSheetSwitchCell: UITableViewCell { var action: (Bool -> Void)? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) textLabel?.textColor = UIColor.darkGrayColor() textLabel?.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var checkedSwitch: UISwitch = { let s = UISwitch() s.addTarget(self, action: #selector(ActionSheetSwitchCell.toggleSwitch(_:)), forControlEvents: .ValueChanged) return s }() @objc private func toggleSwitch(sender: UISwitch) { action?(sender.on) } func makeUI() { contentView.addSubview(checkedSwitch) checkedSwitch.translatesAutoresizingMaskIntoConstraints = false let centerY = NSLayoutConstraint(item: checkedSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: checkedSwitch, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -20) NSLayoutConstraint.activateConstraints([centerY, trailing]) } } // MARK: - ActionSheetSubtitleSwitchCell final private class ActionSheetSubtitleSwitchCell: UITableViewCell { var action: (Bool -> Void)? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) return label }() lazy var subtitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(10, weight: UIFontWeightLight) label.textColor = UIColor.lightGrayColor() return label }() lazy var checkedSwitch: UISwitch = { let s = UISwitch() s.addTarget(self, action: #selector(ActionSheetSwitchCell.toggleSwitch(_:)), forControlEvents: .ValueChanged) return s }() @objc private func toggleSwitch(sender: UISwitch) { action?(sender.on) } func makeUI() { contentView.addSubview(checkedSwitch) titleLabel.translatesAutoresizingMaskIntoConstraints = false subtitleLabel.translatesAutoresizingMaskIntoConstraints = false checkedSwitch.translatesAutoresizingMaskIntoConstraints = false let titleStackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel]) titleStackView.axis = .Vertical titleStackView.distribution = .Fill titleStackView.alignment = .Fill titleStackView.spacing = 2 titleStackView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleStackView) do { let centerY = NSLayoutConstraint(item: titleStackView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let leading = NSLayoutConstraint(item: titleStackView, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .Leading, multiplier: 1, constant: 20) NSLayoutConstraint.activateConstraints([centerY, leading]) } do { let centerY = NSLayoutConstraint(item: checkedSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: checkedSwitch, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -20) NSLayoutConstraint.activateConstraints([centerY, trailing]) } let gap = NSLayoutConstraint(item: checkedSwitch, attribute: .Leading, relatedBy: .Equal, toItem: titleStackView, attribute: .Trailing, multiplier: 1, constant: 10) NSLayoutConstraint.activateConstraints([gap]) } } final private class ActionSheetCheckCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var colorTitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) return label }() lazy var checkImageView: UIImageView = { let image = UIImage.yep_iconLocationCheckmark let imageView = UIImageView(image: image) return imageView }() var colorTitleLabelTextColor: UIColor = UIColor.yepTintColor() { willSet { colorTitleLabel.textColor = newValue } } func makeUI() { contentView.addSubview(colorTitleLabel) contentView.addSubview(checkImageView) colorTitleLabel.translatesAutoresizingMaskIntoConstraints = false checkImageView.translatesAutoresizingMaskIntoConstraints = false let centerY = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let centerX = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([centerY, centerX]) let checkImageViewCenterY = NSLayoutConstraint(item: checkImageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let checkImageViewTrailing = NSLayoutConstraint(item: checkImageView, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -20) NSLayoutConstraint.activateConstraints([checkImageViewCenterY, checkImageViewTrailing]) } } // MARK: - ActionSheetView final class ActionSheetView: UIView { enum Item { case Default(title: String, titleColor: UIColor, action: () -> Bool) case Detail(title: String, titleColor: UIColor, action: () -> Void) case Switch(title: String, titleColor: UIColor, switchOn: Bool, action: (switchOn: Bool) -> Void) case SubtitleSwitch(title: String, titleColor: UIColor, subtitle: String, subtitleColor: UIColor, switchOn: Bool, action: (switchOn: Bool) -> Void) case Check(title: String, titleColor: UIColor, checked: Bool, action: () -> Void) case Cancel } var items: [Item] private let rowHeight: CGFloat = 60 private var totalHeight: CGFloat { return CGFloat(items.count) * rowHeight } init(items: [Item]) { self.items = items super.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var containerView: UIView = { let view = UIView() view.backgroundColor = UIColor.clearColor() return view }() private lazy var tableView: UITableView = { let view = UITableView() view.dataSource = self view.delegate = self view.rowHeight = self.rowHeight view.scrollEnabled = false view.registerClassOf(ActionSheetDefaultCell) view.registerClassOf(ActionSheetDetailCell) view.registerClassOf(ActionSheetSwitchCell) view.registerClassOf(ActionSheetSubtitleSwitchCell) view.registerClassOf(ActionSheetCheckCell) return view }() private var isFirstTimeBeenAddedAsSubview = true override func didMoveToSuperview() { super.didMoveToSuperview() if isFirstTimeBeenAddedAsSubview { isFirstTimeBeenAddedAsSubview = false makeUI() let tap = UITapGestureRecognizer(target: self, action: #selector(ActionSheetView.hide)) containerView.addGestureRecognizer(tap) tap.cancelsTouchesInView = true tap.delegate = self } } func refreshItems() { dispatch_async(dispatch_get_main_queue()) { [weak self] in self?.tableView.reloadData() } } private var tableViewBottomConstraint: NSLayoutConstraint? private func makeUI() { addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false let viewsDictionary: [String: AnyObject] = [ "containerView": containerView, "tableView": tableView, ] // layout for containerView let containerViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[containerView]|", options: [], metrics: nil, views: viewsDictionary) let containerViewConstraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[containerView]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(containerViewConstraintsH) NSLayoutConstraint.activateConstraints(containerViewConstraintsV) // layout for tableView let tableViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: [], metrics: nil, views: viewsDictionary) let tableViewBottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1.0, constant: self.totalHeight) self.tableViewBottomConstraint = tableViewBottomConstraint let tableViewHeightConstraint = NSLayoutConstraint(item: tableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: self.totalHeight) NSLayoutConstraint.activateConstraints(tableViewConstraintsH) NSLayoutConstraint.activateConstraints([tableViewBottomConstraint, tableViewHeightConstraint]) } func showInView(view: UIView) { frame = view.bounds view.addSubview(self) layoutIfNeeded() containerView.alpha = 1 UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseIn, animations: { [weak self] _ in self?.containerView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3) }, completion: nil) UIView.animateWithDuration(0.2, delay: 0.1, options: .CurveEaseOut, animations: { [weak self] _ in self?.tableViewBottomConstraint?.constant = 0 self?.layoutIfNeeded() }, completion: nil) } func hide() { UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseIn, animations: { [weak self] _ in guard let strongSelf = self else { return } strongSelf.tableViewBottomConstraint?.constant = strongSelf.totalHeight strongSelf.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(0.2, delay: 0.1, options: .CurveEaseOut, animations: { [weak self] _ in self?.containerView.backgroundColor = UIColor.clearColor() }, completion: { [weak self] _ in self?.removeFromSuperview() }) } func hideAndDo(afterHideAction: (() -> Void)?) { UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveLinear, animations: { [weak self] _ in guard let strongSelf = self else { return } strongSelf.containerView.alpha = 0 strongSelf.tableViewBottomConstraint?.constant = strongSelf.totalHeight strongSelf.layoutIfNeeded() }, completion: { [weak self] _ in self?.removeFromSuperview() }) delay(0.1) { afterHideAction?() } } } // MARK: - UIGestureRecognizerDelegate extension ActionSheetView: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if touch.view != containerView { return false } return true } } // MARK: - UITableViewDataSource, UITableViewDelegate extension ActionSheetView: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = items[indexPath.row] switch item { case let .Default(title, titleColor, _): let cell: ActionSheetDefaultCell = tableView.dequeueReusableCell() cell.colorTitleLabel.text = title cell.colorTitleLabelTextColor = titleColor return cell case let .Detail(title, titleColor, _): let cell: ActionSheetDetailCell = tableView.dequeueReusableCell() cell.textLabel?.text = title cell.textLabel?.textColor = titleColor return cell case let .Switch(title, titleColor, switchOn, action): let cell: ActionSheetSwitchCell = tableView.dequeueReusableCell() cell.textLabel?.text = title cell.textLabel?.textColor = titleColor cell.checkedSwitch.on = switchOn cell.action = action return cell case let .SubtitleSwitch(title, titleColor, subtitle, subtitleColor, switchOn, action): let cell: ActionSheetSubtitleSwitchCell = tableView.dequeueReusableCell() cell.titleLabel.text = title cell.titleLabel.textColor = titleColor cell.subtitleLabel.text = subtitle cell.subtitleLabel.textColor = subtitleColor cell.checkedSwitch.on = switchOn cell.action = action return cell case let .Check(title, titleColor, checked, _): let cell: ActionSheetCheckCell = tableView.dequeueReusableCell() cell.colorTitleLabel.text = title cell.colorTitleLabelTextColor = titleColor cell.checkImageView.hidden = !checked return cell case .Cancel: let cell: ActionSheetDefaultCell = tableView.dequeueReusableCell() cell.colorTitleLabel.text = String.trans_cancel cell.colorTitleLabelTextColor = UIColor.yepTintColor() return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { defer { tableView.deselectRowAtIndexPath(indexPath, animated: true) } let item = items[indexPath.row] switch item { case .Default(_, _, let action): if action() { hide() } case .Detail(_, _, let action): hideAndDo { action() } case .Switch: break case .SubtitleSwitch: break case .Check(_, _, _, let action): action() hide() case .Cancel: hide() break } } }
mit
5ba21119d964914887a91df87ec101b1
32.347505
202
0.666759
5.275146
false
false
false
false
RxSwiftCommunity/RxGRDB
Tests/RxGRDBTests/DatabaseWriterWriteTests.swift
1
17089
import GRDB import RxBlocking import RxGRDB import RxSwift import XCTest private struct Player: Codable, FetchableRecord, PersistableRecord { var id: Int64 var name: String var score: Int? static func createTable(_ db: Database) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() t.column("score", .integer) } } } class DatabaseWriterWriteTests : XCTestCase { func testRxJoiner() { // Make sure `rx` joiner is available in various contexts func f1(_ writer: DatabasePool) { _ = writer.rx.write(updates: { db in }) } func f2(_ writer: DatabaseQueue) { _ = writer.rx.write(updates: { db in }) } func f4<Writer: DatabaseWriter>(_ writer: Writer) { _ = writer.rx.write(updates: { db in }) } func f5(_ writer: DatabaseWriter) { _ = writer.rx.write(updates: { db in }) } } // MARK: - Write func testWriteObservable() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) throws { let single = writer.rx.write(updates: { db -> Int in try Player(id: 1, name: "Arthur", score: 1000).insert(db) return try Player.fetchCount(db) }) let count = try single.toBlocking(timeout: 1).single() XCTAssertEqual(count, 1) } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - func testWriteObservableAsCompletable() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) throws { let completable = writer.rx .write(updates: { db -> Int in try Player(id: 1, name: "Arthur", score: 1000).insert(db) return try Player.fetchCount(db) }) .asCompletable() _ = try completable.toBlocking(timeout: 1).last() } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - func testWriteObservableError() throws { func test(writer: DatabaseWriter) throws { let single = writer.rx.write(updates: { db in try db.execute(sql: "THIS IS NOT SQL") }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.sql, "THIS IS NOT SQL") } } try Test(test) .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testWriteObservableErrorRollbacksTransaction() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) throws { let single = writer.rx.write(updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) try db.execute(sql: "THIS IS NOT SQL") }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.sql, "THIS IS NOT SQL") } let count = try writer.read(Player.fetchCount) XCTAssertEqual(count, 0) } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - func testWriteObservableIsAsynchronous() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) throws { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) writer.rx .write(updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) }) .subscribe( onSuccess: { semaphore.wait() expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) semaphore.signal() waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testWriteObservableDefaultScheduler() throws { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, *) { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let expectation = self.expectation(description: "") writer.rx .write(updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) }) .subscribe( onSuccess: { _ in dispatchPrecondition(condition: .onQueue(.main)) expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } // MARK: - func testWriteObservableCustomScheduler() throws { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, *) { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let queue = DispatchQueue(label: "test") let expectation = self.expectation(description: "") writer.rx .write( observeOn: SerialDispatchQueueScheduler(queue: queue, internalSerialQueueName: "test"), updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) }) .subscribe( onSuccess: { _ in dispatchPrecondition(condition: .onQueue(queue)) expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } // MARK: - WriteThenRead func testWriteThenReadObservable() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) throws { let single = writer.rx.write( updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) }, thenRead: { db, _ in try Player.fetchCount(db) }) let count = try single.toBlocking(timeout: 1).single() XCTAssertEqual(count, 1) } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - func testWriteThenReadObservableIsReadonly() throws { func test(writer: DatabaseWriter) throws { let single = writer.rx.write( updates: { _ in }, thenRead: { db, _ in try Player.createTable(db) }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_READONLY) } } try Test(test) .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - func testWriteThenReadObservableWriteError() throws { func test(writer: DatabaseWriter) throws { let single = writer.rx.write( updates: { db in try db.execute(sql: "THIS IS NOT SQL") }, thenRead: { _, _ in }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.sql, "THIS IS NOT SQL") } } try Test(test) .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testWriteThenReadObservableWriteErrorRollbacksTransaction() throws { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) throws { let single = writer.rx.write( updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) try db.execute(sql: "THIS IS NOT SQL") }, thenRead: { _, _ in }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.sql, "THIS IS NOT SQL") } let count = try writer.read(Player.fetchCount) XCTAssertEqual(count, 0) } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - func testWriteThenReadObservableReadError() throws { func test(writer: DatabaseWriter) throws { let single = writer.rx.write( updates: { _ in }, thenRead: { db, _ in try Row.fetchAll(db, sql: "THIS IS NOT SQL") }) do { _ = try single.toBlocking(timeout: 1).single() XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.sql, "THIS IS NOT SQL") } } try Test(test) .run { try DatabaseQueue() } .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - func testWriteThenReadObservableDefaultScheduler() throws { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, *) { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let expectation = self.expectation(description: "") writer.rx .write( updates: { _ in }, thenRead: { _, _ in }) .subscribe( onSuccess: { _ in dispatchPrecondition(condition: .onQueue(.main)) expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } // MARK: - func testWriteThenReadObservableCustomScheduler() throws { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, *) { func setUp<Writer: DatabaseWriter>(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer } func test(writer: DatabaseWriter) { let disposeBag = DisposeBag() withExtendedLifetime(disposeBag) { let queue = DispatchQueue(label: "test") let expectation = self.expectation(description: "") writer.rx .write( observeOn: SerialDispatchQueueScheduler(queue: queue, internalSerialQueueName: "test"), updates: { _ in }, thenRead: { _, _ in }) .subscribe( onSuccess: { _ in dispatchPrecondition(condition: .onQueue(queue)) expectation.fulfill() }, onFailure: { error in XCTFail("Unexpected error \(error)") }) .disposed(by: disposeBag) waitForExpectations(timeout: 1, handler: nil) } } try Test(test) .run { try setUp(DatabaseQueue()) } .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } }
mit
481d337bc2334af559c1622dbb72de77
38.375576
115
0.49962
5.416482
false
true
false
false
kazuhiro4949/StringStylizer
StringStylizer/StringStylizerFontName.swift
1
14366
// // StringStylizerFontName.swift // // // Copyright (c) 2016 Kazuhiro Hayashi // // 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 /** available font names in iOS App This enumeration is extracted from UIFont on iOS11 ``` let name = UIFont.familyNames .flatMap { UIFont.fontNames(forFamilyName: $0) } .map { "case \($0.replacingOccurrences(of: "-", with: "_")) = \"\($0)\"" } .joined(separator: "\n") print(name) ``` */ public enum StringStylizerFontName: String { case Copperplate_Light = "Copperplate-Light" case Copperplate = "Copperplate" case Copperplate_Bold = "Copperplate-Bold" case AppleSDGothicNeo_Thin = "AppleSDGothicNeo-Thin" case AppleSDGothicNeo_Light = "AppleSDGothicNeo-Light" case AppleSDGothicNeo_Regular = "AppleSDGothicNeo-Regular" case AppleSDGothicNeo_Bold = "AppleSDGothicNeo-Bold" case AppleSDGothicNeo_SemiBold = "AppleSDGothicNeo-SemiBold" case AppleSDGothicNeo_UltraLight = "AppleSDGothicNeo-UltraLight" case AppleSDGothicNeo_Medium = "AppleSDGothicNeo-Medium" case Thonburi = "Thonburi" case Thonburi_Light = "Thonburi-Light" case Thonburi_Bold = "Thonburi-Bold" case GillSans_Italic = "GillSans-Italic" case GillSans_SemiBold = "GillSans-SemiBold" case GillSans_UltraBold = "GillSans-UltraBold" case GillSans_Light = "GillSans-Light" case GillSans_Bold = "GillSans-Bold" case GillSans = "GillSans" case GillSans_SemiBoldItalic = "GillSans-SemiBoldItalic" case GillSans_BoldItalic = "GillSans-BoldItalic" case GillSans_LightItalic = "GillSans-LightItalic" case MarkerFelt_Thin = "MarkerFelt-Thin" case MarkerFelt_Wide = "MarkerFelt-Wide" case HiraMaruProN_W4 = "HiraMaruProN-W4" case CourierNewPS_ItalicMT = "CourierNewPS-ItalicMT" case CourierNewPSMT = "CourierNewPSMT" case CourierNewPS_BoldItalicMT = "CourierNewPS-BoldItalicMT" case CourierNewPS_BoldMT = "CourierNewPS-BoldMT" case KohinoorTelugu_Regular = "KohinoorTelugu-Regular" case KohinoorTelugu_Medium = "KohinoorTelugu-Medium" case KohinoorTelugu_Light = "KohinoorTelugu-Light" case AvenirNextCondensed_Heavy = "AvenirNextCondensed-Heavy" case AvenirNextCondensed_MediumItalic = "AvenirNextCondensed-MediumItalic" case AvenirNextCondensed_Regular = "AvenirNextCondensed-Regular" case AvenirNextCondensed_UltraLightItalic = "AvenirNextCondensed-UltraLightItalic" case AvenirNextCondensed_Medium = "AvenirNextCondensed-Medium" case AvenirNextCondensed_HeavyItalic = "AvenirNextCondensed-HeavyItalic" case AvenirNextCondensed_DemiBoldItalic = "AvenirNextCondensed-DemiBoldItalic" case AvenirNextCondensed_Bold = "AvenirNextCondensed-Bold" case AvenirNextCondensed_DemiBold = "AvenirNextCondensed-DemiBold" case AvenirNextCondensed_BoldItalic = "AvenirNextCondensed-BoldItalic" case AvenirNextCondensed_Italic = "AvenirNextCondensed-Italic" case AvenirNextCondensed_UltraLight = "AvenirNextCondensed-UltraLight" case TamilSangamMN = "TamilSangamMN" case TamilSangamMN_Bold = "TamilSangamMN-Bold" case HelveticaNeue_UltraLightItalic = "HelveticaNeue-UltraLightItalic" case HelveticaNeue_Medium = "HelveticaNeue-Medium" case HelveticaNeue_MediumItalic = "HelveticaNeue-MediumItalic" case HelveticaNeue_UltraLight = "HelveticaNeue-UltraLight" case HelveticaNeue_Italic = "HelveticaNeue-Italic" case HelveticaNeue_Light = "HelveticaNeue-Light" case HelveticaNeue_ThinItalic = "HelveticaNeue-ThinItalic" case HelveticaNeue_LightItalic = "HelveticaNeue-LightItalic" case HelveticaNeue_Bold = "HelveticaNeue-Bold" case HelveticaNeue_Thin = "HelveticaNeue-Thin" case HelveticaNeue_CondensedBlack = "HelveticaNeue-CondensedBlack" case HelveticaNeue = "HelveticaNeue" case HelveticaNeue_CondensedBold = "HelveticaNeue-CondensedBold" case HelveticaNeue_BoldItalic = "HelveticaNeue-BoldItalic" case GurmukhiMN_Bold = "GurmukhiMN-Bold" case GurmukhiMN = "GurmukhiMN" case Georgia_BoldItalic = "Georgia-BoldItalic" case Georgia_Italic = "Georgia-Italic" case Georgia = "Georgia" case Georgia_Bold = "Georgia-Bold" case TimesNewRomanPS_ItalicMT = "TimesNewRomanPS-ItalicMT" case TimesNewRomanPS_BoldItalicMT = "TimesNewRomanPS-BoldItalicMT" case TimesNewRomanPS_BoldMT = "TimesNewRomanPS-BoldMT" case TimesNewRomanPSMT = "TimesNewRomanPSMT" case SinhalaSangamMN_Bold = "SinhalaSangamMN-Bold" case SinhalaSangamMN = "SinhalaSangamMN" case ArialRoundedMTBold = "ArialRoundedMTBold" case Kailasa_Bold = "Kailasa-Bold" case Kailasa = "Kailasa" case KohinoorDevanagari_Regular = "KohinoorDevanagari-Regular" case KohinoorDevanagari_Light = "KohinoorDevanagari-Light" case KohinoorDevanagari_Semibold = "KohinoorDevanagari-Semibold" case KohinoorBangla_Regular = "KohinoorBangla-Regular" case KohinoorBangla_Semibold = "KohinoorBangla-Semibold" case KohinoorBangla_Light = "KohinoorBangla-Light" case ChalkboardSE_Bold = "ChalkboardSE-Bold" case ChalkboardSE_Light = "ChalkboardSE-Light" case ChalkboardSE_Regular = "ChalkboardSE-Regular" case AppleColorEmoji = "AppleColorEmoji" case PingFangTC_Regular = "PingFangTC-Regular" case PingFangTC_Thin = "PingFangTC-Thin" case PingFangTC_Medium = "PingFangTC-Medium" case PingFangTC_Semibold = "PingFangTC-Semibold" case PingFangTC_Light = "PingFangTC-Light" case PingFangTC_Ultralight = "PingFangTC-Ultralight" case GujaratiSangamMN = "GujaratiSangamMN" case GujaratiSangamMN_Bold = "GujaratiSangamMN-Bold" case GeezaPro_Bold = "GeezaPro-Bold" case GeezaPro = "GeezaPro" case DamascusBold = "DamascusBold" case DamascusLight = "DamascusLight" case Damascus = "Damascus" case DamascusMedium = "DamascusMedium" case DamascusSemiBold = "DamascusSemiBold" case Noteworthy_Bold = "Noteworthy-Bold" case Noteworthy_Light = "Noteworthy-Light" case Avenir_Oblique = "Avenir-Oblique" case Avenir_HeavyOblique = "Avenir-HeavyOblique" case Avenir_Heavy = "Avenir-Heavy" case Avenir_BlackOblique = "Avenir-BlackOblique" case Avenir_BookOblique = "Avenir-BookOblique" case Avenir_Roman = "Avenir-Roman" case Avenir_Medium = "Avenir-Medium" case Avenir_Black = "Avenir-Black" case Avenir_Light = "Avenir-Light" case Avenir_MediumOblique = "Avenir-MediumOblique" case Avenir_Book = "Avenir-Book" case Avenir_LightOblique = "Avenir-LightOblique" case DiwanMishafi = "DiwanMishafi" case AcademyEngravedLetPlain = "AcademyEngravedLetPlain" case Futura_CondensedExtraBold = "Futura-CondensedExtraBold" case Futura_Medium = "Futura-Medium" case Futura_Bold = "Futura-Bold" case Futura_CondensedMedium = "Futura-CondensedMedium" case Futura_MediumItalic = "Futura-MediumItalic" case PartyLetPlain = "PartyLetPlain" case KannadaSangamMN_Bold = "KannadaSangamMN-Bold" case KannadaSangamMN = "KannadaSangamMN" case ArialHebrew_Bold = "ArialHebrew-Bold" case ArialHebrew_Light = "ArialHebrew-Light" case ArialHebrew = "ArialHebrew" case Farah = "Farah" case Arial_BoldMT = "Arial-BoldMT" case Arial_BoldItalicMT = "Arial-BoldItalicMT" case Arial_ItalicMT = "Arial-ItalicMT" case ArialMT = "ArialMT" case Chalkduster = "Chalkduster" case Kefa_Regular = "Kefa-Regular" case HoeflerText_Italic = "HoeflerText-Italic" case HoeflerText_Black = "HoeflerText-Black" case HoeflerText_Regular = "HoeflerText-Regular" case HoeflerText_BlackItalic = "HoeflerText-BlackItalic" case Optima_ExtraBlack = "Optima-ExtraBlack" case Optima_BoldItalic = "Optima-BoldItalic" case Optima_Italic = "Optima-Italic" case Optima_Regular = "Optima-Regular" case Optima_Bold = "Optima-Bold" case Palatino_Italic = "Palatino-Italic" case Palatino_Roman = "Palatino-Roman" case Palatino_BoldItalic = "Palatino-BoldItalic" case Palatino_Bold = "Palatino-Bold" case MalayalamSangamMN_Bold = "MalayalamSangamMN-Bold" case MalayalamSangamMN = "MalayalamSangamMN" case AlNile = "AlNile" case AlNile_Bold = "AlNile-Bold" case LaoSangamMN = "LaoSangamMN" case BradleyHandITCTT_Bold = "BradleyHandITCTT-Bold" case HiraMinProN_W3 = "HiraMinProN-W3" case HiraMinProN_W6 = "HiraMinProN-W6" case PingFangHK_Medium = "PingFangHK-Medium" case PingFangHK_Thin = "PingFangHK-Thin" case PingFangHK_Regular = "PingFangHK-Regular" case PingFangHK_Ultralight = "PingFangHK-Ultralight" case PingFangHK_Semibold = "PingFangHK-Semibold" case PingFangHK_Light = "PingFangHK-Light" case Helvetica_Oblique = "Helvetica-Oblique" case Helvetica_BoldOblique = "Helvetica-BoldOblique" case Helvetica = "Helvetica" case Helvetica_Light = "Helvetica-Light" case Helvetica_Bold = "Helvetica-Bold" case Helvetica_LightOblique = "Helvetica-LightOblique" case Courier_BoldOblique = "Courier-BoldOblique" case Courier_Oblique = "Courier-Oblique" case Courier = "Courier" case Courier_Bold = "Courier-Bold" case Cochin_Italic = "Cochin-Italic" case Cochin_Bold = "Cochin-Bold" case Cochin = "Cochin" case Cochin_BoldItalic = "Cochin-BoldItalic" case TrebuchetMS_Bold = "TrebuchetMS-Bold" case TrebuchetMS_Italic = "TrebuchetMS-Italic" case Trebuchet_BoldItalic = "Trebuchet-BoldItalic" case TrebuchetMS = "TrebuchetMS" case DevanagariSangamMN = "DevanagariSangamMN" case DevanagariSangamMN_Bold = "DevanagariSangamMN-Bold" case OriyaSangamMN = "OriyaSangamMN" case OriyaSangamMN_Bold = "OriyaSangamMN-Bold" case SnellRoundhand = "SnellRoundhand" case SnellRoundhand_Bold = "SnellRoundhand-Bold" case SnellRoundhand_Black = "SnellRoundhand-Black" case ZapfDingbatsITC = "ZapfDingbatsITC" case BodoniSvtyTwoITCTT_Bold = "BodoniSvtyTwoITCTT-Bold" case BodoniSvtyTwoITCTT_BookIta = "BodoniSvtyTwoITCTT-BookIta" case BodoniSvtyTwoITCTT_Book = "BodoniSvtyTwoITCTT-Book" case Verdana_Italic = "Verdana-Italic" case Verdana = "Verdana" case Verdana_Bold = "Verdana-Bold" case Verdana_BoldItalic = "Verdana-BoldItalic" case AmericanTypewriter_CondensedBold = "AmericanTypewriter-CondensedBold" case AmericanTypewriter_Condensed = "AmericanTypewriter-Condensed" case AmericanTypewriter_CondensedLight = "AmericanTypewriter-CondensedLight" case AmericanTypewriter = "AmericanTypewriter" case AmericanTypewriter_Bold = "AmericanTypewriter-Bold" case AmericanTypewriter_Semibold = "AmericanTypewriter-Semibold" case AmericanTypewriter_Light = "AmericanTypewriter-Light" case AvenirNext_Medium = "AvenirNext-Medium" case AvenirNext_DemiBoldItalic = "AvenirNext-DemiBoldItalic" case AvenirNext_DemiBold = "AvenirNext-DemiBold" case AvenirNext_HeavyItalic = "AvenirNext-HeavyItalic" case AvenirNext_Regular = "AvenirNext-Regular" case AvenirNext_Italic = "AvenirNext-Italic" case AvenirNext_MediumItalic = "AvenirNext-MediumItalic" case AvenirNext_UltraLightItalic = "AvenirNext-UltraLightItalic" case AvenirNext_BoldItalic = "AvenirNext-BoldItalic" case AvenirNext_Heavy = "AvenirNext-Heavy" case AvenirNext_Bold = "AvenirNext-Bold" case AvenirNext_UltraLight = "AvenirNext-UltraLight" case Baskerville_SemiBoldItalic = "Baskerville-SemiBoldItalic" case Baskerville_SemiBold = "Baskerville-SemiBold" case Baskerville_BoldItalic = "Baskerville-BoldItalic" case Baskerville = "Baskerville" case Baskerville_Bold = "Baskerville-Bold" case Baskerville_Italic = "Baskerville-Italic" case KhmerSangamMN = "KhmerSangamMN" case Didot_Bold = "Didot-Bold" case Didot = "Didot" case Didot_Italic = "Didot-Italic" case SavoyeLetPlain = "SavoyeLetPlain" case BodoniOrnamentsITCTT = "BodoniOrnamentsITCTT" case Symbol = "Symbol" case Menlo_BoldItalic = "Menlo-BoldItalic" case Menlo_Bold = "Menlo-Bold" case Menlo_Italic = "Menlo-Italic" case Menlo_Regular = "Menlo-Regular" case NotoNastaliqUrdu = "NotoNastaliqUrdu" case BodoniSvtyTwoSCITCTT_Book = "BodoniSvtyTwoSCITCTT-Book" case Papyrus_Condensed = "Papyrus-Condensed" case Papyrus = "Papyrus" case HiraginoSans_W3 = "HiraginoSans-W3" case HiraginoSans_W6 = "HiraginoSans-W6" case PingFangSC_Medium = "PingFangSC-Medium" case PingFangSC_Semibold = "PingFangSC-Semibold" case PingFangSC_Light = "PingFangSC-Light" case PingFangSC_Ultralight = "PingFangSC-Ultralight" case PingFangSC_Regular = "PingFangSC-Regular" case PingFangSC_Thin = "PingFangSC-Thin" case MyanmarSangamMN = "MyanmarSangamMN" case MyanmarSangamMN_Bold = "MyanmarSangamMN-Bold" case Zapfino = "Zapfino" case BodoniSvtyTwoOSITCTT_BookIt = "BodoniSvtyTwoOSITCTT-BookIt" case BodoniSvtyTwoOSITCTT_Book = "BodoniSvtyTwoOSITCTT-Book" case BodoniSvtyTwoOSITCTT_Bold = "BodoniSvtyTwoOSITCTT-Bold" case EuphemiaUCAS = "EuphemiaUCAS" case EuphemiaUCAS_Italic = "EuphemiaUCAS-Italic" case EuphemiaUCAS_Bold = "EuphemiaUCAS-Bold" // added by hand case HiraKakuProN_W6 = "HiraKakuProN-W6" case HiraKakuProN_W3 = "HiraKakuProN-W3" }
mit
14dbbf290aed5ecc4c4ac2546033e5a3
47.698305
87
0.745789
4.170102
false
false
false
false
material-components/material-components-ios
components/Buttons/examples/FloatingButtonTypicalUseSwiftExample.swift
2
7067
// Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import MaterialComponents.MaterialButtons import MaterialComponents.MaterialButtons_Theming import MaterialComponents.MaterialContainerScheme class FloatingButtonTypicalUseSwiftExample: UIViewController { let miniFloatingButton = MDCFloatingButton(frame: .zero, shape: .mini) let defaultFloatingButton = MDCFloatingButton() let largeIconFloatingButton = MDCFloatingButton() var containerScheme = MDCContainerScheme() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.9, alpha: 1) let plusImage = UIImage(named: "system_icons/add") let plusImage36 = UIImage(named: "system_icons/add_36pt") miniFloatingButton.sizeToFit() miniFloatingButton.translatesAutoresizingMaskIntoConstraints = false miniFloatingButton.setMinimumSize(CGSize(width: 96, height: 40), for: .mini, in: .expanded) miniFloatingButton.setImage(plusImage, for: .normal) miniFloatingButton.accessibilityLabel = "Create" miniFloatingButton.applySecondaryTheme(withScheme: containerScheme) defaultFloatingButton.sizeToFit() defaultFloatingButton.translatesAutoresizingMaskIntoConstraints = false defaultFloatingButton.setImage(plusImage, for: .normal) defaultFloatingButton.accessibilityLabel = "Create" defaultFloatingButton.applySecondaryTheme(withScheme: containerScheme) largeIconFloatingButton.sizeToFit() largeIconFloatingButton.translatesAutoresizingMaskIntoConstraints = false largeIconFloatingButton.setImage(plusImage36, for: .normal) largeIconFloatingButton.accessibilityLabel = "Create" largeIconFloatingButton.setContentEdgeInsets( UIEdgeInsets(top: -6, left: -6, bottom: -6, right: 0), for: .default, in: .expanded) largeIconFloatingButton.applySecondaryTheme(withScheme: containerScheme) let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Try me on an iPad!" view.addSubview(label) view.addSubview(miniFloatingButton) view.addSubview(defaultFloatingButton) view.addSubview(largeIconFloatingButton) let totalHeight = miniFloatingButton.bounds.standardized.height + defaultFloatingButton.bounds.standardized.height + largeIconFloatingButton.bounds.standardized.height + 20 // 10 points between buttons let miniDefaultDifference = defaultFloatingButton.bounds.standardized.width - miniFloatingButton.bounds.standardized.width leadingAlignView( view: miniFloatingButton, onView: self.view, horizontalOffset: 10 + miniDefaultDifference / 2, verticalOffset: -totalHeight / 2) leadingAlignView( view: defaultFloatingButton, onView: miniFloatingButton, horizontalOffset: -miniDefaultDifference / 2, verticalOffset: defaultFloatingButton.bounds.standardized.height + 10) leadingAlignView( view: largeIconFloatingButton, onView: defaultFloatingButton, horizontalOffset: 0, verticalOffset: defaultFloatingButton.bounds.standardized.height + 10) self.view.addConstraint( NSLayoutConstraint( item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)) self.view.addConstraint( NSLayoutConstraint( item: label, attribute: .bottom, relatedBy: .equal, toItem: miniFloatingButton, attribute: .top, multiplier: 1, constant: -20)) } // MARK: Private private func leadingAlignView( view: UIView, onView: UIView, horizontalOffset: CGFloat, verticalOffset: CGFloat ) { self.view.addConstraint( NSLayoutConstraint( item: view, attribute: .leading, relatedBy: .equal, toItem: onView, attribute: .leading, multiplier: 1.0, constant: horizontalOffset)) self.view.addConstraint( NSLayoutConstraint( item: view, attribute: .centerY, relatedBy: .equal, toItem: onView, attribute: .centerY, multiplier: 1.0, constant: verticalOffset)) } } extension FloatingButtonTypicalUseSwiftExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Buttons", "Floating Action Button (Swift)"], "primaryDemo": false, "presentable": false, ] } } extension FloatingButtonTypicalUseSwiftExample { func updateFloatingButtons(to mode: MDCFloatingButtonMode) { if miniFloatingButton.mode != mode { miniFloatingButton.mode = mode } if defaultFloatingButton.mode != mode { defaultFloatingButton.mode = mode } if largeIconFloatingButton.mode != mode { largeIconFloatingButton.mode = mode } } func updateFloatingButtons(whenSizeClass isRegularRegular: Bool) { if isRegularRegular { updateFloatingButtons(to: .expanded) miniFloatingButton.setTitle("Add", for: .normal) defaultFloatingButton.setTitle("Create", for: .normal) largeIconFloatingButton.setTitle("Create", for: .normal) } else { updateFloatingButtons(to: .normal) miniFloatingButton.setTitle(nil, for: .normal) defaultFloatingButton.setTitle(nil, for: .normal) largeIconFloatingButton.setTitle(nil, for: .normal) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let horizontalSizeClass = traitCollection.horizontalSizeClass let verticalSizeClass = traitCollection.verticalSizeClass let isRegularRegular = horizontalSizeClass == .regular && verticalSizeClass == .regular updateFloatingButtons(whenSizeClass: isRegularRegular) } override func willTransition( to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator ) { super.willTransition(to: newCollection, with: coordinator) let currentTraits = traitCollection let sizeClassChanged = newCollection.horizontalSizeClass != currentTraits.horizontalSizeClass || newCollection.verticalSizeClass != currentTraits.verticalSizeClass if sizeClassChanged { let willBeRegularRegular = newCollection.horizontalSizeClass == .regular && newCollection.verticalSizeClass == .regular coordinator.animate( alongsideTransition: { (_) in self.updateFloatingButtons(whenSizeClass: willBeRegularRegular) }, completion: nil) } } }
apache-2.0
3e594bd7f2c529c449f3c1b23edfa19e
36
100
0.734824
4.997878
false
false
false
false
everald/JetPack
Sources/UI/z_ImageView+UrlSource.swift
1
9827
// File name prefixed with z_ to avoid compiler crash related to type extensions, nested types and order of Swift source files. import ImageIO import UIKit public extension ImageView { public struct UrlSource: ImageView.Source, Equatable { public var considersOptimalImageSize = true public var isTemplate: Bool public var placeholder: UIImage? public var url: URL public init(url: URL, isTemplate: Bool = false, placeholder: UIImage? = nil) { self.isTemplate = isTemplate self.placeholder = placeholder self.url = url } public static func cachedImageForUrl(_ url: URL) -> UIImage? { return ImageCache.sharedInstance.imageForKey(url as AnyObject) } public func createSession() -> ImageView.Session? { return UrlSourceSession(source: self) } public static func preload(url: URL) { _ = ImageDownloader.forUrl(url).download { _ in } } } } public func == (a: ImageView.UrlSource, b: ImageView.UrlSource) -> Bool { return a.url == b.url && a.isTemplate == b.isTemplate } private final class UrlSourceSession: ImageView.Session { fileprivate let source: ImageView.UrlSource fileprivate var stopLoading: Closure? fileprivate init(source: ImageView.UrlSource) { self.source = source } fileprivate func imageViewDidChangeConfiguration(_ imageView: ImageView) { // ignore } fileprivate func startRetrievingImageForImageView(_ imageView: ImageView, listener: ImageView.SessionListener) { precondition(stopLoading == nil) var isLoadingImage = true func completion(image sourceImage: UIImage) { isLoadingImage = false var image = sourceImage if self.source.isTemplate { image = image.withRenderingMode(.alwaysTemplate) } listener.sessionDidRetrieveImage(image) } if source.url.isFileURL && source.considersOptimalImageSize { let optimalImageSize = imageView.optimalImageSize.scaleBy(imageView.optimalImageScale) stopLoading = ImageFileLoader.forUrl(source.url, size: max(optimalImageSize.width, optimalImageSize.height)).load(completion) } else { stopLoading = ImageDownloader.forUrl(source.url).download(completion) } if isLoadingImage, let placeholder = source.placeholder { listener.sessionDidRetrieveImage(placeholder) } } fileprivate func stopRetrievingImage() { guard let stopLoading = stopLoading else { return } self.stopLoading = nil stopLoading() } } private final class ImageCache { fileprivate let cache = NSCache<AnyObject, AnyObject>() fileprivate init() {} fileprivate func costForImage(_ image: UIImage) -> Int { guard let cgImage = image.cgImage else { return 0 } // TODO does CGImageGetHeight() include the scale? return cgImage.bytesPerRow * cgImage.height } fileprivate func imageForKey(_ key: AnyObject) -> UIImage? { return cache.object(forKey: key) as? UIImage } fileprivate func setImage(_ image: UIImage, forKey key: AnyObject) { cache.setObject(image, forKey: key, cost: costForImage(image)) } fileprivate static let sharedInstance = ImageCache() } private class ImageDownloader { fileprivate typealias Completion = (UIImage) -> Void fileprivate static var downloaders = [URL : ImageDownloader]() fileprivate var completions = [Int : Completion]() fileprivate var image: UIImage? fileprivate var nextId = 0 fileprivate var task: URLSessionDataTask? fileprivate let url: URL fileprivate init(url: URL) { self.url = url } fileprivate func cancelCompletionWithId(_ id: Int) { completions[id] = nil if completions.isEmpty { onMainQueue { // wait one cycle. maybe someone canceled just to retry immediately if self.completions.isEmpty { self.cancelDownload() } } } } fileprivate func cancelDownload() { precondition(completions.isEmpty) task?.cancel() task = nil } fileprivate func download(_ completion: @escaping Completion) -> CancelClosure { if let image = image { completion(image) return {} } if let image = ImageCache.sharedInstance.imageForKey(url as AnyObject) { self.image = image runAllCompletions() cancelDownload() completion(image) return {} } let id = nextId nextId += 1 completions[id] = completion startDownload() return { self.cancelCompletionWithId(id) } } fileprivate static func forUrl(_ url: URL) -> ImageDownloader { if let downloader = downloaders[url] { return downloader } let downloader = ImageDownloader(url: url) downloaders[url] = downloader return downloader } fileprivate func runAllCompletions() { guard let image = image else { fatalError("Cannot run completions unless an image was successfully loaded") } // careful: a completion might get removed while we're calling another one so don't copy the dictionary while let (id, completion) = self.completions.first { self.completions.removeValue(forKey: id) completion(image) } ImageDownloader.downloaders[url] = nil } fileprivate func startDownload() { precondition(image == nil) precondition(!completions.isEmpty) guard self.task == nil else { return } let url = self.url let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in guard let data = data, let image = UIImage(data: data) else { onMainQueue { self.task = nil } var failureReason: String if let error = error { failureReason = "\(error)" } else { failureReason = "server returned invalid response or image could not be parsed" } log("Cannot load image '\(url)': \(failureReason)") // TODO retry, handle 4xx, etc. return } image.inflate() // TODO doesn't UIImage(data:) already inflate the image? onMainQueue { self.task = nil self.image = image ImageCache.sharedInstance.setImage(image, forKey: url as AnyObject) self.runAllCompletions() } }) self.task = task task.resume() } } private final class ImageFileLoader { fileprivate typealias Completion = (UIImage) -> Void fileprivate static var loaders = [Query : ImageFileLoader]() fileprivate static let operationQueue = OperationQueue() fileprivate var completions = [Int : Completion]() fileprivate var image: UIImage? fileprivate var nextId = 0 fileprivate var operation: Operation? fileprivate let query: Query fileprivate init(query: Query) { self.query = query } fileprivate func cancelCompletionWithId(_ id: Int) { completions[id] = nil if completions.isEmpty { onMainQueue { // wait one cycle. maybe someone canceled just to retry immediately if self.completions.isEmpty { self.cancelOperation() } } } } fileprivate func cancelOperation() { precondition(completions.isEmpty) operation?.cancel() operation = nil } fileprivate func load(_ completion: @escaping Completion) -> CancelClosure { if let image = image { completion(image) return {} } if let image = ImageCache.sharedInstance.imageForKey(query) { self.image = image runAllCompletions() cancelOperation() completion(image) return {} } let id = nextId nextId += 1 completions[id] = completion startOperation() return { self.cancelCompletionWithId(id) } } fileprivate static func forUrl(_ url: URL, size: CGFloat) -> ImageFileLoader { let query = Query(url: url, size: size) if let loader = loaders[query] { return loader } let loader = ImageFileLoader(query: query) loaders[query] = loader return loader } fileprivate func runAllCompletions() { guard let image = image else { fatalError("Cannot run completions unless an image was successfully loaded") } // careful: a completion might get removed while we're calling another one so don't copy the dictionary while let (id, completion) = self.completions.first { self.completions.removeValue(forKey: id) completion(image) } ImageFileLoader.loaders[query] = nil } fileprivate func startOperation() { precondition(image == nil) precondition(!completions.isEmpty) guard self.operation == nil else { return } let query = self.query let size = query.size let url = query.url let operation = BlockOperation() { var image: UIImage? defer { onMainQueue { self.operation = nil self.image = image guard let image = image else { return } ImageCache.sharedInstance.setImage(image, forKey: query) self.runAllCompletions() } } guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { log("Cannot load image '\(url)': Cannot create image source") return } let options: [AnyHashable: Any] = [ kCGImageSourceCreateThumbnailFromImageAlways as AnyHashable: kCFBooleanTrue, kCGImageSourceCreateThumbnailWithTransform as AnyHashable: kCFBooleanTrue, kCGImageSourceThumbnailMaxPixelSize as AnyHashable: size ] guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary?) else { log("Cannot load image '\(url)': Cannot create thumbnail from image source") return } image = UIImage(cgImage: cgImage) image?.inflate() } self.operation = operation ImageFileLoader.operationQueue.addOperation(operation) } fileprivate final class Query: NSObject { fileprivate let size: CGFloat fileprivate let url: URL fileprivate init(url: URL, size: CGFloat) { self.size = size self.url = url } fileprivate override func copy() -> Any { return self } fileprivate override var hash: Int { return url.hashValue ^ size.hashValue } fileprivate override func isEqual(_ object: Any?) -> Bool { guard let query = object as? Query else { return false } return url == query.url && size == query.size } } }
mit
7673f40b9dbc90aabfad17d54d85e45a
20.178879
128
0.7052
3.968901
false
false
false
false
apple/swift
test/Constraints/members.swift
4
26244
// RUN: %target-typecheck-verify-swift -swift-version 5 //// // Members of structs //// struct X { func f0(_ i: Int) -> X { } func f1(_ i: Int) { } mutating func f1(_ f: Float) { } func f2<T>(_ x: T) -> T { } } struct Y<T> { func f0(_: T) -> T {} func f1<U>(_ x: U, y: T) -> (T, U) {} } var i : Int var x : X var yf : Y<Float> func g0(_: (inout X) -> (Float) -> ()) {} _ = x.f0(i) x.f0(i).f1(i) g0(X.f1) // expected-error{{cannot reference 'mutating' method as function value}} _ = x.f0(x.f2(1)) _ = x.f0(1).f2(i) _ = yf.f0(1) _ = yf.f1(i, y: 1) // Members referenced from inside the struct struct Z { var i : Int func getI() -> Int { return i } mutating func incI() {} func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } } subscript (k : Int) -> Int { get { return i + k } mutating set { i -= k } } } struct GZ<T> { var i : T func getI() -> T { return i } func f1<U>(_ a: T, b: U) -> (T, U) { return (a, b) } func f2() { var f : Float var t = f1(i, b: f) f = t.1 var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}} var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}} } } var z = Z(i: 0) var getI = z.getI var incI = z.incI // expected-error{{cannot reference 'mutating' method as function value}} var zi = z.getI() var zcurried1 = z.curried var zcurried2 = z.curried(0) var zcurriedFull = z.curried(0)(1) //// // Members of modules //// // Module Swift.print(3, terminator: "") //// // Unqualified references //// //// // Members of literals //// // FIXME: Crappy diagnostic "foo".lower() // expected-error{{value of type 'String' has no member 'lower'}} var tmp = "foo".debugDescription //// // Members of enums //// enum W { case Omega func foo(_ x: Int) {} func curried(_ x: Int) -> (Int) -> () {} } var w = W.Omega var foo = w.foo var fooFull : () = w.foo(0) var wcurried1 = w.curried var wcurried2 = w.curried(0) var wcurriedFull : () = w.curried(0)(1) // Member of enum type func enumMetatypeMember(_ opt: Int?) { opt.none // expected-error{{enum case 'none' cannot be used as an instance member}} } //// // Nested types //// // Reference a Type member. <rdar://problem/15034920> class G<T> { class In { class func foo() {} } } func goo() { G<Int>.In.foo() } //// // Misc ambiguities //// // <rdar://problem/15537772> struct DefaultArgs { static func f(_ a: Int = 0) -> DefaultArgs { return DefaultArgs() } init() { self = .f() } } class InstanceOrClassMethod { func method() -> Bool { return true } class func method(_ other: InstanceOrClassMethod) -> Bool { return false } } func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) { let result = InstanceOrClassMethod.method(obj) let _: Bool = result // no-warning let _: () -> Bool = InstanceOrClassMethod.method(obj) } protocol Numeric { static func +(x: Self, y: Self) -> Self } func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { } func testNumeric<T : Numeric>(_ x: T) { acceptBinaryFunc(x, +) } /* FIXME: We can't check this directly, but it can happen with multiple modules. class PropertyOrMethod { func member() -> Int { return 0 } let member = false class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 } let methodOnClass = false } func testPreferPropertyToMethod(_ obj: PropertyOrMethod) { let result = obj.member let resultChecked: Bool = result let called = obj.member() let calledChecked: Int = called let curried = obj.member as () -> Int let methodOnClass = PropertyOrMethod.methodOnClass let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass } */ struct Foo { var foo: Int } protocol ExtendedWithMutatingMethods { } extension ExtendedWithMutatingMethods { mutating func mutatingMethod() {} var mutableProperty: Foo { get { } set { } } var nonmutatingProperty: Foo { get { } nonmutating set { } } var mutatingGetProperty: Foo { mutating get { } set { } } } class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {} class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {} func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}} sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}} c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}} c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}} c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}} c.nonmutatingProperty = Foo(foo: 0) c.nonmutatingProperty.foo = 0 c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}} c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}} _ = c.mutableProperty _ = c.mutableProperty.foo _ = c.nonmutatingProperty _ = c.nonmutatingProperty.foo // FIXME: diagnostic nondeterministically says "member" or "getter" _ = c.mutatingGetProperty // expected-error{{cannot use mutating}} _ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}} sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}} sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}} sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}} sub.nonmutatingProperty = Foo(foo: 0) sub.nonmutatingProperty.foo = 0 sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}} sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}} _ = sub.mutableProperty _ = sub.mutableProperty.foo _ = sub.nonmutatingProperty _ = sub.nonmutatingProperty.foo _ = sub.mutatingGetProperty // expected-error{{cannot use mutating}} _ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}} var mutableC = c mutableC.mutatingMethod() mutableC.mutableProperty = Foo(foo: 0) mutableC.mutableProperty.foo = 0 mutableC.nonmutatingProperty = Foo(foo: 0) mutableC.nonmutatingProperty.foo = 0 mutableC.mutatingGetProperty = Foo(foo: 0) mutableC.mutatingGetProperty.foo = 0 _ = mutableC.mutableProperty _ = mutableC.mutableProperty.foo _ = mutableC.nonmutatingProperty _ = mutableC.nonmutatingProperty.foo _ = mutableC.mutatingGetProperty _ = mutableC.mutatingGetProperty.foo var mutableSub = sub mutableSub.mutatingMethod() mutableSub.mutableProperty = Foo(foo: 0) mutableSub.mutableProperty.foo = 0 mutableSub.nonmutatingProperty = Foo(foo: 0) mutableSub.nonmutatingProperty.foo = 0 _ = mutableSub.mutableProperty _ = mutableSub.mutableProperty.foo _ = mutableSub.nonmutatingProperty _ = mutableSub.nonmutatingProperty.foo _ = mutableSub.mutatingGetProperty _ = mutableSub.mutatingGetProperty.foo } // <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad. enum LedModules: Int { case WS2811_1x_5V } extension LedModules { static var watts: Double { return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}} } } // <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic class r15117741S { static func g() {} } func test15117741(_ s: r15117741S) { s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}} } // <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous struct UnavailMember { @available(*, unavailable) static var XYZ : UnavailMember { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}} } let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}} let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}} // <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias struct S22490787 { typealias Iterator = AnyIterator<Int> } func f22490787() { var path: S22490787 = S22490787() for p in path { // expected-error {{for-in loop requires 'S22490787' to conform to 'Sequence'}} } } // <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor enum r23942743 { case Tomato(cloud: String) } let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}} // expected-error@-1 {{cannot infer contextual base in reference to member 'none'}} // https://github.com/apple/swift/issues/43267 // REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions enum SomeErrorType { case StandaloneError case UnderlyingError(String) static func someErrorFromString(_ str: String) -> SomeErrorType? { if str == "standalone" { return .StandaloneError } if str == "underlying" { return .UnderlyingError } // expected-error {{member 'UnderlyingError' expects argument of type 'String'}} return nil } } // https://github.com/apple/swift/issues/44801 // QoI: Better diagnostic when a decl exists, but is not a type do { enum E: Error { case Boom } do { throw E.Boom } catch let e as E.Boom { // expected-error {{enum case 'Boom' is not a member type of 'E'}} } } // rdar://problem/25341015 extension Sequence { func r25341015_1() -> Int { return max(1, 2) // expected-error {{use of 'max' refers to instance method rather than global function 'max' in module 'Swift'}} expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} } } class C_25341015 { static func baz(_ x: Int, _ y: Int) {} func baz() {} func qux() { baz(1, 2) // expected-error {{static member 'baz' cannot be used on instance of type 'C_25341015'}} {{5-5=C_25341015.}} } } struct S_25341015 { static func foo(_ x: Int, y: Int) {} func foo(z: Int) {} func bar() { foo(1, y: 2) // expected-error {{static member 'foo' cannot be used on instance of type 'S_25341015'}} {{5-5=S_25341015.}} } } func r25341015() { func baz(_ x: Int, _ y: Int) {} class Bar { func baz() {} func qux() { baz(1, 2) // expected-error {{use of 'baz' refers to instance method rather than local function 'baz'}} } } } func r25341015_local(x: Int, y: Int) {} func r25341015_inner() { func r25341015_local() {} r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}} } // rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely func foo_32854314() -> Double { return 42 } func bar_32854314() -> Int { return 0 } extension Array where Element == Int { func foo() { let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}} } func foo(_ x: Int, _ y: Double) { let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}} } func bar() { let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}} // expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}} } } // Crash in diagnoseImplicitSelfErrors() struct Aardvark { var snout: Int mutating func burrow() { dig(&snout, .y) // expected-error {{type 'Int' has no member 'y'}} } func dig(_: inout Int, _: Int) {} } func rdar33914444() { struct A { enum R<E: Error> { case e(E) // expected-note {{'e' declared here}} } struct S { enum E: Error { case e1 } let e: R<E> } } _ = A.S(e: .e1) // expected-error@-1 {{type 'A.R<A.S.E>' has no member 'e1'; did you mean 'e'?}} } // https://github.com/apple/swift/issues/47898 // Better diagnostic when instance member of outer type is referenced from // nested type struct Outer { var outer: Int struct Inner { var inner: Int func sum() -> Int { return inner + outer // expected-error@-1 {{instance member 'outer' of type 'Outer' cannot be used on instance of nested type 'Outer.Inner'}} } } } // rdar://problem/39514009 - don't crash when trying to diagnose members with special names print("hello")[0] // expected-error {{value of type '()' has no subscripts}} func rdar40537782() { class A {} class B : A { override init() {} func foo() -> A { return A() } } struct S<T> { init(_ a: T...) {} } func bar<T>(_ t: T) { _ = S(B(), .foo(), A()) // expected-error {{type 'A' has no member 'foo'}} } } func rdar36989788() { struct A<T> { func foo() -> A<T> { return self } } func bar<T>(_ x: A<T>) -> (A<T>, A<T>) { return (x.foo(), x.undefined()) // expected-error {{value of type 'A<T>' has no member 'undefined'}} } } func rdar46211109() { struct MyIntSequenceStruct: Sequence { struct Iterator: IteratorProtocol { var current = 0 mutating func next() -> Int? { return current + 1 } } func makeIterator() -> Iterator { return Iterator() } } func foo<E, S: Sequence>(_ type: E.Type) -> S? where S.Element == E { return nil } let _: MyIntSequenceStruct? = foo(Int.Self) // expected-error@-1 {{type 'Int' has no member 'Self'}} } class A {} enum B { static func foo() { bar(A()) // expected-error {{instance member 'bar' cannot be used on type 'B'}} } func bar(_: A) {} } class C { static func foo() { bar(0) // expected-error {{instance member 'bar' cannot be used on type 'C'}} } func bar(_: Int) {} } class D { static func foo() {} func bar() { foo() // expected-error {{static member 'foo' cannot be used on instance of type 'D'}} } } func rdar_48114578() { struct S<T> { var value: T static func valueOf<T>(_ v: T) -> S<T> { return S<T>(value: v) } } typealias A = (a: [String]?, b: Int) func foo(_ a: [String], _ b: Int) -> S<A> { let v = (a, b) return .valueOf(v) } func bar(_ a: [String], _ b: Int) -> S<A> { return .valueOf((a, b)) // Ok } } struct S_Min { var xmin: Int = 42 } func xmin(_: Int, _: Float) -> Int { return 0 } func xmin(_: Float, _: Int) -> Int { return 0 } extension S_Min : CustomStringConvertible { public var description: String { return "\(xmin)" // Ok } } // rdar://problem/50679161 func rdar50679161() { struct Point {} struct S { var w, h: Point } struct Q { init(a: Int, b: Int) {} init(a: Point, b: Point) {} } func foo() { _ = { () -> Void in // Missing `.self` or `init` is not diagnosed here because there are errors in // `if let` statement and `MiscDiagnostics` only run if the body is completely valid. var foo = S if let v = Int?(1) { var _ = Q( a: v + foo.w, // expected-error@-1 {{instance member 'w' cannot be used on type 'S'}} // expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}} b: v + foo.h // expected-error@-1 {{instance member 'h' cannot be used on type 'S'}} // expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}} ) } } _ = { () -> Void in var foo = S // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} print(foo) } } } func rdar_50467583_and_50909555() { if #available(macOS 11.3, iOS 14.5, tvOS 14.5, watchOS 7.4, *) { // rdar://problem/50467583 let _: Set = [Int][] // expected-error {{no 'subscript' candidates produce the expected contextual result type 'Set'}} // expected-error@-1 {{no exact matches in call to subscript}} // expected-note@-2 {{found candidate with type '(Int) -> Int'}} // expected-note@-3 {{found candidate with type '(Range<Int>) -> ArraySlice<Int>'}} // expected-note@-4 {{found candidate with type '((UnboundedRange_) -> ()) -> ArraySlice<Int>'}} } // rdar://problem/50909555 struct S { static subscript(x: Int, y: Int) -> Int { // expected-note {{'subscript(_:_:)' declared here}} return 1 } } func test(_ s: S) { s[1] // expected-error {{static member 'subscript' cannot be used on instance of type 'S'}} {{5-6=S}} // expected-error@-1 {{missing argument for parameter #2 in call}} {{8-8=, <#Int#>}} } } // rdar://problem/46427500 // https://github.com/apple/swift/issues/51862 // Nonsensical error message related to constrained extensions struct S_51862<A, B> {} extension S_51862 where A == Bool { // expected-note {{where 'A' = 'Int'}} func foo() {} } func test_51862(_ s: S_51862<Int, Double>) { s.foo() // expected-error {{referencing instance method 'foo()' on 'S_51862' requires the types 'Int' and 'Bool' be equivalent}} } // rdar://problem/34770265 - Better diagnostic needed for constrained extension method call extension Dictionary where Key == String { // expected-note {{where 'Key' = 'Int'}} func rdar_34770265_key() {} } extension Dictionary where Value == String { // expected-note {{where 'Value' = 'Int'}} func rdar_34770265_val() {} } func test_34770265(_ dict: [Int: Int]) { dict.rdar_34770265_key() // expected-error@-1 {{referencing instance method 'rdar_34770265_key()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}} dict.rdar_34770265_val() // expected-error@-1 {{referencing instance method 'rdar_34770265_val()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}} } // https://github.com/apple/swift/issues/55116 _ = [.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}} let _ : [Any] = [.e] // expected-error {{type 'Any' has no member 'e'}} _ = [1 :.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}} _ = [.e: 1] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}} let _ : [Int: Any] = [1 : .e] // expected-error {{type 'Any' has no member 'e'}} let _ : (Int, Any) = (1, .e) // expected-error {{type 'Any' has no member 'e'}} _ = (1, .e) // expected-error {{cannot infer contextual base in reference to member 'e'}} // https://github.com/apple/swift/issues/55799 typealias Pair = (Int, Int) func test_55799(_ pair: (Int, Int), _ alias: Pair, _ void: Void, labeled: (a: Int, b: Int)) { _ = pair[0] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; did you mean to use '.0'?}} {{11-14=.0}} _ = pair[1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; did you mean to use '.1'?}} {{11-14=.1}} _ = pair[2] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}} _ = pair[100] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}} _ = pair["string"] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}} _ = pair[-1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}} _ = pair[1, 1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}} _ = void[0] // expected-error {{value of type 'Void' has no subscripts}} // Other representations of literals _ = pair[0x00] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}} _ = pair[0b00] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}} _ = alias[0] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); did you mean to use '.0'?}} {{12-15=.0}} _ = alias[1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); did you mean to use '.1'?}} {{12-15=.1}} _ = alias[2] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}} _ = alias[100] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}} _ = alias["string"] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}} _ = alias[-1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}} _ = alias[1, 1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}} _ = alias[0x00] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}} _ = alias[0b00] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}} // Labeled tuple base _ = labeled[0] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.0'?}} {{14-17=.0}} _ = labeled[1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.1'?}} {{14-17=.1}} _ = labeled[2] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} _ = labeled[100] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} _ = labeled["string"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} _ = labeled[-1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} _ = labeled[1, 1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} _ = labeled[0x00] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} _ = labeled[0b00] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} // Suggesting use label access _ = labeled["a"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.a'?}} {{14-19=.a}} _ = labeled["b"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.b'?}} {{14-19=.b}} _ = labeled["c"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} _ = labeled[""] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}} } // rdar://problem/66891544 - incorrect diagnostic ("type is ambiguous") when base type of a reference cannot be determined func rdar66891544() { func foo<T>(_: T, defaultT: T? = nil) {} func foo<U>(_: U, defaultU: U? = nil) {} foo(.bar) // expected-error {{cannot infer contextual base in reference to member 'bar'}} } // rdar://55369704 - extraneous diagnostics produced in combination with missing/misspelled members func rdar55369704() { struct S { } func test(x: Int, s: S) { _ = x - Int(s.value) // expected-error {{value of type 'S' has no member 'value'}} } } // https://github.com/apple/swift/issues/56885 do { struct S { var xs: [Int] // expected-note {{'xs' declared here}} } func f(_ s: S) { for (x1, x2) in zip(s.xs, s.ys) { // expected-error@-1 {{value of type 'S' has no member 'ys'; did you mean 'xs'?}} } } } // rdar://92358570 class SomeClassBound {} protocol ClassBoundProtocol: SomeClassBound { } struct RDAR92358570<Element> {} extension RDAR92358570 where Element : SomeClassBound { // expected-note@-1 2 {{where 'Element' = 'any ClassBoundProtocol', 'SomeClassBound' = 'AnyObject'}} // expected-note@-2 2 {{where 'Element' = 'any SomeClassBound & ClassBoundProtocol', 'SomeClassBound' = 'AnyObject'}} func doSomething() {} static func doSomethingStatically() {} } func rdar92358570(_ x: RDAR92358570<ClassBoundProtocol>, _ y: RDAR92358570<SomeClassBound & ClassBoundProtocol>) { x.doSomething() // expected-error {{referencing instance method 'doSomething()' on 'RDAR92358570' requires that 'any ClassBoundProtocol' inherit from 'AnyObject'}} RDAR92358570<ClassBoundProtocol>.doSomethingStatically() // expected-error {{referencing static method 'doSomethingStatically()' on 'RDAR92358570' requires that 'any ClassBoundProtocol' inherit from 'AnyObject'}} y.doSomething() // expected-error {{referencing instance method 'doSomething()' on 'RDAR92358570' requires that 'any SomeClassBound & ClassBoundProtocol' inherit from 'AnyObject'}} RDAR92358570<SomeClassBound & ClassBoundProtocol>.doSomethingStatically() // expected-error {{referencing static method 'doSomethingStatically()' on 'RDAR92358570' requires that 'any SomeClassBound & ClassBoundProtocol' inherit from 'AnyObject'}} }
apache-2.0
e1f0e514e737bf8934059748afcf4bca
32.431847
248
0.648377
3.589168
false
false
false
false
cdtschange/SwiftMKit
SwiftMKit/Extension/Action+Extension.swift
1
1351
// // Action+Extension.swift // SwiftMKitDemo // // Created by Mao on 5/19/16. // Copyright © 2016 cdts. All rights reserved. // import Foundation import ReactiveCocoa import ReactiveSwift import UIKit public extension Action { public func bindEnabled(_ button: UIButton) { self.privateCocoaAction.isEnabled.producer.startWithValues { enabled in button.isEnabled = enabled button.viewContainingController?.view.isUserInteractionEnabled = enabled button.viewContainingController?.view.endEditing(false) } } public var toCocoaAction: CocoaAction<Any> { get { privateCocoaAction = CocoaAction(self) { input in if let button = input as? UIButton { self.bindEnabled(button) } return input as! Input } return privateCocoaAction } } } private var privateCocoaActionAssociationKey: UInt8 = 0 extension Action { var privateCocoaAction: CocoaAction<Any> { get { return objc_getAssociatedObject(self, &privateCocoaActionAssociationKey) as! CocoaAction } set(newValue) { objc_setAssociatedObject(self, &privateCocoaActionAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } }
mit
f18c3a2d6d3472db2f629f32b5832ce2
27.723404
135
0.646667
5.05618
false
false
false
false
hgl888/firefox-ios
Client/Frontend/Browser/TabTrayController.swift
1
36478
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit struct TabTrayControllerUX { static let CornerRadius = CGFloat(4.0) static let BackgroundColor = UIConstants.AppBackgroundColor static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1) static let TextBoxHeight = CGFloat(32.0) static let FaviconSize = CGFloat(18.0) static let Margin = CGFloat(15) static let ToolbarBarTintColor = UIConstants.AppBackgroundColor static let ToolbarButtonOffset = CGFloat(10.0) static let TabTitleTextFont = UIConstants.DefaultSmallFontBold static let CloseButtonSize = CGFloat(18.0) static let CloseButtonMargin = CGFloat(6.0) static let CloseButtonEdgeInset = CGFloat(10) static let NumberOfColumnsThin = 1 static let NumberOfColumnsWide = 3 static let CompactNumberOfColumnsThin = 2 // Moved from UIConstants temporarily until animation code is merged static var StatusBarHeight: CGFloat { if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact { return 0 } return 20 } } struct LightTabCellUX { static let TabTitleTextColor = UIColor.blackColor() } struct DarkTabCellUX { static let TabTitleTextColor = UIColor.whiteColor() } protocol TabCellDelegate: class { func tabCellDidClose(cell: TabCell) } class TabCell: UICollectionViewCell { enum Style { case Light case Dark } static let Identifier = "TabCellIdentifier" var style: Style = .Light { didSet { applyStyle(style) } } let backgroundHolder = UIView() let background = UIImageViewAligned() let titleText: UILabel let innerStroke: InnerStrokedView let favicon: UIImageView = UIImageView() let closeButton: UIButton var title: UIVisualEffectView! var animator: SwipeAnimator! weak var delegate: TabCellDelegate? // Changes depending on whether we're full-screen or not. var margin = CGFloat(0) override init(frame: CGRect) { self.backgroundHolder.backgroundColor = UIColor.whiteColor() self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius self.backgroundHolder.clipsToBounds = true self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor self.background.contentMode = UIViewContentMode.ScaleAspectFill self.background.clipsToBounds = true self.background.userInteractionEnabled = false self.background.alignLeft = true self.background.alignTop = true self.favicon.backgroundColor = UIColor.clearColor() self.favicon.layer.cornerRadius = 2.0 self.favicon.layer.masksToBounds = true self.titleText = UILabel() self.titleText.textAlignment = NSTextAlignment.Left self.titleText.userInteractionEnabled = false self.titleText.numberOfLines = 1 self.titleText.font = TabTrayControllerUX.TabTitleTextFont self.closeButton = UIButton() self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal) self.closeButton.tintColor = UIColor.lightGrayColor() self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset) self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame) self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor super.init(frame: frame) self.opaque = true self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self) self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside) contentView.addSubview(backgroundHolder) backgroundHolder.addSubview(self.background) backgroundHolder.addSubview(innerStroke) // Default style is light applyStyle(style) self.accessibilityCustomActions = [ UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture") ] } private func applyStyle(style: Style) { self.title?.removeFromSuperview() let title: UIVisualEffectView switch style { case .Light: title = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) self.titleText.textColor = LightTabCellUX.TabTitleTextColor case .Dark: title = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) self.titleText.textColor = DarkTabCellUX.TabTitleTextColor } titleText.backgroundColor = UIColor.clearColor() title.layer.shadowColor = UIColor.blackColor().CGColor title.layer.shadowOpacity = 0.2 title.layer.shadowOffset = CGSize(width: 0, height: 0.5) title.layer.shadowRadius = 0 title.addSubview(self.closeButton) title.addSubview(self.titleText) title.addSubview(self.favicon) backgroundHolder.addSubview(title) self.title = title } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let w = frame.width let h = frame.height backgroundHolder.frame = CGRect(x: margin, y: margin, width: w, height: h) background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size) title.frame = CGRect(x: 0, y: 0, width: backgroundHolder.frame.width, height: TabTrayControllerUX.TextBoxHeight) favicon.frame = CGRect(x: 6, y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2, width: TabTrayControllerUX.FaviconSize, height: TabTrayControllerUX.FaviconSize) let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6 titleText.frame = CGRect(x: titleTextLeft, y: 0, width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2, height: title.frame.height) innerStroke.frame = background.frame closeButton.snp_makeConstraints { make in make.size.equalTo(title.snp_height) make.trailing.centerY.equalTo(title) } let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0 titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top)) } override func prepareForReuse() { // Reset any close animations. backgroundHolder.transform = CGAffineTransformIdentity backgroundHolder.alpha = 1 } override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool { var right: Bool switch direction { case .Left: right = false case .Right: right = true default: return false } animator.close(right: right) return true } } @available(iOS 9, *) struct PrivateModeStrings { static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode") static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode") static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value") static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value") } class TabTrayController: UIViewController { let tabManager: TabManager let profile: Profile var collectionView: UICollectionView! var navBar: UIView! var addTabButton: UIButton! var settingsButton: UIButton! var collectionViewTransitionSnapshot: UIView? private(set) internal var privateMode: Bool = false { didSet { if #available(iOS 9, *) { togglePrivateMode.selected = privateMode togglePrivateMode.accessibilityValue = privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff tabDataSource.tabs = tabsToDisplay collectionView.reloadData() } } } private var tabsToDisplay: [Browser] { return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs } @available(iOS 9, *) lazy var togglePrivateMode: ToggleButton = { let button = ToggleButton() button.setImage(UIImage(named: "smallPrivateMask"), forState: UIControlState.Normal) button.addTarget(self, action: "SELdidTogglePrivateMode", forControlEvents: .TouchUpInside) button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint button.accessibilityValue = self.privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff return button }() @available(iOS 9, *) private lazy var emptyPrivateTabsView: EmptyPrivateTabsView = { let emptyView = EmptyPrivateTabsView() emptyView.learnMoreButton.addTarget(self, action: "SELdidTapLearnMore", forControlEvents: UIControlEvents.TouchUpInside) return emptyView }() private lazy var tabDataSource: TabManagerDataSource = { return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self) }() private lazy var tabLayoutDelegate: TabLayoutDelegate = { let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection) delegate.tabSelectionDelegate = self return delegate }() init(tabManager: TabManager, profile: Profile) { self.tabManager = tabManager self.profile = profile super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil) } // MARK: View Controller Callbacks override func viewDidLoad() { super.viewDidLoad() view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.") tabManager.addDelegate(self) navBar = UIView() navBar.backgroundColor = TabTrayControllerUX.BackgroundColor addTabButton = UIButton() addTabButton.setImage(UIImage(named: "add"), forState: .Normal) addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside) addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.") settingsButton = UIButton() settingsButton.setImage(UIImage(named: "settings"), forState: .Normal) settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside) settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.") let flowLayout = TabTrayCollectionViewLayout() collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout) collectionView.dataSource = tabDataSource collectionView.delegate = tabLayoutDelegate collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier) collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor view.addSubview(collectionView) view.addSubview(navBar) view.addSubview(addTabButton) view.addSubview(settingsButton) makeConstraints() if #available(iOS 9, *) { view.addSubview(togglePrivateMode) togglePrivateMode.snp_makeConstraints { make in make.right.equalTo(addTabButton.snp_left).offset(-10) make.size.equalTo(UIConstants.ToolbarHeight) make.centerY.equalTo(self.navBar) } view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView) emptyPrivateTabsView.alpha = privateMode && tabManager.privateTabs.count == 0 ? 1 : 0 emptyPrivateTabsView.snp_makeConstraints { make in make.edges.equalTo(self.view) } if let tab = tabManager.selectedTab where tab.isPrivate { privateMode = true } } NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELappWillResignActiveNotification", name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELappDidBecomeActiveNotification", name: UIApplicationDidBecomeActiveNotification, object: nil) } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // Update the trait collection we reference in our layout delegate tabLayoutDelegate.traitCollection = traitCollection } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition({ _ in self.collectionView.collectionViewLayout.invalidateLayout() }, completion: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } private func makeConstraints() { let viewBindings: [String: AnyObject] = [ "topLayoutGuide" : topLayoutGuide, "navBar" : navBar ] let topConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][navBar]", options: [], metrics: nil, views: viewBindings) view.addConstraints(topConstraints) navBar.snp_makeConstraints { make in make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } addTabButton.snp_makeConstraints { make in make.trailing.bottom.equalTo(self.navBar) make.size.equalTo(UIConstants.ToolbarHeight) } settingsButton.snp_makeConstraints { make in make.leading.bottom.equalTo(self.navBar) make.size.equalTo(UIConstants.ToolbarHeight) } collectionView.snp_makeConstraints { make in make.top.equalTo(navBar.snp_bottom) make.left.right.bottom.equalTo(self.view) } } // MARK: Selectors func SELdidClickDone() { presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } func SELdidClickSettingsItem() { let settingsTableViewController = SettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet presentViewController(controller, animated: true, completion: nil) } func SELdidClickAddTab() { openNewTab() } @available(iOS 9, *) func SELdidTapLearnMore() { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String if let langID = NSLocale.preferredLanguages().first { let learnMoreRequest = NSURLRequest(URL: "https://support.mozilla.org/1/mobile/\(appVersion)/iOS/\(langID)/private-browsing-ios".asURL!) openNewTab(learnMoreRequest) } } @available(iOS 9, *) func SELdidTogglePrivateMode() { let scaleDownTransform = CGAffineTransformMakeScale(0.9, 0.9) let fromView: UIView if privateTabsAreEmpty() { fromView = emptyPrivateTabsView } else { let snapshot = collectionView.snapshotViewAfterScreenUpdates(false) snapshot.frame = collectionView.frame view.insertSubview(snapshot, aboveSubview: collectionView) fromView = snapshot } privateMode = !privateMode // If we are exiting private mode and we have the close private tabs option selected, make sure // we clear out all of the private tabs if !privateMode && profile.prefs.boolForKey("settings.closePrivateTabs") ?? false { tabManager.removeAllPrivateTabsAndNotify(false) } togglePrivateMode.setSelected(privateMode, animated: true) collectionView.layoutSubviews() let toView: UIView if privateTabsAreEmpty() { toView = emptyPrivateTabsView } else { let newSnapshot = collectionView.snapshotViewAfterScreenUpdates(true) newSnapshot.frame = collectionView.frame view.insertSubview(newSnapshot, aboveSubview: fromView) collectionView.alpha = 0 toView = newSnapshot } toView.alpha = 0 toView.transform = scaleDownTransform UIView.animateWithDuration(0.2, delay: 0, options: [], animations: { () -> Void in fromView.transform = scaleDownTransform fromView.alpha = 0 toView.transform = CGAffineTransformIdentity toView.alpha = 1 }) { finished in if fromView != self.emptyPrivateTabsView { fromView.removeFromSuperview() } if toView != self.emptyPrivateTabsView { toView.removeFromSuperview() } self.collectionView.alpha = 1 } } @available(iOS 9, *) private func privateTabsAreEmpty() -> Bool { return privateMode && tabManager.privateTabs.count == 0 } private func openNewTab(request: NSURLRequest? = nil) { if #available(iOS 9, *) { if privateMode { emptyPrivateTabsView.hidden = true } } // We're only doing one update here, but using a batch update lets us delay selecting the tab // until after its insert animation finishes. self.collectionView.performBatchUpdates({ _ in var tab: Browser if #available(iOS 9, *) { tab = self.tabManager.addTab(request, isPrivate: self.privateMode) } else { tab = self.tabManager.addTab(request) } self.tabManager.selectTab(tab) }, completion: { finished in if finished { self.navigationController?.popViewControllerAnimated(true) } }) } } // MARK: - App Notifications extension TabTrayController { func SELappWillResignActiveNotification() { if privateMode { collectionView.alpha = 0 } } func SELappDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.collectionView.alpha = 1 }, completion: nil) } } extension TabTrayController: TabSelectionDelegate { func didSelectTabAtIndex(index: Int) { let tab = tabsToDisplay[index] tabManager.selectTab(tab) self.navigationController?.popViewControllerAnimated(true) } } extension TabTrayController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) { dismissViewControllerAnimated(animated, completion: { self.collectionView.reloadData() }) } } extension TabTrayController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { } func tabManager(tabManager: TabManager, didCreateTab tab: Browser) { } func tabManager(tabManager: TabManager, didAddTab tab: Browser) { // Get the index of the added tab from it's set (private or normal) guard let index = tabsToDisplay.indexOf(tab) else { return } tabDataSource.addTab(tab) self.collectionView.performBatchUpdates({ _ in self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)]) }, completion: { finished in if finished { tabManager.selectTab(tab) // don't pop the tab tray view controller if it is not in the foreground if self.presentedViewController == nil { self.navigationController?.popViewControllerAnimated(true) } } }) } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) { let removedIndex = tabDataSource.removeTab(tab) self.collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: removedIndex, inSection: 0)]) // Workaround: On iOS 8.* devices, cells don't get reloaded during the deletion but after the // animation has finished which causes cells that animate from above to suddenly 'appear'. This // is fixed on iOS 9 but for iOS 8 we force a reload on non-visible cells during the animation. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_8_3) { let visibleCount = collectionView.indexPathsForVisibleItems().count var offscreenIndexPaths = [NSIndexPath]() for i in 0..<(tabsToDisplay.count - visibleCount) { offscreenIndexPaths.append(NSIndexPath(forItem: i, inSection: 0)) } self.collectionView.reloadItemsAtIndexPaths(offscreenIndexPaths) } if #available(iOS 9, *) { if privateTabsAreEmpty() { emptyPrivateTabsView.alpha = 1 } } } func tabManagerDidAddTabs(tabManager: TabManager) { } func tabManagerDidRestoreTabs(tabManager: TabManager) { } } extension TabTrayController: UIScrollViewAccessibilityDelegate { func accessibilityScrollStatusForScrollView(scrollView: UIScrollView) -> String? { var visibleCells = collectionView.visibleCells() as! [TabCell] var bounds = collectionView.bounds bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top) bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom // visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...) visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) } let indexPaths = visibleCells.map { self.collectionView.indexPathForCell($0)! } .sort { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) } if indexPaths.count == 0 { return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray") } let firstTab = indexPaths.first!.row + 1 let lastTab = indexPaths.last!.row + 1 let tabCount = collectionView.numberOfItemsInSection(0) if (firstTab == lastTab) { let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.") return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount)) } else { let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.") return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount)) } } } extension TabTrayController: SwipeAnimatorDelegate { func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) { let tabCell = animator.container as! TabCell if let indexPath = collectionView.indexPathForCell(tabCell) { let tab = tabsToDisplay[indexPath.item] tabManager.removeTab(tab) UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: "")) } } } extension TabTrayController: TabCellDelegate { func tabCellDidClose(cell: TabCell) { let indexPath = collectionView.indexPathForCell(cell)! let tab = tabsToDisplay[indexPath.item] tabManager.removeTab(tab) } } private class TabManagerDataSource: NSObject, UICollectionViewDataSource { unowned var cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate> private var tabs: [Browser] init(tabs: [Browser], cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>) { self.cellDelegate = cellDelegate self.tabs = tabs super.init() } /** Removes the given tab from the data source - parameter tab: Tab to remove - returns: The index of the removed tab, -1 if tab did not exist */ func removeTab(tabToRemove: Browser) -> Int { var index: Int = -1 for (i, tab) in tabs.enumerate() { if tabToRemove === tab { index = i break } } tabs.removeAtIndex(index) return index } /** Adds the given tab to the data source - parameter tab: Tab to add */ func addTab(tab: Browser) { tabs.append(tab) } @objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let tabCell = collectionView.dequeueReusableCellWithReuseIdentifier(TabCell.Identifier, forIndexPath: indexPath) as! TabCell tabCell.animator.delegate = cellDelegate tabCell.delegate = cellDelegate let tab = tabs[indexPath.item] tabCell.style = tab.isPrivate ? .Dark : .Light tabCell.titleText.text = tab.displayTitle if !tab.displayTitle.isEmpty { tabCell.accessibilityLabel = tab.displayTitle } else { tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url) } tabCell.isAccessibilityElement = true tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.") if let favIcon = tab.displayFavicon { tabCell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!) } else { var defaultFavicon = UIImage(named: "defaultFavicon") if tab.isPrivate { defaultFavicon = defaultFavicon?.imageWithRenderingMode(.AlwaysTemplate) tabCell.favicon.image = defaultFavicon tabCell.favicon.tintColor = UIColor.whiteColor() } else { tabCell.favicon.image = defaultFavicon } } tabCell.background.image = tab.screenshot return tabCell } @objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tabs.count } } @objc protocol TabSelectionDelegate: class { func didSelectTabAtIndex(index :Int) } private class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout { weak var tabSelectionDelegate: TabSelectionDelegate? private var traitCollection: UITraitCollection private var profile: Profile private var numberOfColumns: Int { let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true // iPhone 4-6+ portrait if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular { return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin } else { return TabTrayControllerUX.NumberOfColumnsWide } } init(profile: Profile, traitCollection: UITraitCollection) { self.profile = profile self.traitCollection = traitCollection super.init() } private func cellHeightForCurrentDevice() -> CGFloat { let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5) if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact { return shortHeight } else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact { return shortHeight } else { return TabTrayControllerUX.TextBoxHeight * 8 } } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return TabTrayControllerUX.Margin } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)) return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice()) } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin) } @objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return TabTrayControllerUX.Margin } @objc func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row) } } // There seems to be a bug with UIKit where when the UICollectionView changes its contentSize // from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the // final state. // This workaround forces the contentSize to always be larger than the frame size so the animation happens more // smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I // think is fine, but if needed we can disable user scrolling in this case. private class TabTrayCollectionViewLayout: UICollectionViewFlowLayout { private override func collectionViewContentSize() -> CGSize { var calculatedSize = super.collectionViewContentSize() let collectionViewHeight = collectionView?.bounds.size.height ?? 0 if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 { calculatedSize.height = collectionViewHeight + 1 } return calculatedSize } } struct EmptyPrivateTabsViewUX { static let TitleColor = UIColor.whiteColor() static let TitleFont = UIFont.systemFontOfSize(22, weight: UIFontWeightMedium) static let DescriptionColor = UIColor.whiteColor() static let DescriptionFont = UIFont.systemFontOfSize(17) static let LearnMoreFont = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium) static let TextMargin: CGFloat = 18 static let LearnMoreMargin: CGFloat = 30 static let MaxDescriptionWidth: CGFloat = 250 } // View we display when there are no private tabs created private class EmptyPrivateTabsView: UIView { private lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = EmptyPrivateTabsViewUX.TitleColor label.font = EmptyPrivateTabsViewUX.TitleFont label.textAlignment = NSTextAlignment.Center return label }() private var descriptionLabel: UILabel = { let label = UILabel() label.textColor = EmptyPrivateTabsViewUX.DescriptionColor label.font = EmptyPrivateTabsViewUX.DescriptionFont label.textAlignment = NSTextAlignment.Center label.numberOfLines = 0 label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth return label }() private var learnMoreButton: UIButton = { let button = UIButton(type: .System) button.setTitle( NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode"), forState: .Normal) button.setTitleColor(UIConstants.PrivateModeTextHighlightColor, forState: .Normal) button.titleLabel?.font = EmptyPrivateTabsViewUX.LearnMoreFont return button }() private var iconImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "largePrivateMask")) return imageView }() override init(frame: CGRect) { super.init(frame: frame) titleLabel.text = NSLocalizedString("Private Browsing", tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode") descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.", tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode") addSubview(titleLabel) addSubview(descriptionLabel) addSubview(iconImageView) addSubview(learnMoreButton) titleLabel.snp_makeConstraints { make in make.center.equalTo(self) } iconImageView.snp_makeConstraints { make in make.bottom.equalTo(titleLabel.snp_top).offset(-EmptyPrivateTabsViewUX.TextMargin) make.centerX.equalTo(self) } descriptionLabel.snp_makeConstraints { make in make.top.equalTo(titleLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.TextMargin) make.centerX.equalTo(self) } learnMoreButton.snp_makeConstraints { (make) -> Void in make.top.equalTo(descriptionLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.LearnMoreMargin) make.centerX.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
393741ab4fe2bbb1070aa82298c90785
40.032621
304
0.688716
5.644128
false
false
false
false
jonsimington/sentence-pal
Sentence Pal/SecondViewController.swift
1
9917
// // SecondViewController.swift // Sentence Pal // // Created by Jon Simington on 9/27/15. // Copyright (c) 2015 Jon Simington. All rights reserved. // import UIKit import Parsimmon extension String { func words() -> [String] { let range = Range<String.Index>(start: self.startIndex, end: self.endIndex) var words = [String]() self.enumerateSubstringsInRange(range, options: NSStringEnumerationOptions.ByWords) { (substring, _, _, _) -> () in words.append(substring!) } return words } } func random(range: Range<Int> ) -> Int { var offset = 0 if range.startIndex < 0 // allow negative ranges { offset = abs(range.startIndex) } let mini = UInt32(range.startIndex + offset) let maxi = UInt32(range.endIndex + offset) return Int(mini + arc4random_uniform(maxi - mini)) - offset } // Returns the last character of a string func lastChar(string: String) -> Character { let char: Character = string[string.endIndex.predecessor()] return char } // Returns the first character of a string func firstChar(string: String) -> Character { let char: Character = string[string.startIndex] return char } class SecondViewController: UIViewController { // UITextFields @IBOutlet weak var structureTextField: UITextField! // UILabels @IBOutlet weak var structureLabel: UILabel! // UIButtons @IBOutlet weak var nounButton: UIButton! @IBOutlet weak var prepositionButton: UIButton! @IBOutlet weak var adjectiveButton: UIButton! @IBOutlet weak var verbButton: UIButton! @IBOutlet weak var determinerButton: UIButton! @IBOutlet weak var personalNameButton: UIButton! @IBOutlet weak var uarticleButton: UIButton! @IBOutlet weak var particleButton: UIButton! @IBOutlet weak var interjectionButton: UIButton! @IBOutlet weak var adverbButton: UIButton! @IBOutlet weak var placeNameButton: UIButton! @IBOutlet weak var conjunctionButton: UIButton! @IBOutlet weak var numberButton: UIButton! @IBOutlet weak var pronounButton: UIButton! @IBOutlet weak var orgNameButton: UIButton! @IBOutlet weak var generateButton: UIButton! @IBOutlet weak var generatedText: UILabel! @IBOutlet weak var clearAllKeywordsButton: UIButton! // Button Actions @IBAction func nounButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " noun" } @IBAction func adverbButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " adverb" } @IBAction func personalNameButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " personal_name" } @IBAction func prepositionButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " preposition" } @IBAction func interjectionButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " interjection" } @IBAction func determinerButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " determiner" } @IBAction func particleButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " particle" } @IBAction func uarticleButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " uarticle" } @IBAction func orgNameButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " organization_name" } @IBAction func numberButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " number" } @IBAction func adjectiveButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " adjective" } @IBAction func conjunctionButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " conjunction" } @IBAction func verbButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " verb" } @IBAction func placeNameButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " place_name" } @IBAction func pronounButtonPressed(sender: UIButton) { structureTextField.text = structureTextField.text! + " pronoun" } @IBAction func generateButtonPressed(sender: UIButton) { generatedText.hidden = false generatedText.text = generateSentence(structureTextField.text!) if (generatedText.text == "") { generatedText.text = "Enter some keywords, ya doop!" } } @IBAction func clearAllKeywordsButtonPressed(sender: UIButton) { structureTextField.text = "" } // NLP machines let tokenizer = Tokenizer() let tagger = Tagger() let classifier = NaiveBayesClassifier() // Arrays to hold words of each tag var nouns: [String] = [""] var adjectives: [String] = [""] var verbs: [String] = [""] var determiners: [String] = [""] var prepositions: [String] = [""] var adverbs: [String] = [""] var conjunctions: [String] = [""] var numbers: [String] = [""] var pronouns: [String] = [""] var place_names: [String] = [""] var personal_names: [String] = [""] var particles: [String] = [""] var interjections: [String] = [""] var organization_names: [String] = [""] let uarticles: [String] = ["The", "A"] let space: String = " " // Fills arrays with words of their tag func setUp() { let taggedTokens = tagger.tagWordsInText(book_text) for token in taggedTokens { switch token.getTag { case "Noun": nouns.append(token.getToken.lowercaseString) case "Adjective": adjectives.append(token.getToken.lowercaseString) case "Verb": verbs.append(token.getToken.lowercaseString) case "Determiner": determiners.append(token.getToken.lowercaseString) case "Preposition": prepositions.append(token.getToken.lowercaseString) case "Adverb": adverbs.append(token.getToken.lowercaseString) case "Conjunction": conjunctions.append(token.getToken.lowercaseString) case "Number": numbers.append(token.getToken.lowercaseString) case "Pronoun": pronouns.append(token.getToken.lowercaseString) case "PlaceName": place_names.append(token.getToken.lowercaseString) case "PersonalName": personal_names.append(token.getToken.lowercaseString) case "Particle": particles.append(token.getToken.lowercaseString) case "Interjection": interjections.append(token.getToken.lowercaseString) case "OrganizationName": organization_names.append(token.getToken.lowercaseString) default: continue } } } // returns sentence built from structure passed func generateSentence(structure: String) -> String { var word: String = "" let words = structure.words() var string: String = "" for token in words { switch token.lowercaseString { case "noun": word = nouns[random(0...nouns.count-1)] case "adjective", "adj": word = adjectives[random(0...adjectives.count-1)] case "verb": word = verbs[random(0...verbs.count-1)] case "determiner", "det": word = determiners[random(0...determiners.count-1)] case "preposition", "prep": word = prepositions[random(0...prepositions.count-1)] case "adverb", "adv": word = adverbs[random(0...adverbs.count-1)] case "conjunction", "conj": word = conjunctions[random(0...conjunctions.count-1)] case "number": word = numbers[random(0...numbers.count-1)] case "pronoun": word = pronouns[random(0...pronouns.count-1)] case "place_name": word = place_names[random(0...place_names.count-1)] case "personal_name": word = personal_names[random(0...personal_names.count-1)] case "particle": word = particles[random(0...particles.count-1)] case "interjection": word = interjections[random(0...interjections.count-1)] case "organization_name": word = organization_names[random(0...organization_names.count-1)] case "uarticle": word = uarticles[random(0...uarticles.count-1)] case "<the>", "the": word = "the" case "<period>", "period": word = "." default: word = "" } if token == words[0] { word = word.capitalizedString } print(word) if word == "." { string += word } else { string += " " + word } } print(string) return string } override func viewDidLoad() { super.viewDidLoad() setUp() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
4bcb02614bf0d1a9604075c86beda338
34.417857
123
0.601392
4.647142
false
false
false
false
ios-archy/Sinaweibo_swift
SinaWeibo_swift/SinaWeibo_swift/Classess/Home/Popover/PopoverAnimator.swift
1
4081
// // PopoverAnimator.swift // SinaWeibo_swift // // Created by archy on 16/10/21. // Copyright © 2016年 archy. All rights reserved. // import UIKit class PopoverAnimator: NSObject { //MARK: --对外提供属性 var isPresent : Bool = false var presentedFrame : CGRect = CGRectZero var callBack :((presented :Bool) -> ())? //MARK: --自定义构造函数 //注意:如果自定义了一个构造函数,但是没有对默认构造函数init()重写。那么自定义一构造函数会覆盖默认的init()构造函数 init(callBack : (presented : Bool) -> ()) { self.callBack = callBack } } //MARK: --自定义转场代理的方法 extension PopoverAnimator : UIViewControllerTransitioningDelegate { //目的:改变弹出的view的尺寸 func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { let presentation = ArchyPresentationController(presentedViewController : presented ,presentingViewController: presenting ) presentation.presentedFrame = presentedFrame return presentation } // //MARK: --目的:自定义弹出的动画 func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = true callBack!(presented: isPresent) return self } //MARK: --自定义消失的动画 func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false callBack!(presented: isPresent) return self } } //MARK: --弹出和消失动画代理的方法 extension PopoverAnimator : UIViewControllerAnimatedTransitioning { /** * 动画执行的时间 */ func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } // func animateTransition(transitionContext: UIViewControllerContextTransitioning) { isPresent ? animationForPresentedView(transitionContext) : animationForDismissedView(transitionContext) } //自定义弹出动画 private func animationForPresentedView(transitonContext : UIViewControllerContextTransitioning) { //1.获取弹出的view let presentedView = transitonContext.viewForKey(UITransitionContextToViewKey)! //2.将弹出的view添加到contaninerView中 transitonContext.containerView()?.addSubview(presentedView) //3.执行动画 presentedView.transform = CGAffineTransformMakeScale(1.0, 0.0) presentedView.layer.anchorPoint = CGPointMake(0.5, 0) UIView.animateWithDuration(transitionDuration(transitonContext), animations: { () -> Void in presentedView.transform = CGAffineTransformIdentity }) { (_) -> Void in //必须告诉转场上下文你已经完成动画 transitonContext.completeTransition(true) } } /** * 自定义消失动画 */ private func animationForDismissedView(transitionContext : UIViewControllerContextTransitioning) { //1.获取消失view let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey) //2.执行动画 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in dismissView?.transform = CGAffineTransformMakeScale(1.0, 0.00001) }) { (_) -> Void in dismissView?.removeFromSuperview() //必须告诉转场上下文你已经完成动画 transitionContext.completeTransition(true) } } }
mit
2188bdda2bb1265e8834ce33db40b1ed
28.070866
219
0.673619
5.75975
false
false
false
false
jasperscholten/programmeerproject
JasperScholten-project/Organisation.swift
1
1112
// // Organisation.swift // JasperScholten-project // // Created by Jasper Scholten on 23-01-17. // Copyright © 2017 Jasper Scholten. All rights reserved. // // The struct presented here deals with 'Organisations' saved in Firebase. These are saved in a separate list, to make it easier to retrieve them all when you, for example, want to present them in a pickerView on registration of a new employee. import Foundation import Firebase struct Organisation { let organisationID: String let organisation: String init(organisationID: String, organisation: String) { self.organisationID = organisationID self.organisation = organisation } init(snapshot: FIRDataSnapshot) { let snapshotValue = snapshot.value as! [String: AnyObject] self.organisationID = snapshotValue["organisationID"] as! String self.organisation = snapshotValue["organisation"] as! String } func toAnyObject() -> Any { return [ "organisationID": organisationID, "organisation": organisation ] } }
apache-2.0
56e4d998403690e421384d230236f11b
29.861111
245
0.675968
4.572016
false
false
false
false
OscarSwanros/swift
stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift
2
10423
//===--- Subprocess.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftPrivate #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) import Glibc #endif #if !os(Windows) // posix_spawn is not available on Windows. // posix_spawn is not available on Android. // posix_spawn is not available on Haiku. #if !os(Android) && !os(Haiku) // swift_posix_spawn isn't available in the public watchOS SDK, we sneak by the // unavailable attribute declaration here of the APIs that we need. // FIXME: Come up with a better way to deal with APIs that are pointers on some // platforms but not others. #if os(Linux) typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t #else typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t? #endif @_silgen_name("swift_posix_spawn_file_actions_init") func swift_posix_spawn_file_actions_init( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t> ) -> CInt @_silgen_name("swift_posix_spawn_file_actions_destroy") func swift_posix_spawn_file_actions_destroy( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t> ) -> CInt @_silgen_name("swift_posix_spawn_file_actions_addclose") func swift_posix_spawn_file_actions_addclose( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>, _ filedes: CInt) -> CInt @_silgen_name("swift_posix_spawn_file_actions_adddup2") func swift_posix_spawn_file_actions_adddup2( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>, _ filedes: CInt, _ newfiledes: CInt) -> CInt @_silgen_name("swift_posix_spawn") func swift_posix_spawn( _ pid: UnsafeMutablePointer<pid_t>?, _ file: UnsafePointer<Int8>, _ file_actions: UnsafePointer<swift_posix_spawn_file_actions_t>?, _ attrp: UnsafePointer<posix_spawnattr_t>?, _ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>, _ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt #endif /// Calls POSIX `pipe()`. func posixPipe() -> (readFD: CInt, writeFD: CInt) { var fds: [CInt] = [ -1, -1 ] if pipe(&fds) != 0 { preconditionFailure("pipe() failed") } return (fds[0], fds[1]) } /// Start the same executable as a child process, redirecting its stdout and /// stderr. public func spawnChild(_ args: [String]) -> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) { // The stdout, stdin, and stderr from the child process will be redirected // to these pipes. let childStdout = posixPipe() let childStdin = posixPipe() let childStderr = posixPipe() #if os(Android) || os(Haiku) // posix_spawn isn't available on Android. Instead, we fork and exec. // To correctly communicate the exit status of the child process to this // (parent) process, we'll use this pipe. let childToParentPipe = posixPipe() let pid = fork() precondition(pid >= 0, "fork() failed") if pid == 0 { // pid of 0 means we are now in the child process. // Capture the output before executing the program. dup2(childStdout.writeFD, STDOUT_FILENO) dup2(childStdin.readFD, STDIN_FILENO) dup2(childStderr.writeFD, STDERR_FILENO) // Set the "close on exec" flag on the parent write pipe. This will // close the pipe if the execve() below successfully executes a child // process. let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC) let closeErrno = errno precondition( closeResult == 0, "Could not set the close behavior of the child-to-parent pipe; " + "errno: \(closeErrno)") // Start the executable. If execve() does not encounter an error, the // code after this block will never be executed, and the parent write pipe // will be closed. withArrayOfCStrings([CommandLine.arguments[0]] + args) { execve(CommandLine.arguments[0], $0, _getEnviron()) } // If execve() encountered an error, we write the errno encountered to the // parent write pipe. let errnoSize = MemoryLayout.size(ofValue: errno) var execveErrno = errno let writtenBytes = withUnsafePointer(to: &execveErrno) { write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize) } let writeErrno = errno if writtenBytes > 0 && writtenBytes < errnoSize { // We were able to write some of our error, but not all of it. // FIXME: Retry in this case. preconditionFailure("Unable to write entire error to child-to-parent " + "pipe.") } else if writtenBytes == 0 { preconditionFailure("Unable to write error to child-to-parent pipe.") } else if writtenBytes < 0 { preconditionFailure("An error occurred when writing error to " + "child-to-parent pipe; errno: \(writeErrno)") } // Close the pipe when we're done writing the error. close(childToParentPipe.writeFD) } #else var fileActions = _make_posix_spawn_file_actions_t() if swift_posix_spawn_file_actions_init(&fileActions) != 0 { preconditionFailure("swift_posix_spawn_file_actions_init() failed") } // Close the write end of the pipe on the child side. if swift_posix_spawn_file_actions_addclose( &fileActions, childStdin.writeFD) != 0 { preconditionFailure("swift_posix_spawn_file_actions_addclose() failed") } // Remap child's stdin. if swift_posix_spawn_file_actions_adddup2( &fileActions, childStdin.readFD, STDIN_FILENO) != 0 { preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed") } // Close the read end of the pipe on the child side. if swift_posix_spawn_file_actions_addclose( &fileActions, childStdout.readFD) != 0 { preconditionFailure("swift_posix_spawn_file_actions_addclose() failed") } // Remap child's stdout. if swift_posix_spawn_file_actions_adddup2( &fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 { preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed") } // Close the read end of the pipe on the child side. if swift_posix_spawn_file_actions_addclose( &fileActions, childStderr.readFD) != 0 { preconditionFailure("swift_posix_spawn_file_actions_addclose() failed") } // Remap child's stderr. if swift_posix_spawn_file_actions_adddup2( &fileActions, childStderr.writeFD, STDERR_FILENO) != 0 { preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed") } var pid: pid_t = -1 var childArgs = args childArgs.insert(CommandLine.arguments[0], at: 0) let interpreter = getenv("SWIFT_INTERPRETER") if interpreter != nil { if let invocation = String(validatingUTF8: interpreter!) { childArgs.insert(invocation, at: 0) } } let spawnResult = withArrayOfCStrings(childArgs) { swift_posix_spawn( &pid, childArgs[0], &fileActions, nil, $0, _getEnviron()) } if spawnResult != 0 { print(String(cString: strerror(spawnResult))) preconditionFailure("swift_posix_spawn() failed") } if swift_posix_spawn_file_actions_destroy(&fileActions) != 0 { preconditionFailure("swift_posix_spawn_file_actions_destroy() failed") } #endif // Close the read end of the pipe on the parent side. if close(childStdin.readFD) != 0 { preconditionFailure("close() failed") } // Close the write end of the pipe on the parent side. if close(childStdout.writeFD) != 0 { preconditionFailure("close() failed") } // Close the write end of the pipe on the parent side. if close(childStderr.writeFD) != 0 { preconditionFailure("close() failed") } return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD) } #if !os(Android) && !os(Haiku) #if os(Linux) internal func _make_posix_spawn_file_actions_t() -> swift_posix_spawn_file_actions_t { return posix_spawn_file_actions_t() } #else internal func _make_posix_spawn_file_actions_t() -> swift_posix_spawn_file_actions_t { return nil } #endif #endif internal func _signalToString(_ signal: Int) -> String { switch CInt(signal) { case SIGILL: return "SIGILL" case SIGTRAP: return "SIGTRAP" case SIGABRT: return "SIGABRT" case SIGFPE: return "SIGFPE" case SIGBUS: return "SIGBUS" case SIGSEGV: return "SIGSEGV" case SIGSYS: return "SIGSYS" default: return "SIG???? (\(signal))" } } public enum ProcessTerminationStatus : CustomStringConvertible { case exit(Int) case signal(Int) public var description: String { switch self { case .exit(let status): return "Exit(\(status))" case .signal(let signal): return "Signal(\(_signalToString(signal)))" } } } public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus { var status: CInt = 0 #if os(Cygwin) withUnsafeMutablePointer(to: &status) { statusPtr in let statusPtrWrapper = __wait_status_ptr_t(__int_ptr: statusPtr) while waitpid(pid, statusPtrWrapper, 0) < 0 { if errno != EINTR { preconditionFailure("waitpid() failed") } } } #else while waitpid(pid, &status, 0) < 0 { if errno != EINTR { preconditionFailure("waitpid() failed") } } #endif if WIFEXITED(status) { return .exit(Int(WEXITSTATUS(status))) } if WIFSIGNALED(status) { return .signal(Int(WTERMSIG(status))) } preconditionFailure("did not understand what happened to child process") } #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) @_silgen_name("swift_SwiftPrivateLibcExtras_NSGetEnviron") func _NSGetEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>> #endif internal func _getEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) return _NSGetEnviron().pointee #elseif os(FreeBSD) return environ #elseif os(PS4) return environ #elseif os(Android) return environ #elseif os(Cygwin) return environ #elseif os(Haiku) return environ #else return __environ #endif } #endif
apache-2.0
4a84b5848502810d2062b4533435f22d
31.77673
96
0.684352
3.749281
false
false
false
false
winslowdibona/TabDrawer
TabDrawer/Classes/Attribute+Operators.swift
1
2914
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation extension Attribute: Equatable { } /** Infix operator which determines whether two Attributes are equal */ public func == (lhs: Attribute, rhs: Attribute) -> Bool { // Create views if (lhs.createView === rhs.createView) == false { return false } // Create attributes if lhs.createAttribute.conflictingAttributes.contains(rhs.createAttribute) == false { return false } // Reference views if (lhs.referenceView === rhs.referenceView) == false { return false } // Reference attributes if lhs.referenceAttribute != rhs.referenceAttribute { return false } // Constant if lhs.constant.value != rhs.constant.value { return false } if lhs.constant.modifier != rhs.constant.modifier { return false } // Priorities conflict if lhs.priority.layoutPriority() != rhs.priority.layoutPriority() { return false } // Conditions conflict var lhsCondition = true if let createView = lhs.createView { lhsCondition = lhs.shouldInstallOnView(createView) } var rhsCondition = true if let createView = rhs.createView { rhsCondition = rhs.shouldInstallOnView(createView) } if lhsCondition != rhsCondition { return false } return true } infix operator =~ {} /** Infix operator which determines whether two Attributes conflict between them or not */ internal func =~ (installed: Attribute, toInstall: Attribute) -> Bool { // Create views conflict if (installed.createView === toInstall.createView) == false { return false } // Create attributes conflict if installed.createAttribute.conflictingAttributes.contains(toInstall.createAttribute) == false { return false } // Priorities conflict if installed.priority.layoutPriority() != toInstall.priority.layoutPriority() { return false } // Conditions conflict (we assume condition is true for // the installed view) var toInstallCondition = true if let createView = toInstall.createView { toInstallCondition = toInstall.shouldInstallOnView(createView) } if toInstallCondition == false { return false } return true }
mit
83aead0a7f7c456f444354b80c326d0a
26.233645
101
0.658545
4.848586
false
false
false
false
akesson/weathery
weathery/WeatherData.swift
1
1059
// // WeatherData.swift // weathery // // Created by Henrik Akesson on 1/7/17. // Copyright © 2017 Henrik Akesson. All rights reserved. // import Foundation import SwiftyJSON struct WeatherData { enum DataError: Error { case invalidJSON(String) } let city: String let temperature: Double let cloud: Int let windSpeed: Double let humidity: Int init(_ data: Data) throws { let json = JSON(data: data) guard let kelvin = json["main"]["temp"].double, let city = json["name"].string, let cloud = json["clouds"]["all"].int, let windSpeed = json["wind"]["speed"].double, let humidity = json["main"]["humidity"].int else { throw DataError.invalidJSON(json.description) } self.city = city self.temperature = kelvin - 273.15 //Kelvin to Celcius self.cloud = cloud self.windSpeed = windSpeed self.humidity = humidity } }
mit
ebe229e894e3bdf6847d75de01bc39f6
23.045455
62
0.55482
4.483051
false
false
false
false
larrabetzu/iBasque-Radio
SwiftRadio/SwiftRadio-Settings.swift
1
808
// // SwiftRadio-Settings.swift // Swift Radio // // Created by Matthew Fecher on 7/2/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import Foundation //************************************** // GENERAL SETTINGS //************************************** // Display Comments let DEBUG_LOG = false //************************************** // STATION JSON //************************************** // If this is set to "true", it will use the JSON file in the app // Set it to "false" to use the JSON file at the stationDataURL let useLocalStations = true let stationDataURL = "http://yoururl.com/json/stations.json" let SupportEmail = "[email protected]" let SupportEmailSubject = "From iBasqueRadio App" let SupportWebsite = "https://github.com/larrabetzu/iBasque-Radio/"
mit
7c20ab402517fbdcb89c21294a602673
26.862069
67
0.584158
3.866029
false
false
false
false
richerarc/Simplr
Sources/Simplr.swift
1
41075
// // File created by Richer Archambault // February 18, 2017 // [email protected] // import Foundation // Just Http // // Found at https://github.com/JustHTTP/Just under : // // The MIT License (MIT) // // Copyright (c) 2015 Just contributors // // 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. // stolen from python-requests let statusCodeDescriptions = [ // Informational. 100: "continue", 101: "switching protocols", 102: "processing", 103: "checkpoint", 122: "uri too long", 200: "ok", 201: "created", 202: "accepted", 203: "non authoritative info", 204: "no content", 205: "reset content", 206: "partial content", 207: "multi status", 208: "already reported", 226: "im used", // Redirection. 300: "multiple choices", 301: "moved permanently", 302: "found", 303: "see other", 304: "not modified", 305: "use proxy", 306: "switch proxy", 307: "temporary redirect", 308: "permanent redirect", // Client Error. 400: "bad request", 401: "unauthorized", 402: "payment required", 403: "forbidden", 404: "not found", 405: "method not allowed", 406: "not acceptable", 407: "proxy authentication required", 408: "request timeout", 409: "conflict", 410: "gone", 411: "length required", 412: "precondition failed", 413: "request entity too large", 414: "request uri too large", 415: "unsupported media type", 416: "requested range not satisfiable", 417: "expectation failed", 418: "im a teapot", 422: "unprocessable entity", 423: "locked", 424: "failed dependency", 425: "unordered collection", 426: "upgrade required", 428: "precondition required", 429: "too many requests", 431: "header fields too large", 444: "no response", 449: "retry with", 450: "blocked by windows parental controls", 451: "unavailable for legal reasons", 499: "client closed request", // Server Error. 500: "internal server error", 501: "not implemented", 502: "bad gateway", 503: "service unavailable", 504: "gateway timeout", 505: "http version not supported", 506: "variant also negotiates", 507: "insufficient storage", 509: "bandwidth limit exceeded", 510: "not extended", ] public enum HTTPFile { case url(URL, String?) // URL to a file, mimetype case data(String, Foundation.Data, String?) // filename, data, mimetype case text(String, String, String?) // filename, text, mimetype } // Supported request types public enum HTTPMethod: String { case DELETE = "DELETE" case GET = "GET" case HEAD = "HEAD" case OPTIONS = "OPTIONS" case PATCH = "PATCH" case POST = "POST" case PUT = "PUT" } extension URLResponse { var HTTPHeaders: [String: String] { return (self as? HTTPURLResponse)?.allHeaderFields as? [String: String] ?? [:] } } /// The only reason this is not a struct is the requirements for /// lazy evaluation of `headers` and `cookies`, which is mutating the /// struct. This would make those properties unusable with `HTTPResult`s /// declared with `let` public final class HTTPResult : NSObject { public final var content: Data? public var response: URLResponse? public var error: Error? public var request: URLRequest? { return task?.originalRequest } public var task: URLSessionTask? public var encoding = String.Encoding.utf8 public var JSONReadingOptions = JSONSerialization.ReadingOptions(rawValue: 0) public var reason: String { if let code = self.statusCode, let text = statusCodeDescriptions[code] { return text } if let error = self.error { return error.localizedDescription } return "Unknown" } public var isRedirect: Bool { if let code = self.statusCode { return code >= 300 && code < 400 } return false } public var isPermanentRedirect: Bool { return self.statusCode == 301 } public override var description: String { if let status = statusCode, let urlString = request?.url?.absoluteString, let method = request?.httpMethod { return "\(method) \(urlString) \(status)" } else { return "<Empty>" } } public init(data: Data?, response: URLResponse?, error: Error?, task: URLSessionTask?) { self.content = data self.response = response self.error = error self.task = task } public var json: Any? { return content.flatMap { try? JSONSerialization.jsonObject(with: $0, options: JSONReadingOptions) } } public var statusCode: Int? { return (self.response as? HTTPURLResponse)?.statusCode } public var text: String? { return content.flatMap { String(data: $0, encoding: encoding) } } public lazy var headers: CaseInsensitiveDictionary<String, String> = { return CaseInsensitiveDictionary<String, String>( dictionary: self.response?.HTTPHeaders ?? [:]) }() public lazy var cookies: [String: HTTPCookie] = { let foundCookies: [HTTPCookie] if let headers = self.response?.HTTPHeaders, let url = self.response?.url { foundCookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: url) as [HTTPCookie] } else { foundCookies = [] } var result: [String: HTTPCookie] = [:] for cookie in foundCookies { result[cookie.name] = cookie } return result }() public var ok: Bool { return statusCode != nil && !(statusCode! >= 400 && statusCode! < 600) } public var url: URL? { return response?.url } public lazy var links: [String: [String: String]] = { var result = [String: [String: String]]() guard let content = self.headers["link"] else { return result } content.components(separatedBy: ", ").forEach { s in let linkComponents = s.components(separatedBy: ";") .map { ($0 as NSString).trimmingCharacters(in: CharacterSet.whitespaces) } // although a link without a rel is valid, there's no way to reference it. if linkComponents.count > 1 { let url = linkComponents.first! let start = url.characters.index(url.startIndex, offsetBy: 1) let end = url.characters.index(url.endIndex, offsetBy: -1) let urlRange = start..<end var link: [String: String] = ["url": String(url.characters[urlRange])] linkComponents.dropFirst().forEach { s in if let equalIndex = s.characters.index(of: "=") { let componentKey = String(s.characters[s.startIndex..<equalIndex]) let range = s.index(equalIndex, offsetBy: 1)..<s.endIndex let value = s.characters[range] if value.first == "\"" && value.last == "\"" { let start = value.index(value.startIndex, offsetBy: 1) let end = value.index(value.endIndex, offsetBy: -1) link[componentKey] = String(value[start..<end]) } else { link[componentKey] = String(value) } } } if let rel = link["rel"] { result[rel] = link } } } return result }() public func cancel() { task?.cancel() } } public struct CaseInsensitiveDictionary<Key: Hashable, Value>: Collection, ExpressibleByDictionaryLiteral { private var _data: [Key: Value] = [:] private var _keyMap: [String: Key] = [:] public typealias Element = (key: Key, value: Value) public typealias Index = DictionaryIndex<Key, Value> public var startIndex: Index { return _data.startIndex } public var endIndex: Index { return _data.endIndex } public func index(after: Index) -> Index { return _data.index(after: after) } public var count: Int { assert(_data.count == _keyMap.count, "internal keys out of sync") return _data.count } public var isEmpty: Bool { return _data.isEmpty } public init(dictionaryLiteral elements: (Key, Value)...) { for (key, value) in elements { _keyMap["\(key)".lowercased()] = key _data[key] = value } } public init(dictionary: [Key: Value]) { for (key, value) in dictionary { _keyMap["\(key)".lowercased()] = key _data[key] = value } } public subscript (position: Index) -> Element { return _data[position] } public subscript (key: Key) -> Value? { get { if let realKey = _keyMap["\(key)".lowercased()] { return _data[realKey] } return nil } set(newValue) { let lowerKey = "\(key)".lowercased() if _keyMap[lowerKey] == nil { _keyMap[lowerKey] = key } _data[_keyMap[lowerKey]!] = newValue } } public func makeIterator() -> DictionaryIterator<Key, Value> { return _data.makeIterator() } public var keys: LazyMapCollection<[Key : Value], Key> { return _data.keys } public var values: LazyMapCollection<[Key : Value], Value> { return _data.values } } typealias TaskID = Int public typealias Credentials = (username: String, password: String) public typealias TaskProgressHandler = (HTTPProgress) -> Void typealias TaskCompletionHandler = (HTTPResult) -> Void struct TaskConfiguration { let credential: Credentials? let redirects: Bool let originalRequest: URLRequest? var data: NSMutableData let progressHandler: TaskProgressHandler? let completionHandler: TaskCompletionHandler? } public struct JustSessionDefaults { public var JSONReadingOptions: JSONSerialization.ReadingOptions public var JSONWritingOptions: JSONSerialization.WritingOptions public var headers: [String: String] public var multipartBoundary: String public var credentialPersistence: URLCredential.Persistence public var encoding: String.Encoding public var cachePolicy: NSURLRequest.CachePolicy public init( JSONReadingOptions: JSONSerialization.ReadingOptions = JSONSerialization.ReadingOptions(rawValue: 0), JSONWritingOptions: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0), headers: [String: String] = [:], multipartBoundary: String = "Ju5tH77P15Aw350m3", credentialPersistence: URLCredential.Persistence = .forSession, encoding: String.Encoding = String.Encoding.utf8, cachePolicy: NSURLRequest.CachePolicy = .reloadIgnoringLocalCacheData) { self.JSONReadingOptions = JSONReadingOptions self.JSONWritingOptions = JSONWritingOptions self.headers = headers self.multipartBoundary = multipartBoundary self.encoding = encoding self.credentialPersistence = credentialPersistence self.cachePolicy = cachePolicy } } public struct HTTPProgress { public enum `Type` { case upload case download } public let type: Type public let bytesProcessed: Int64 public let bytesExpectedToProcess: Int64 public var chunk: Data? public var percent: Float { return Float(bytesProcessed) / Float(bytesExpectedToProcess) } } let errorDomain = "net.simplrhttp.Simplr" public protocol JustAdaptor { func request( _ method: HTTPMethod, URLString: String, params: [String: Any], data: [String: Any], json: Any?, headers: [String: String], files: [String: HTTPFile], auth: Credentials?, cookies: [String: String], redirects: Bool, timeout: Double?, URLQuery: String?, requestBody: Data?, asyncProgressHandler: TaskProgressHandler?, asyncCompletionHandler: ((HTTPResult) -> Void)? ) -> HTTPResult init(session: URLSession?, defaults: JustSessionDefaults?) func setURLBasePath(url: String) } public struct JustOf<Adaptor: JustAdaptor> { let adaptor: Adaptor public init(session: URLSession? = nil, defaults: JustSessionDefaults? = nil) { adaptor = Adaptor(session: session, defaults: defaults) } } extension JustOf { @discardableResult public func request( _ method: HTTPMethod, URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( method, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func delete( _ URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .DELETE, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func get( _ URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .GET, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func head( _ URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .HEAD, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func options( _ URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .OPTIONS, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func patch( _ URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .PATCH, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func post( _ URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .POST, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } @discardableResult public func put( _ URLString: String, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return adaptor.request( .PUT, URLString: URLString, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public func setURLBasePath(url: String) { adaptor.setURLBasePath(url: url) } } public final class HTTP: NSObject, URLSessionDelegate, JustAdaptor { var URLBasePath: String? public func setURLBasePath(url: String) { self.URLBasePath = url } public init(session: Foundation.URLSession? = nil, defaults: JustSessionDefaults? = nil) { super.init() if let initialSession = session { self.session = initialSession } else { self.session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) } if let initialDefaults = defaults { self.defaults = initialDefaults } else { self.defaults = JustSessionDefaults() } } var taskConfigs: [TaskID: TaskConfiguration]=[:] var defaults: JustSessionDefaults! var session: URLSession! var invalidURLError = NSError( domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: "[Simplr] URL is invalid"] ) var syncResultAccessError = NSError( domain: errorDomain, code: 1, userInfo: [ NSLocalizedDescriptionKey: "[Simplr] You are accessing asynchronous result synchronously." ] ) func queryComponents(_ key: String, _ value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [Any] { for value in array { components += queryComponents("\(key)", value) } } else { components.append(( percentEncodeString(key), percentEncodeString("\(value)")) ) } return components } func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sorted(by: <) { let value: Any! = parameters[key] components += self.queryComponents(key, value) } return (components.map{"\($0)=\($1)"} as [String]).joined(separator: "&") } func percentEncodeString(_ originalObject: Any) -> String { if originalObject is NSNull { return "null" } else { var reserved = CharacterSet.urlQueryAllowed reserved.remove(charactersIn: ": #[]@!$&'()*+, ;=") return String(describing: originalObject) .addingPercentEncoding(withAllowedCharacters: reserved) ?? "" } } func makeTask(_ request: URLRequest, configuration: TaskConfiguration) -> URLSessionDataTask? { let task = session.dataTask(with: request) taskConfigs[task.taskIdentifier] = configuration return task } func synthesizeMultipartBody(_ data: [String: Any], files: [String: HTTPFile]) -> Data? { var body = Data() let boundary = "--\(self.defaults.multipartBoundary)\r\n" .data(using: defaults.encoding)! for (k, v) in data { let valueToSend: Any = v is NSNull ? "null" : v body.append(boundary) body.append("Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n" .data(using: defaults.encoding)!) body.append("\(valueToSend)\r\n".data(using: defaults.encoding)!) } for (k, v) in files { body.append(boundary) var partContent: Data? = nil var partFilename: String? = nil var partMimetype: String? = nil switch v { case let .url(URL, mimetype): partFilename = URL.lastPathComponent if let URLContent = try? Data(contentsOf: URL) { partContent = URLContent } partMimetype = mimetype case let .text(filename, text, mimetype): partFilename = filename if let textData = text.data(using: defaults.encoding) { partContent = textData } partMimetype = mimetype case let .data(filename, data, mimetype): partFilename = filename partContent = data partMimetype = mimetype } if let content = partContent, let filename = partFilename { let dispose = "Content-Disposition: form-data; name=\"\(k)\"; filename=\"\(filename)\"\r\n" body.append(dispose.data(using: defaults.encoding)!) if let type = partMimetype { body.append( "Content-Type: \(type)\r\n\r\n".data(using: defaults.encoding)!) } else { body.append("\r\n".data(using: defaults.encoding)!) } body.append(content) body.append("\r\n".data(using: defaults.encoding)!) } } if body.count > 0 { body.append("--\(self.defaults.multipartBoundary)--\r\n" .data(using: defaults.encoding)!) } return body } public func synthesizeRequest( _ method: HTTPMethod, URLString: String, params: [String: Any], data: [String: Any], json: Any?, headers: CaseInsensitiveDictionary<String, String>, files: [String: HTTPFile], auth: Credentials?, timeout: Double?, URLQuery: String?, requestBody: Data? ) -> URLRequest? { if let urlComponent = NSURLComponents(string: URLString) { let queryString = query(params) if queryString.characters.count > 0 { urlComponent.percentEncodedQuery = queryString } var finalHeaders = headers var contentType: String? = nil var body: Data? if let requestData = requestBody { body = requestData } else if files.count > 0 { body = synthesizeMultipartBody(data, files: files) let bound = self.defaults.multipartBoundary contentType = "multipart/form-data; boundary=\(bound)" } else { if let requestJSON = json { contentType = "application/json" body = try? JSONSerialization.data(withJSONObject: requestJSON, options: defaults.JSONWritingOptions) } else { if data.count > 0 { // assume user wants JSON if she is using this header if headers["content-type"]?.lowercased() == "application/json" { body = try? JSONSerialization.data(withJSONObject: data, options: defaults.JSONWritingOptions) } else { contentType = "application/x-www-form-urlencoded" body = query(data).data(using: defaults.encoding) } } } } if let contentTypeValue = contentType { finalHeaders["Content-Type"] = contentTypeValue } if let auth = auth, let utf8 = "\(auth.0):\(auth.1)".data(using: String.Encoding.utf8) { finalHeaders["Authorization"] = "Basic \(utf8.base64EncodedString())" } if let URL = urlComponent.url { var request = URLRequest(url: URL) request.cachePolicy = defaults.cachePolicy request.httpBody = body request.httpMethod = method.rawValue if let requestTimeout = timeout { request.timeoutInterval = requestTimeout } for (k, v) in defaults.headers { request.addValue(v, forHTTPHeaderField: k) } for (k, v) in finalHeaders { request.addValue(v, forHTTPHeaderField: k) } return request as URLRequest } } return nil } public func request( _ method: HTTPMethod, URLString: String, params: [String: Any], data: [String: Any], json: Any?, headers: [String: String], files: [String: HTTPFile], auth: Credentials?, cookies: [String: String], redirects: Bool, timeout: Double?, URLQuery: String?, requestBody: Data?, asyncProgressHandler: TaskProgressHandler?, asyncCompletionHandler: ((HTTPResult) -> Void)?) -> HTTPResult { var url : String = URLString if(self.URLBasePath != nil) { url = self.URLBasePath! + url } let isSynchronous = asyncCompletionHandler == nil let semaphore = DispatchSemaphore(value: 0) var requestResult: HTTPResult = HTTPResult(data: nil, response: nil, error: syncResultAccessError, task: nil) let caseInsensitiveHeaders = CaseInsensitiveDictionary<String, String>( dictionary: headers) guard let request = synthesizeRequest(method, URLString: url, params: params, data: data, json: json, headers: caseInsensitiveHeaders, files: files, auth: auth, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody) else { let erronousResult = HTTPResult(data: nil, response: nil, error: invalidURLError, task: nil) if let handler = asyncCompletionHandler { handler(erronousResult) } return erronousResult } addCookies(request.url!, newCookies: cookies) let config = TaskConfiguration( credential: auth, redirects: redirects, originalRequest: request, data: NSMutableData(), progressHandler: asyncProgressHandler) { result in if let handler = asyncCompletionHandler { handler(result) } if isSynchronous { requestResult = result semaphore.signal() } } if let task = makeTask(request, configuration: config) { task.resume() } if isSynchronous { let timeout = timeout.flatMap { DispatchTime.now() + $0 } ?? DispatchTime.distantFuture _ = semaphore.wait(timeout: timeout) return requestResult } return requestResult } func addCookies(_ URL: Foundation.URL, newCookies: [String: String]) { for (k, v) in newCookies { if let cookie = HTTPCookie(properties: [ HTTPCookiePropertyKey.name: k, HTTPCookiePropertyKey.value: v, HTTPCookiePropertyKey.originURL: URL, HTTPCookiePropertyKey.path: "/" ]) { session.configuration.httpCookieStorage?.setCookie(cookie) } } } } extension HTTP: URLSessionTaskDelegate, URLSessionDataDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var endCredential: URLCredential? = nil if let taskConfig = taskConfigs[task.taskIdentifier], let credential = taskConfig.credential { if !(challenge.previousFailureCount > 0) { endCredential = URLCredential( user: credential.0, password: credential.1, persistence: self.defaults.credentialPersistence ) } } completionHandler(.useCredential, endCredential) } public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { if let allowRedirects = taskConfigs[task.taskIdentifier]?.redirects { if !allowRedirects { completionHandler(nil) return } completionHandler(request) } else { completionHandler(request) } } public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let handler = taskConfigs[task.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .upload, bytesProcessed: totalBytesSent, bytesExpectedToProcess: totalBytesExpectedToSend, chunk: nil ) ) } } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if let handler = taskConfigs[dataTask.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .download, bytesProcessed: dataTask.countOfBytesReceived, bytesExpectedToProcess: dataTask.countOfBytesExpectedToReceive, chunk: data ) ) } if taskConfigs[dataTask.taskIdentifier]?.data != nil { taskConfigs[dataTask.taskIdentifier]?.data.append(data) } } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let config = taskConfigs[task.taskIdentifier], let handler = config.completionHandler { let result = HTTPResult( data: config.data as Data, response: task.response, error: error, task: task ) result.JSONReadingOptions = self.defaults.JSONReadingOptions result.encoding = self.defaults.encoding handler(result) } taskConfigs.removeValue(forKey: task.taskIdentifier) } } // // End of Just Http code // public let Simplr = JustOf<HTTP>() public extension String { @discardableResult func get( params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.get(self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } @discardableResult func post( params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.post(self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } @discardableResult func put( params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.put(self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } @discardableResult func patch( params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.patch(self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } @discardableResult func delete( params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.delete(self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } @discardableResult func head( params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.head(self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } @discardableResult func options( params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.options(self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } @discardableResult func httpRequest( _ method: HTTPMethod, params: [String: Any] = [:], data: [String: Any] = [:], json: Any? = nil, headers: [String: String] = [:], files: [String: HTTPFile] = [:], auth: (String, String)? = nil, cookies: [String: String] = [:], allowRedirects: Bool = true, timeout: Double? = nil, URLQuery: String? = nil, requestBody: Data? = nil, asyncProgressHandler: (TaskProgressHandler)? = nil, asyncCompletionHandler: ((HTTPResult) -> Void)? = nil ) -> HTTPResult { return Simplr.request(method, URLString: self, params: params, data: data, json: json, headers: headers, files: files, auth: auth, cookies: cookies, allowRedirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler) } }
mit
580c056b12584ba9c82d02bf4f07d619
29.860255
344
0.632453
4.548726
false
false
false
false
edwardchao/MovingHelper
MovingHelperTests/TaskCellTests.swift
1
2907
// // TaskCellTests.swift // MovingHelper // // Created by Edward on 9/15/15. // Copyright (c) 2015 Razeware. All rights reserved. // import UIKit import XCTest import MovingHelper class TaskCellTests: XCTestCase { func testCheckingCheckboxMarksTaskDone() { var testCell: TaskTableViewCell? let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) if let navVC = mainStoryboard.instantiateInitialViewController() as? UINavigationController, listVC = navVC.topViewController as? MasterViewController { let tasks = TaskLoader.loadStockTasks() listVC.createdMovingTasks(tasks) testCell = listVC.tableView(listVC.tableView, cellForRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as? TaskTableViewCell if let cell = testCell { //1 let expectation = expectationWithDescription("Task updated") //2 struct TestDelegate: TaskUpdatedDelegate { let testExpectation: XCTestExpectation let expectedDone: Bool init(updatedExpectation: XCTestExpectation, expectedDoneStateAfterToggle: Bool) { testExpectation = updatedExpectation expectedDone = expectedDoneStateAfterToggle } func taskUpdated(task: Task) { XCTAssertEqual(expectedDone, task.done, "Task done state did not match expected!") testExpectation.fulfill() } } //3 let testTask = Task(aTitle: "TestTask", aDueDate: .OneMonthAfter) XCTAssertFalse(testTask.done, "Newly created task is already done!") cell.delegate = TestDelegate(updatedExpectation: expectation, expectedDoneStateAfterToggle: true) cell.configureForTask(testTask) //4 XCTAssertFalse(cell.checkbox.isChecked, "Checkbox checked for not-done task!") //5 cell.checkbox.sendActionsForControlEvents(.TouchUpInside) //6 XCTAssertTrue(cell.checkbox.isChecked, "Checkbox not checked after tap!") waitForExpectationsWithTimeout(1, handler: nil) } else { XCTFail("Test cell was nil!") } } else { XCTFail("Could not get reference to list VC!") } } }
mit
a76f0b39303399f16a58647c9161be89
41.764706
110
0.511524
6.636986
false
true
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/Utility/SavableImage.swift
1
4919
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Photos import WireSystem import WireUtilities import UIKit protocol PhotoLibraryProtocol { func performChanges(_ changeBlock: @escaping () -> Swift.Void, completionHandler: ((Bool, Error?) -> Swift.Void)?) func register(_ observer: PHPhotoLibraryChangeObserver) func unregisterChangeObserver(_ observer: PHPhotoLibraryChangeObserver) } extension PHPhotoLibrary: PhotoLibraryProtocol {} protocol AssetChangeRequestProtocol: AnyObject { @discardableResult static func creationRequestForAsset(from image: UIImage) -> Self @discardableResult static func creationRequestForAssetFromImage(atFileURL fileURL: URL) -> Self? } protocol AssetCreationRequestProtocol: AnyObject { static func forAsset() -> Self func addResource(with type: PHAssetResourceType, data: Data, options: PHAssetResourceCreationOptions?) } extension PHAssetChangeRequest: AssetChangeRequestProtocol {} extension PHAssetCreationRequest: AssetCreationRequestProtocol {} private let log = ZMSLog(tag: "SavableImage") final class SavableImage: NSObject { enum Source { case gif(URL) case image(Data) } /// Protocols used to inject mock photo services in tests var photoLibrary: PhotoLibraryProtocol = PHPhotoLibrary.shared() var assetChangeRequestType: AssetChangeRequestProtocol.Type = PHAssetChangeRequest.self var assetCreationRequestType: AssetCreationRequestProtocol.Type = PHAssetCreationRequest.self var applicationType: ApplicationProtocol.Type = UIApplication.self typealias ImageSaveCompletion = (Bool) -> Void private var writeInProgess = false private let imageData: Data private let isGIF: Bool init(data: Data, isGIF: Bool) { self.isGIF = isGIF imageData = data super.init() } private static func storeGIF(_ data: Data) -> URL { let url = URL(fileURLWithPath: NSTemporaryDirectory() + "\(UUID().uuidString).gif") do { try data.write(to: url, options: .atomic) } catch { log.error("error writing image data to \(url): \(error)") } return url } // SavableImage instances get created when image cells etc are being created and // we don't want to write data to disk when we didn't start a save operation, yet. private func createSource() -> Source { return isGIF ? .gif(SavableImage.storeGIF(imageData)) : .image(imageData) } public func saveToLibrary(withCompletion completion: ImageSaveCompletion? = .none) { guard !writeInProgess else { return } writeInProgess = true let source = createSource() let cleanup: (Bool) -> Void = { [source] success in if case .gif(let url) = source { try? FileManager.default.removeItem(at: url) } completion?(success) } applicationType.wr_requestOrWarnAboutPhotoLibraryAccess { granted in guard granted else { return cleanup(false) } self.photoLibrary.performChanges(papply(self.saveImage, source)) { success, error in DispatchQueue.main.async { self.writeInProgess = false error.apply(self.warnAboutError) cleanup(success) } } } } // Has to be called from inside a `photoLibrary.perform` block private func saveImage(using source: Source) { switch source { case .gif(let url): _ = assetChangeRequestType.creationRequestForAssetFromImage(atFileURL: url) case .image(let data): assetCreationRequestType.forAsset().addResource(with: .photo, data: data, options: PHAssetResourceCreationOptions()) } } private func warnAboutError(_ error: Error) { log.error("error saving image: \(error)") let alert = UIAlertController( title: "library.alert.permission_warning.title".localized, message: (error as NSError).localizedDescription, alertAction: .ok(style: .cancel)) AppDelegate.shared.window?.rootViewController?.present(alert, animated: true) } }
gpl-3.0
b636807b22546919d6d62e7e5d897465
34.135714
128
0.677373
4.780369
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Extensions/DevicePickerViewController.swift
2
12263
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit import Shared import Storage import SnapKit import Account import SwiftUI protocol DevicePickerViewControllerDelegate: AnyObject { func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) } private enum LoadingState { case loading case loaded } public enum ClientType: String { case Desktop = "deviceTypeDesktop" case Mobile = "deviceTypeMobile" case Tablet = "deviceTypeTablet" case VR = "deviceTypeVR" case TV = "deviceTypeTV" static func fromFxAType(_ type: String?) -> ClientType { switch type { case "desktop": return ClientType.Desktop case "mobile": return ClientType.Mobile case "tablet": return ClientType.Tablet case "vr": return ClientType.VR case "tv": return ClientType.TV default: return ClientType.Mobile } } } class DevicePickerViewController: UITableViewController { private struct UX { static let tableHeaderRowHeight: CGFloat = 50 static let deviceRowHeight: CGFloat = 50 } private var devices = [RemoteDevice]() var profile: Profile? var profileNeedsShutdown = true var pickerDelegate: DevicePickerViewControllerDelegate? private var selectedIdentifiers = Set<String>() // Stores Device.id private var notification: Any? private var loadingState = LoadingState.loading // ShareItem has been added as we are now using this class outside of the ShareTo extension to // provide Share To functionality // And in this case we need to be able to store the item we are sharing as we may not have access to the // url later. Currently used only when sharing an item from the Tab Tray from a Preview Action. var shareItem: ShareItem? override func viewDidLoad() { super.viewDidLoad() title = .SendToTitle refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refresh), for: .valueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem( title: .SendToCancelButton, style: .plain, target: self, action: #selector(cancel) ) tableView.register(DevicePickerTableViewHeaderCell.self, forCellReuseIdentifier: DevicePickerTableViewHeaderCell.cellIdentifier) tableView.register(DevicePickerTableViewCell.self, forCellReuseIdentifier: DevicePickerTableViewCell.cellIdentifier) tableView.register(HostingTableViewCell<HelpView>.self, forCellReuseIdentifier: HostingTableViewCell<HelpView>.cellIdentifier) tableView.tableFooterView = UIView(frame: .zero) tableView.allowsSelection = true notification = NotificationCenter.default.addObserver(forName: Notification.Name.constellationStateUpdate, object: nil, queue: .main) { [weak self ] _ in self?.loadList() self?.refreshControl?.endRefreshing() } let profile = ensureOpenProfile() RustFirefoxAccounts.startup(prefs: profile.prefs).uponQueue(.main) { accountManager in accountManager.deviceConstellation()?.refreshState() } loadList() } deinit { if let obj = notification { NotificationCenter.default.removeObserver(obj) } } private func loadList() { let profile = ensureOpenProfile() RustFirefoxAccounts.startup(prefs: profile.prefs).uponQueue(.main) { [weak self] accountManager in guard let state = accountManager.deviceConstellation()?.state() else { self?.loadingState = .loaded return } guard let self = self else { return } let currentIds = self.devices.map { $0.id ?? "" }.sorted() let newIds = state.remoteDevices.map { $0.id }.sorted() if !currentIds.isEmpty, currentIds == newIds { return } self.devices = state.remoteDevices.map { device in let typeString = "\(device.deviceType)" let lastAccessTime = device.lastAccessTime == nil ? nil : UInt64(clamping: device.lastAccessTime!) return RemoteDevice(id: device.id, name: device.displayName, type: typeString, isCurrentDevice: device.isCurrentDevice, lastAccessTime: lastAccessTime, availableCommands: nil) } if self.devices.isEmpty { self.navigationItem.rightBarButtonItem = nil } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: .SendToSendButtonTitle, style: .done, target: self, action: #selector(self.send)) self.navigationItem.rightBarButtonItem?.isEnabled = false } self.loadingState = .loaded self.tableView.reloadData() } } override func numberOfSections(in tableView: UITableView) -> Int { if devices.isEmpty { return 1 } else { return 2 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if devices.isEmpty { return 1 } else { if section == 0 { return 1 } else { return devices.count } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? if !devices.isEmpty { if indexPath.section == 0 { cell = tableView.dequeueReusableCell(withIdentifier: DevicePickerTableViewHeaderCell.cellIdentifier, for: indexPath) as? DevicePickerTableViewHeaderCell } else if let clientCell = tableView.dequeueReusableCell( withIdentifier: DevicePickerTableViewCell.cellIdentifier, for: indexPath) as? DevicePickerTableViewCell { let item = devices[indexPath.row] clientCell.nameLabel.text = item.name clientCell.clientType = ClientType.fromFxAType(item.type) if let id = item.id { clientCell.checked = selectedIdentifiers.contains(id) } cell = clientCell } } else { if loadingState == .loaded, let hostingCell = tableView.dequeueReusableCell( withIdentifier: HostingTableViewCell<HelpView>.cellIdentifier) as? HostingTableViewCell<HelpView> { #if MOZ_TARGET_SHARETO let textColor = ShareTheme.textColor.color let imageColor = ShareTheme.iconColor.color #else let themeManager: ThemeManager = AppContainer.shared.resolve() let textColor = themeManager.currentTheme.colors.textPrimary let imageColor = themeManager.currentTheme.colors.iconPrimary #endif let emptyView = HelpView(textColor: textColor, imageColor: imageColor, topMessage: String.SendToNoDevicesFound, bottomMessage: nil) hostingCell.host(emptyView, parentController: self) // Move the separator off screen hostingCell.separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) cell = hostingCell } } return cell ?? UITableViewCell(style: .default, reuseIdentifier: "ClientCell") } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return indexPath.section != 0 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if devices.isEmpty || indexPath.section != 1 { return } tableView.deselectRow(at: indexPath, animated: true) guard let id = devices[indexPath.row].id else { return } if selectedIdentifiers.contains(id) { selectedIdentifiers.remove(id) } else { selectedIdentifiers.insert(id) } UIView.performWithoutAnimation { // If the selected cell is off-screen when the tableview is first shown, the tableview // will re-scroll without disabling animation. tableView.reloadRows(at: [indexPath], with: .none) } navigationItem.rightBarButtonItem?.isEnabled = !selectedIdentifiers.isEmpty } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if !devices.isEmpty { if indexPath.section == 0 { return UX.tableHeaderRowHeight } else { return UX.deviceRowHeight } } else { return tableView.frame.height } } fileprivate func ensureOpenProfile() -> Profile { // If we were not given a profile, open the default profile. This happens in case we are called from an app // extension. That also means that we need to shut down the profile, otherwise the app extension will be // terminated when it goes into the background. if let profile = self.profile { // Re-open the profile if it was shutdown. This happens when we run from an app extension, where we must // make sure that the profile is only open for brief moments of time. if profile.isShutdown && Bundle.main.bundleURL.pathExtension == "appex" { profile.reopen() } return profile } let profile = BrowserProfile(localName: "profile") self.profile = profile self.profileNeedsShutdown = true return profile } @objc func refresh() { RustFirefoxAccounts.shared.accountManager.peek()?.deviceConstellation()?.refreshState() if let refreshControl = refreshControl { refreshControl.beginRefreshing() let height = -(refreshControl.bounds.size.height + (navigationController?.navigationBar.bounds.size.height ?? 0)) self.tableView.contentOffset = CGPoint(x: 0, y: height) } } @objc func cancel() { pickerDelegate?.devicePickerViewControllerDidCancel(self) } @objc func send() { var pickedItems = [RemoteDevice]() for id in selectedIdentifiers { if let item = devices.find({ $0.id == id }) { pickedItems.append(item) } } pickerDelegate?.devicePickerViewController(self, didPickDevices: pickedItems) // Replace the Send button with a loading indicator since it takes a while to sync // up our changes to the server. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(width: 25, height: 25)) loadingIndicator.color = UIColor.Photon.Grey60 loadingIndicator.startAnimating() let customBarButton = UIBarButtonItem(customView: loadingIndicator) self.navigationItem.rightBarButtonItem = customBarButton } }
mpl-2.0
ba4ab741133e9f117e74038ba997ce3f
38.814935
133
0.598385
5.656365
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Graphics/Drawing_iOS.swift
1
22252
// // Drawing_iOS.swift // LispKit // // Created by Matthias Zenger on 23/04/2021. // Copyright © 2021 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import CoreGraphics import Foundation import UIKit import MobileCoreServices /// /// Class `Drawing` represents a sequence of drawing instructions. The class offers the /// following functionality: /// - New instructions can be appended to a drawing /// - The drawing can be drawn to the current graphics context /// - The drawing can be written to a file. Natively supported are PDF, PNG, and JPEG. /// public final class Drawing: NativeObject { /// Type representing drawings. public static let type = Type.objectType(Symbol(uninterned: "drawing")) /// The sequence of drawing instructions. public private(set) var instructions: [DrawingInstruction] /// Initializer copying another drawing. public init(copy drawing: Drawing) { self.instructions = drawing.instructions } /// Initializer providing an initial sequence of drawing instructions. public init(_ instructions: DrawingInstruction...) { self.instructions = instructions } /// Return native object type. public override var type: Type { return Self.type } /// Appends a new drawing instruction. @discardableResult public func append(_ instruction: DrawingInstruction) -> Bool { switch instruction { case .inline(let drawing), .include(let drawing, _): if drawing.includes(self) { return false } default: break } self.instructions.append(instruction) return true } /// Draws the drawing to the current graphics context clipped to a given shape. The drawing is /// put into a new transparency layer. Upon exit, the previous graphics state is being /// restored. public func draw(clippedTo shape: Shape? = nil) { if let context = UIGraphicsGetCurrentContext() { context.saveGState() context.beginTransparencyLayer(auxiliaryInfo: nil) shape?.compile().addClip() defer { context.endTransparencyLayer() context.restoreGState() } self.drawInline() } } /// Draw the drawing into the current graphics context without saving and restoring the /// graphics state. public func drawInline() { for instruction in self.instructions { instruction.draw() } } /// Returns true if the given drawing is included or inlined into this drawing. public func includes(_ drawing: Drawing) -> Bool { guard self !== drawing else { return true } for instruction in self.instructions { switch instruction { case .inline(let other), .include(let other, _): if other.includes(drawing) { return true } default: break } } return false } /// Saves the drawing into a PDF file at URL `url`. The canvas's size is provide via the /// `width` and `height` parameters. If `flipped` is set to false, it is assumed that the /// origin of the coordinate system is in the lower-left corner of the canvas with x values /// increasing to the right and y values increasing upwards. If `flipped` is set to true, /// the origin of the coordinate system is in the upper-left corner of the canvas with x values /// increasing to the right and y values increasing downwards. /// /// The optional parameters `title`, `author`, and `creator` are stored in the metadata of /// the generated PDF file. public func saveAsPDF(url: URL, width: Int, height: Int, flipped: Bool = false, title: String? = nil, author: String? = nil, creator: String? = nil) -> Bool { // First check if we can write to the URL var dir: ObjCBool = false let parent = url.deletingLastPathComponent().path guard FileManager.default.fileExists(atPath: parent, isDirectory: &dir) && dir.boolValue else { return false } guard FileManager.default.isWritableFile(atPath: parent) else { return false } // Define a media box var mediaBox = CGRect(x: 0, y: 0, width: Double(width), height: Double(height)) // Create a core graphics context suitable for drawing the image into a PDF file let pdfInfo = NSMutableDictionary() if let title = title { pdfInfo[kCGPDFContextTitle] = title } if let author = author { pdfInfo[kCGPDFContextAuthor] = author } if let creator = creator { pdfInfo[kCGPDFContextCreator] = creator } guard let context = CGContext(url as CFURL, mediaBox: &mediaBox, pdfInfo as CFDictionary) else { return false } UIGraphicsPushContext(context) defer { UIGraphicsPopContext() } // Create a new PDF page context.beginPDFPage(nil) context.saveGState() // Flip graphics if required if flipped { context.translateBy(x: 0.0, y: CGFloat(height)) context.scaleBy(x: 1.0, y: -1.0) } // Draw the image self.draw() context.restoreGState() // Close PDF page and document context.endPDFPage() context.closePDF() return true } /// Saves the drawing into a PNG file at URL `url`. The canvas's size is provide via the /// `width` and `height` parameters. The `scale` factor determines the actual size of the /// bitmap when multiplied with `width` and `height`. For instance, setting `scale` to 2.0 /// will result in a PNF file using a "Retina"/2x resolution. /// /// If `flipped` is set to false, it is assumed that the origin of the coordinate system is /// in the lower-left corner of the canvas with x values increasing to the right and y values /// increasing upwards. If `flipped` is set to true, the origin of the coordinate system is /// in the upper-left corner of the canvas with x values increasing to the right and y /// values increasing downwards. public func saveAsPNG(url: URL, width: Int, height: Int, scale: Double = 1.0, flipped: Bool = false) -> Bool { return self.saveAsBitmap(url: url, width: width, height: height, scale: scale, format: .png, flipped: flipped) } /// Saves the drawing into a JPEF file at URL `url`. The canvas's size is provide via the /// `width` and `height` parameters. The `scale` factor determines the actual size of the /// bitmap when multiplied with `width` and `height`. For instance, setting `scale` to 2.0 /// will result in a JPEG file using a "Retina"/2x resolution. /// /// If `flipped` is set to false, it is assumed that the origin of the coordinate system is /// in the lower-left corner of the canvas with x values increasing to the right and y values /// increasing upwards. If `flipped` is set to true, the origin of the coordinate system is /// in the upper-left corner of the canvas with x values increasing to the right and y /// values increasing downwards. public func saveAsJPG(url: URL, width: Int, height: Int, scale: Double = 1.0, flipped: Bool = false) -> Bool { return self.saveAsBitmap(url: url, width: width, height: height, scale: scale, format: .jpeg, flipped: flipped) } /// Saves the drawing into a file at URL `url` of format `format`. The canvas's size is /// provide via the `width` and `height` parameters. The `scale` factor determines the /// actual size of the bitmap when multiplied with `width` and `height`. For instance, /// setting `scale` to 2.0 will result in file using a "Retina"/2x resolution. /// /// If `flipped` is set to false, it is assumed that the origin of the coordinate system is /// in the lower-left corner of the canvas with x values increasing to the right and y values /// increasing upwards. If `flipped` is set to true, the origin of the coordinate system is /// in the upper-left corner of the canvas with x values increasing to the right and y /// values increasing downwards. public func saveAsBitmap(url: URL, width: Int, height: Int, scale: Double, format: BitmapImageFileType, flipped: Bool) -> Bool { // Create a bitmap suitable for storing the image in a PNG guard let context = CGContext(data: nil, width: Int(Double(width) * scale), height: Int(Double(height) * scale), bitsPerComponent: 8, bytesPerRow: 0, space: Color.colorSpaceName, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue) .union(.byteOrder32Little).rawValue) else { return false } // Create a flipped graphics context if required if flipped { context.translateBy(x: 0.0, y: CGFloat(height)) context.scaleBy(x: 1.0, y: -1.0) } UIGraphicsPushContext(context) defer { UIGraphicsPopContext() } // Draw the image self.draw() // Encode bitmap guard let image = UIGraphicsGetImageFromCurrentImageContext(), let data = format.data(for: image) else { return false } // Write encoded data into a file do { try data.write(to: url, options: .atomic) return true } catch { return false } } public func flush() { for instruction in self.instructions { instruction.markDirty() } } } /// /// Enumeration of all supported drawing instructions. /// public enum DrawingInstruction { case setStrokeColor(Color) case setFillColor(Color) case setStrokeWidth(Double) case setBlendMode(BlendMode) case setShadow(Color, dx: Double, dy: Double, blurRadius: Double) case removeShadow case setTransformation(Transformation) case concatTransformation(Transformation) case undoTransformation(Transformation) case strokeLine(CGPoint, CGPoint) case strokeRect(CGRect) case fillRect(CGRect) case strokeEllipse(CGRect) case fillEllipse(CGRect) case stroke(Shape, width: Double) case strokeDashed(Shape, width: Double, lengths: [Double], phase: Double) case fill(Shape) case fillLinearGradient(Shape, [Color], angle: Double) case fillRadialGradient(Shape, [Color], relativeCenter: CGPoint) case text(String, font: Font?, color: Color?, style: NSParagraphStyle?, at: ObjectLocation) case attributedText(NSAttributedString, at: ObjectLocation) case image(UIImage, ObjectLocation, operation: CGBlendMode, opacity: Double) case inline(Drawing) case include(Drawing, clippedTo: Shape?) fileprivate func draw() { switch self { case .setStrokeColor(let color): UIGraphicsGetCurrentContext()?.setStrokeColor(color.nsColor.cgColor) case .setFillColor(let color): UIGraphicsGetCurrentContext()?.setFillColor(color.nsColor.cgColor) case .setStrokeWidth(let width): UIGraphicsGetCurrentContext()?.setLineWidth(CGFloat(width)) case .setBlendMode(let blendMode): UIGraphicsGetCurrentContext()?.setBlendMode(blendMode) case .setShadow(let color, let dx, let dy, let blurRadius): UIGraphicsGetCurrentContext()?.setShadow(offset: CGSize(width: dx, height: dy), blur: CGFloat(blurRadius), color: color.nsColor.cgColor) case .removeShadow: UIGraphicsGetCurrentContext()?.setShadow(offset: CGSize(width: 0.0, height: 0.0), blur: 0.0, color: nil) case .setTransformation(let transformation): if let transform = UIGraphicsGetCurrentContext()?.ctm { UIGraphicsGetCurrentContext()?.concatenate(transform.inverted()) UIGraphicsGetCurrentContext()?.concatenate(transformation.affineTransform) } case .concatTransformation(let transformation): UIGraphicsGetCurrentContext()?.concatenate(transformation.affineTransform) case .undoTransformation(let transformation): UIGraphicsGetCurrentContext()?.concatenate(transformation.affineTransform.inverted()) case .strokeLine(let start, let end): if let context = UIGraphicsGetCurrentContext() { context.beginPath() context.move(to: start) context.addLine(to: end) context.strokePath() } case .strokeRect(let rct): UIGraphicsGetCurrentContext()?.stroke(rct) case .fillRect(let rct): UIGraphicsGetCurrentContext()?.fill(rct) case .strokeEllipse(let rct): UIGraphicsGetCurrentContext()?.strokeEllipse(in: rct) case .fillEllipse(let rct): UIGraphicsGetCurrentContext()?.fillEllipse(in: rct) case .stroke(let shape, let width): shape.stroke(lineWidth: width) case .strokeDashed(let shape, let width, let dashLengths, let dashPhase): shape.stroke(lineWidth: width, lineDashPhase: dashPhase, lineDashLengths: dashLengths) case .fill(let shape): shape.fill() case .fillLinearGradient(let shape, let colors, let angle): if let context = UIGraphicsGetCurrentContext(), let gradient = CGGradient(colorsSpace: Color.colorSpaceName, colors: Color.cgColorArray(colors) as CFArray, locations: nil) { context.saveGState() context.addPath(shape.compile().cgPath) context.closePath() context.clip() context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: cos(angle), y: sin(angle)), options: []) context.restoreGState() } case .fillRadialGradient(let shape, let colors, let center): if let context = UIGraphicsGetCurrentContext(), let gradient = CGGradient(colorsSpace: Color.colorSpaceName, colors: Color.cgColorArray(colors) as CFArray, locations: nil) { context.saveGState() let path = shape.compile() context.addPath(path.cgPath) context.closePath() context.clip() let bounds = path.bounds var radius = abs(center.distance(to: CGPoint(x: bounds.minX, y: bounds.minY))) var r = abs(center.distance(to: CGPoint(x: bounds.minX, y: bounds.maxY))) if r > radius { radius = r } r = abs(center.distance(to: CGPoint(x: bounds.maxX, y: bounds.minY))) if r > radius { radius = r } r = abs(center.distance(to: CGPoint(x: bounds.maxX, y: bounds.maxY))) if r > radius { radius = r } context.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: radius, options: []) context.restoreGState() } case .text(let str, let font, let color, let paragraphStyle, let location): let pstyle: NSParagraphStyle if let style = paragraphStyle { pstyle = style } else { // let style = NSMutableParagraphStyle() // style.alignment = .left // pstyle = style pstyle = .default } let attributes = [ .font: font ?? Font.systemFont(ofSize: Font.systemFontSize), .foregroundColor: (color ?? Color.black).nsColor, .paragraphStyle: pstyle, ] as [NSAttributedString.Key: Any] let textRect: CGRect switch location { case .position(let point): textRect = CGRect(x: point.x, y: point.y, width: CGFloat.infinity, height: CGFloat.infinity) case .boundingBox(let box): textRect = box } str.draw(with: textRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil) case .attributedText(let attribStr, let location): let textRect: CGRect switch location { case .position(let point): textRect = CGRect(x: point.x, y: point.y, width: CGFloat.infinity, height: CGFloat.infinity) case .boundingBox(let box): textRect = box } attribStr.draw(with: textRect, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) case .image(let image, let location, let oper, let opa): switch location { case .position(let point): image.draw(at: CGPoint(x: point.x, y: point.y), blendMode: oper, alpha: CGFloat(opa)) case .boundingBox(let box): image.draw(in: box, blendMode: oper, alpha: CGFloat(opa)) } case .include(let drawing, let clippingRegion): drawing.draw(clippedTo: clippingRegion) case .inline(let drawing): drawing.drawInline() } } func markDirty() { switch self { case .stroke(let shape, _): shape.markDirty() case .strokeDashed(let shape, _, _, _): shape.markDirty() case .fill(let shape): shape.markDirty() case .fillLinearGradient(let shape, _, _): shape.markDirty() case .fillRadialGradient(let shape, _, _): shape.markDirty() default: break } } } /// /// Enumeration of all supported blend modes. /// public typealias BlendMode = CGBlendMode /// /// Enumeration of all supported object locations. /// public enum ObjectLocation { case position(CGPoint) case boundingBox(CGRect) } public enum BitmapImageFileType { case tiff case bmp case gif case jpeg case png func data(for image: UIImage) -> Data? { guard let cgImage = image.cgImage else { return nil } switch self { case .tiff: let tiffOptions: Dictionary<String, Int> = [ kCGImagePropertyTIFFCompression as String: 4 ] let options: NSDictionary = [ kCGImagePropertyTIFFDictionary as String : tiffOptions, // kCGImagePropertyDepth as String : 1, kCGImagePropertyDPIWidth as String : Int(CGFloat(cgImage.width)*72.0/image.size.width), kCGImagePropertyDPIHeight as String : Int(CGFloat(cgImage.height)*72.0/image.size.height), kCGImagePropertyColorModel as String : kCGImagePropertyColorModelRGB as String, kCGImagePropertyOrientation as String : NSNumber(value: image.imageOrientation.rawValue) ] let md = NSMutableData() guard let dest = CGImageDestinationCreateWithData(md, kUTTypeTIFF, 1, nil) else { return nil } CGImageDestinationAddImage(dest, cgImage, options) CGImageDestinationFinalize(dest) return md as Data case .bmp: let options: NSDictionary = [ kCGImagePropertyDPIWidth as String : Int(CGFloat(cgImage.width)*72.0/image.size.width), kCGImagePropertyDPIHeight as String : Int(CGFloat(cgImage.height)*72.0/image.size.height), kCGImagePropertyColorModel as String : kCGImagePropertyColorModelRGB as String, kCGImagePropertyHasAlpha as String: NSNumber(value: true), kCGImagePropertyOrientation as String : NSNumber(value: image.imageOrientation.rawValue) ] let md = NSMutableData() guard let dest = CGImageDestinationCreateWithData(md, kUTTypeBMP, 1, nil) else { return nil } CGImageDestinationAddImage(dest, cgImage, options) CGImageDestinationFinalize(dest) return md as Data case .gif: let options: NSDictionary = [ kCGImagePropertyDPIWidth as String : Int(CGFloat(cgImage.width)*72.0/image.size.width), kCGImagePropertyDPIHeight as String : Int(CGFloat(cgImage.height)*72.0/image.size.height), kCGImagePropertyColorModel as String : kCGImagePropertyColorModelRGB as String, kCGImagePropertyOrientation as String : NSNumber(value: image.imageOrientation.rawValue) ] let md = NSMutableData() guard let dest = CGImageDestinationCreateWithData(md, kUTTypeGIF, 1, nil) else { return nil } CGImageDestinationAddImage(dest, cgImage, options) CGImageDestinationFinalize(dest) return md as Data case .jpeg: return image.jpegData(compressionQuality: 0.8) case .png: return image.pngData() } } } extension CGPoint { func distance(to point: CGPoint) -> CGFloat { return sqrt(pow((point.x - x), 2) + pow((point.y - y), 2)) } }
apache-2.0
8506f96bd7f9e0ab110772d16801a5bc
38.733929
100
0.61422
4.828776
false
false
false
false
LYM-mg/DemoTest
indexView/indexView/One/TableView的头部展开与折叠/Controller/XJLOccupationViewController.swift
1
4811
// // XJLOccupationViewController.swift // OccupationClassify // // Created by 许佳莉 on 2017/3/24. // Copyright © 2017年 MESMKEE. All rights reserved. // import UIKit import Alamofire class XJLOccupationViewController: UITableViewController { // 数据源 fileprivate lazy var occupationDict = [XJLGroupModel]() fileprivate lazy var hearderSection: NSInteger = 0 var isSame: Bool = false //: XJLHeaderFooterView = XJLHeaderFooterView() override func viewDidLoad() { super.viewDidLoad() self.title = "职业列表" tableView.tableFooterView = UIView() tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "TableViewCellID") tableView.register(XJLHeaderFooterView.classForCoder(), forHeaderFooterViewReuseIdentifier: "HeaderFooterViewID") loadData() } func loadData() { // // http://api.shikee.tv/common/Occupation/index Alamofire.request("http://api.shikee.tv/common/Occupation/index").responseJSON { (response) in guard let dict = response.result.value as? [String: Any] else { return } guard let dictArr = dict["data"] as? [[String: Any]] else { return } var resultArr:[[String: Any]] = [[String: Any]]() var lastIid: Int = 0 for model in dictArr { let iid = Int(model["iid"]! as! String)! if lastIid == iid { continue } var arr = [Any]() for dict in dictArr{ if iid == (dict["iid"]! as AnyObject).intValue { arr.append(dict) } } let dictionary:[String: Any] = ["group": arr] resultArr.append(dictionary) lastIid = iid } for model in resultArr { self.occupationDict.append(XJLGroupModel(dict: model)) } self.tableView.reloadData() } } } // MARK: - Table view data source extension XJLOccupationViewController { override func numberOfSections(in tableView: UITableView) -> Int { return occupationDict.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let group = occupationDict[section] // return group.models.count // return group.models.count; return group.isExpaned == false ? 0 : group.models.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellID", for: indexPath) let group = occupationDict[indexPath.section] let model = group.models[indexPath.row] cell.textLabel?.text = model.name return cell } } // MARK: - UITableViewDelegate extension XJLOccupationViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderFooterViewID") as! XJLHeaderFooterView // 回调 headerView.gruop = occupationDict[section] var tempHearderView: XJLHeaderFooterView? headerView.btnBlock = { [unowned self](gruop: XJLGroupModel,hearderView: XJLHeaderFooterView) in self.tableView.beginUpdates() self.tableView.reloadSections(IndexSet(integer: self.hearderSection), with: .automatic) self.tableView.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic) self.tableView.endUpdates() tempHearderView = hearderView if (section == self.hearderSection && !self.isSame) { self.isSame = true gruop.isExpaned = !gruop.isExpaned self.hearderSection = section self.occupationDict[section] = gruop; self.tableView.reloadData() return; } self.isSame = false self.hearderSection = section tempHearderView!.gruop?.isExpaned = false // // // if (self.hearderSection == section) { // // }else { // // } // // self.tableView.reloadData() } return headerView } }
mit
f713c29d6a25ea05802285c15a4b55f8
32.929078
128
0.592391
4.774451
false
false
false
false
programersun/HiChongSwift
HiChongSwift/AboutMeSettingViewController.swift
1
7195
// // AboutMeSettingViewController.swift // HiChongSwift // // Created by eagle on 15/1/12. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit class AboutMeSettingViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() navigationItem.title = "设置" tableView.backgroundColor = UIColor.LCYThemeColor() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. switch section { case 0: return 1 case 1: // return 6 return 5 default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... switch indexPath.section { case 0: cell.textLabel?.text = "忘记密码" case 1: switch indexPath.row { case 0: cell.textLabel?.text = "用户帮助" case 1: cell.textLabel?.text = "用户协议" case 2: cell.textLabel?.text = "意见反馈" case 3: cell.textLabel?.text = "打分支持" case 4: // cell.textLabel?.text = "版本升级" // case 5: cell.textLabel?.text = "退出账号" default: break } default: break } switch indexPath.row % 2 { case 0: cell.backgroundColor = UIColor.LCYTableLightBlue() case 1: cell.backgroundColor = UIColor.LCYTableLightGray() default: break } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: // 忘记密码 let storyboard = UIStoryboard(name: "Login", bundle: nil) let viewController = storyboard.instantiateViewControllerWithIdentifier("reset") as! ForgetPasswordViewController viewController.lockPhoneNumber = true navigationController?.pushViewController(viewController, animated: true) case 1: switch indexPath.row { case 0: // 用户帮助 performSegueWithIdentifier("showHelp", sender: nil) case 1: // 使用协议 performSegueWithIdentifier("showAgreement", sender: nil) case 2: // 意见反馈 performSegueWithIdentifier("showFeedback", sender: nil) case 3: // 打分支持 let URLString = "https://itunes.apple.com/cn/app/hai-chong-chong-wu/id918809824?l=zh&ls=1&mt=8" UIApplication.sharedApplication().openURL(NSURL(string: URLString)!) case 4: // // 版本升级 // let URLString = "http://itunes.apple.com/cn/lookup?id=918809824" // if let URL = NSURL(string: URLString) { // if let jsonData = NSData(contentsOfURL: URL) { // if let jsonObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions(0), error: nil) as? [String: AnyObject] { // if let version = (((jsonObject["results"] as? NSArray)?[0] as? NSDictionary)?["version"] as? String) { // if let localVersion = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String { // let remoteSep = version.componentsSeparatedByString(".") // let localSep = localVersion.componentsSeparatedByString(".") // if remoteSep.first?.toInt() > localSep.first?.toInt() { // // 有升级版 // let URLString = "https://itunes.apple.com/cn/app/hai-chong-chong-wu/id918809824?l=zh&ls=1&mt=8" // UIApplication.sharedApplication().openURL(NSURL(string: URLString)!) // break // } else if (remoteSep[0].toInt() == localSep[0].toInt()) && (remoteSep[1].toInt() > localSep[1].toInt()) { // // 有升级版 // let URLString = "https://itunes.apple.com/cn/app/hai-chong-chong-wu/id918809824?l=zh&ls=1&mt=8" // UIApplication.sharedApplication().openURL(NSURL(string: URLString)!) // break // } // } // } // } // } // } // alert("没有更新的版本哦~") // case 5: // 退出账号 let alertView = UIAlertView(title: "", message: "您确定要退出吗", delegate: self, cancelButtonTitle: "确定", otherButtonTitles: "取消") alertView.tag = 3000 alertView.show() default: break } default: break } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ } extension AboutMeSettingViewController: UIAlertViewDelegate { func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if alertView.tag == 3000 { if buttonIndex == 0 { LCYCommon.sharedInstance.logout() } } } }
apache-2.0
92799aa0361d931e0abfa9b43b481551
37.961111
166
0.533153
5.249251
false
false
false
false
LbfAiYxx/douyuTV
DouYu/DouYu/Classes/Tools/Extension/UIBarButtonItem+extension.swift
1
896
// // UIBarButtonItem+extension.swift // DouYu // // Created by 刘冰峰 on 2016/12/14. // Copyright © 2016年 LBF. All rights reserved. // import UIKit extension UIBarButtonItem{ //便利构造函数快速创建 convenience init(normalImageName:String, hightImageName: String = "", frame:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)){ //创建按钮 let btn = UIButton() //设置按钮 btn.setImage(UIImage.init(named: normalImageName), for: .normal) //判断会否有参数 if hightImageName != "" { btn.setImage(UIImage.init(named: hightImageName), for: .highlighted) } if frame != CGRect(x: 0, y: 0, width: 0, height: 0) { btn.frame = frame }else{ btn.sizeToFit() } //初始化UIBarButtonItem self.init(customView:btn) } }
mit
e47275fb64a6e3b4e5c243608af053ea
23.441176
130
0.570397
3.777273
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Routing/About App Flow/AboutAppFlow.swift
1
4208
// // AboutAppFlow.swift // NearbyWeather // // Created by Erik Maximilian Martens on 11.03.22. // Copyright © 2022 Erik Maximilian Martens. All rights reserved. // import RxFlow import Swinject import MessageUI // MARK: - Dependencies extension AboutAppFlow { struct Dependencies { let flowPresentationStyle: FlowPresentationStyle let endingStep: Step let dependencyContainer: Container } } // MARK: - Class Definition final class AboutAppFlow: Flow { // MARK: - Assets var root: Presentable { rootViewController } lazy var rootViewController: UINavigationController = { switch dependencies.flowPresentationStyle { case let .pushed(rootViewController): return rootViewController case .presented: return Factory.NavigationController.make(fromType: .standard) } }() // MARK: - Properties private let mailComposeViewControllerDelegateHelper = MailComposeViewControllerDelegateHelper() // MARK: - Dependencies private let dependencies: Dependencies // MARK: - Initialization init(dependencies: Dependencies) { self.dependencies = dependencies } deinit { printDebugMessage( domain: String(describing: self), message: "was deinitialized", type: .info ) } // MARK: - Functions func navigate(to step: Step) -> FlowContributors { guard let step = step as? AboutAppStep else { return .none } switch step { case .aboutApp: return summonAboutAppViewController() case let .sendEmail(recipients, subject, message): return summonEmailComposeSheet(recipients: recipients, subject: subject, message: message) case let .safariViewController(url): return summonSafariViewController(with: url) case let .externalApp(url): return summonExternalApp(with: url) case .end: return endAboutAppFlow() } } } // MARK: - Summoning Functions private extension AboutAppFlow { func summonAboutAppViewController() -> FlowContributors { let aboutAppViewController = AboutAppViewController(dependencies: AboutAppViewModel.Dependencies( weatherStationService: dependencies.dependencyContainer.resolve(WeatherStationService.self)!, preferencesService: dependencies.dependencyContainer.resolve(PreferencesService.self)! )) switch dependencies.flowPresentationStyle { case .pushed: rootViewController.pushViewController(aboutAppViewController, animated: true) case .presented: rootViewController.setViewControllers([aboutAppViewController], animated: false) } return .one(flowContributor: .contribute(withNextPresentable: aboutAppViewController, withNextStepper: aboutAppViewController.viewModel)) } func summonEmailComposeSheet(recipients: [String], subject: String, message: String) -> FlowContributors { guard MFMailComposeViewController.canSendMail() else { return .none // TODO: tell user needs to set up a mail account } let mailController = MFMailComposeViewController() mailController.mailComposeDelegate = mailComposeViewControllerDelegateHelper mailController.setToRecipients(recipients) mailController.setSubject(subject) mailController.setMessageBody(message, isHTML: false) rootViewController.present(mailController, animated: true, completion: nil) return .none } func summonSafariViewController(with url: URL) -> FlowContributors { rootViewController.presentSafariViewController(for: url) return .none } func summonExternalApp(with url: URL) -> FlowContributors { UIApplication.shared.open(url, completionHandler: nil) return .none } func endAboutAppFlow() -> FlowContributors { .end(forwardToParentFlowWithStep: dependencies.endingStep) } } // MARK: - Helper Extensions private class MailComposeViewControllerDelegateHelper: NSObject {} extension MailComposeViewControllerDelegateHelper: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
mit
c9485a3fd0f06bea02b4870a6f9329df
28.215278
141
0.738056
5.05649
false
false
false
false
Dax220/Swifty_HTTP
SwiftyHttp/SHUploadRequest.swift
2
1423
// // SHUploadRequest.swift // SwiftyHttp // // Created by Максим on 18.08.17. // Copyright © 2017 Maks. All rights reserved. // import Foundation open class SHUploadRequest: SHRequest { public var success: UploadCompletion? public var progress: ProgressCallBack? public var failure: FailureHTTPCallBack? public override init(URL: String, method: SHMethod) { super.init(URL: URL, method: method) contentType = .multipart_form_data } @discardableResult public func upload() -> URLSessionUploadTask { configureRequest() let uploadTask = SHDataTaskManager.createUploadTaskWithRequest(request: self, completion: success, progress: progress, failure: failure) uploadTask.resume() return uploadTask } @discardableResult public func upload(completion: UploadCompletion? = nil, progress: ProgressCallBack? = nil, failure: FailureHTTPCallBack? = nil) -> URLSessionUploadTask { self.success = completion self.progress = progress self.failure = failure return upload() } }
mit
e7c69ef294165f93222784b2e43e1a4c
29.12766
91
0.534605
5.803279
false
false
false
false
zalando/ModularDemo
ZContainer/ZContainer.playground/Contents.swift
1
857
//: ZContainer - A Service Locator var registry = [ObjectIdentifier : Any]() func register<Service>(factory: () -> Service) { let serviceIdentifier = ObjectIdentifier(Service.self) registry[serviceIdentifier] = factory } func resolve<Service>() -> Service! { let serviceIdentifier = ObjectIdentifier(Service.self) guard let factory = registry[serviceIdentifier] as? () -> Service else { return Service!() } return factory() } //: Sample Service public protocol StringProcessor { func process(string: String) -> String } class Duplicator: StringProcessor { func process(string: String) -> String { return String(string.characters.flatMap { [$0, $0] }) } } register { Duplicator() as StringProcessor } //: Sample Client let processor: StringProcessor = resolve() processor.process("Hello, world")
bsd-2-clause
dc9d61390d6ece9532fd97258e29d73c
22.805556
76
0.690782
4.180488
false
false
false
false
radu-costea/ATests
ATests/ATests/UI/TakeExamViewController.swift
1
6526
// // TakeExamViewController.swift // ATests // // Created by Radu Costea on 20/06/16. // Copyright © 2016 Radu Costea. All rights reserved. // import UIKit class TakeExamViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { @IBOutlet var previousButton: UIButton! @IBOutlet var nextButton: UIButton! @IBOutlet var labelCurrentIdx: UILabel! weak var pagingViewController: UIPageViewController! var exam: ParseClientExam? var answers: [ParseExamAnswer] = [] var currentIdx: Int? var current: EditQuestionViewController? var currentAnswer: ParseExamAnswer? var timeout: NSTimer? var seenOnce: Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let allAnswers = exam?.answers where allAnswers.count > 0 { self.answers = allAnswers } if let dt = exam?.source.duration where dt > 0 { let elapsed = NSDate().timeIntervalSinceDate(exam?.startDate ?? NSDate()) let remaining = Double(dt) - elapsed timeout = NSTimer.scheduledTimerWithTimeInterval(remaining, target: self, selector: #selector(TakeExamViewController.timedOut(_:)), userInfo: nil, repeats: false) } } deinit { timeout?.invalidate() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !seenOnce { loadControllerForIdx(0) seenOnce = true } } func loadControllerForIdx(index: Int, direction: UIPageViewControllerNavigationDirection = .Forward, animated: Bool = false) -> Void { saveIfNeeded { guard 0..<self.answers.count ~= index else { return } self.currentIdx = index self.refreshIdx() let answer = self.answers[index] self.currentAnswer = answer if let controller = EditQuestionViewController.controller() { controller.editingEnabled = false controller.provideContentBlock = { _ in answer.question.content } controller.provideAnswerBlock = { _ in answer.answer } self.pagingViewController.setViewControllers([controller], direction: direction, animated: animated, completion: { success in print("new controllers: \(self.pagingViewController.viewControllers) success \(success)") }) } } } func refreshIdx() { guard let index = currentIdx else { previousButton.enabled = false nextButton.enabled = false labelCurrentIdx.text = "" return } self.previousButton.enabled = index > 0 self.nextButton.enabled = index < (self.answers.count - 1) self.labelCurrentIdx.text = "\(index + 1) / \(answers.count)" } func saveIfNeeded(completion: () -> Void) { if let idx = currentIdx where answers[idx].dirty { AnimatingViewController.showInController(self, status: "Saving state") answers[idx].saveInBackgroundWithBlock( { (success, err) in self.exam?.saveInBackgroundWithBlock({ (success, err) in AnimatingViewController.hide(completion) }) }) } else { completion() } } /// MARK: - /// MARK: Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if let identifier = segue.identifier { switch identifier { case "embedSegue": let pageViewController = segue.destinationViewController as! UIPageViewController pageViewController.delegate = self pageViewController.dataSource = self self.pagingViewController = pageViewController default: break; } } } /// MARK: - /// MARK: Actions @IBAction func didTapNext(sender: AnyObject?) -> Void { validateAnswer(currentAnswer) loadControllerForIdx(currentIdx?.successor() ?? 0, direction: .Forward, animated: true) } @IBAction func didTapPrevious(sender: AnyObject?) -> Void { validateAnswer(currentAnswer) loadControllerForIdx(currentIdx?.predecessor() ?? 0, direction: .Reverse, animated: true) } @IBAction func didTapDone(sender: AnyObject?) -> Void { validateAnswer(currentAnswer) exam?.endDate = NSDate() saveIfNeeded { [unowned self] _ in UIAlertController.showIn(self, style: .Alert, title: "Exam over", message: "You scored \(self.exam?.grade ?? 0) out of \(self.exam?.source.totalPoints ?? 0)", actions: [], cancelAction: (title: "Go Back", action: { _ in self.performSegueWithIdentifier("backToMyAccount", sender: nil) }) ) } } /// MARK: - /// MARK: PAgeViewController delegate func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { return nil } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { return nil } /// MARK: - /// MARK: Answers validtaion func timedOut(sender: NSTimer?) -> Void { didTapDone(nil) } func validateAnswer(answer: ParseExamAnswer?) -> Bool { let correct = answer?.question.answer let current = answer?.answer let isCorrect = correct?.equalTo(current) ?? false answer?.result = isCorrect ? 1.0 : 0.0 computeScore() return isCorrect } func computeScore() -> Void { let grade = answers.reduce(Float(exam?.source.freePoints ?? 0.0), combine: { $0 + $1.result * Float($1.question.points)}) exam?.grade = grade } }
mit
ac648fb14b5fa9ebfd616e6abb7bb152
34.851648
174
0.606284
5.283401
false
false
false
false
CanyFrog/HCComponent
HCComponentsDemo/HCDividerViewController.swift
1
2534
// // HCDividerViewController.swift // HCComponents // // Created by Magee Huang on 4/14/17. // Copyright © 2017 Person Inc. All rights reserved. // import UIKit import HCComponents class HCDividerViewController: UIViewController { let top: DividerView = { let top = DividerView() top.backgroundColor = UIColor.darkGray top.divider?.alignment = .top top.divider?.color = UIColor.red return top }() let bottom: DividerView = { let bottom = DividerView() bottom.backgroundColor = UIColor.darkText bottom.divider?.alignment = .bottom bottom.divider?.color = UIColor.blue return bottom }() let left: DividerView = { let left = DividerView() left.backgroundColor = UIColor.gray left.divider?.alignment = .left left.divider?.color = UIColor.green return left }() let right: DividerView = { let right = DividerView() right.backgroundColor = UIColor.lightGray right.divider?.alignment = .right right.divider?.color = UIColor.yellow return right }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white view.addSubview(top) view.addSubview(bottom) view.addSubview(left) view.addSubview(right) let views = ["top": top, "bottom": bottom, "left": left, "right": right] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[top]-12-[right(==top)]-12-|", options: .alignAllTop, metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-76-[top]-12-[bottom(==top)]-12-|", options: .alignAllLeft, metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-76-[right]-12-[left(==right)]-12-|", options: .alignAllRight, metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[bottom]-12-[left(==bottom)]-12-|", options: .alignAllTop, metrics: nil, views: views)) } } class DividerView: UIView { var divider: HCDivider? convenience init() { self.init(frame: CGRect.zero) translatesAutoresizingMaskIntoConstraints = false divider = HCDivider(view: self) divider?.thickness = 8 } override func layoutSubviews() { super.layoutSubviews() divider?.layout() } }
mit
20da276d11f456e9a1af1ef5d5a2cd89
33.22973
172
0.637584
4.459507
false
false
false
false
code-squad/blue-common
algorithm/Graph/Graph/AdjacencyListGraph.swift
2
3141
// // AdjacencyListGraph.swift // Graph // // Created by Andrew McKnight on 5/13/16. // import Foundation private class EdgeList<T> where T: Equatable, T: Hashable { var vertex: Vertex<T> var edges: [Edge<T>]? init(vertex: Vertex<T>) { self.vertex = vertex } func addEdge(_ edge: Edge<T>) { edges?.append(edge) } } open class AdjacencyListGraph<T>: AbstractGraph<T> where T: Equatable, T: Hashable { fileprivate var adjacencyList: [EdgeList<T>] = [] public required init() { super.init() } public required init(fromGraph graph: AbstractGraph<T>) { super.init(fromGraph: graph) } open override var vertices: [Vertex<T>] { var vertices = [Vertex<T>]() for edgeList in adjacencyList { vertices.append(edgeList.vertex) } return vertices } open override var edges: [Edge<T>] { var allEdges = Set<Edge<T>>() for edgeList in adjacencyList { guard let edges = edgeList.edges else { continue } for edge in edges { allEdges.insert(edge) } } return Array(allEdges) } open override func createVertex(_ data: T) -> Vertex<T> { // check if the vertex already exists let matchingVertices = vertices.filter { vertex in return vertex.data == data } if matchingVertices.count > 0 { return matchingVertices.last! } // if the vertex doesn't exist, create a new one let vertex = Vertex(data: data, index: adjacencyList.count) adjacencyList.append(EdgeList(vertex: vertex)) return vertex } open override func addDirectedEdge(_ from: Vertex<T>, to: Vertex<T>, withWeight weight: Double?) { // works let edge = Edge(from: from, to: to, weight: weight) let edgeList = adjacencyList[from.index] if edgeList.edges != nil { edgeList.addEdge(edge) } else { edgeList.edges = [edge] } } open override func addUndirectedEdge(_ vertices: (Vertex<T>, Vertex<T>), withWeight weight: Double?) { addDirectedEdge(vertices.0, to: vertices.1, withWeight: weight) addDirectedEdge(vertices.1, to: vertices.0, withWeight: weight) } open override func weightFrom(_ sourceVertex: Vertex<T>, to destinationVertex: Vertex<T>) -> Double? { guard let edges = adjacencyList[sourceVertex.index].edges else { return nil } for edge: Edge<T> in edges { if edge.to == destinationVertex { return edge.weight } } return nil } open override func edgesFrom(_ sourceVertex: Vertex<T>) -> [Edge<T>] { return adjacencyList[sourceVertex.index].edges ?? [] } open override var description: String { var rows = [String]() for edgeList in adjacencyList { guard let edges = edgeList.edges else { continue } var row = [String]() for edge in edges { var value = "\(edge.to.data)" if edge.weight != nil { value = "(\(value): \(edge.weight!))" } row.append(value) } rows.append("\(edgeList.vertex.data) -> [\(row.joined(separator: ", "))]") } return rows.joined(separator: "\n") } }
mit
a1a6dcbbe43a4a75b6d104b7b454c062
22.440299
104
0.622413
3.807273
false
false
false
false
czpc/ZpKit
ZpKit/UIKit/UIViewController+PopupController.swift
1
3474
// // UIViewController+PopupController.swift // ZpKit // // Created by 陈中培 on 16/4/12. // Copyright © 2016年 陈中培. All rights reserved. // import UIKit let kPopupViewTag = 1000 let kControlViewTag = 1001 public extension UIViewController { func popupViewController(viewController:UIViewController) { popupView(viewController.view) } func dismissViewController() { let kwindowView = windowView() let kPopupView = kwindowView.viewWithTag(kPopupViewTag) let kControlView = kwindowView.viewWithTag(kControlViewTag) slideViewOut(kwindowView, kPopupView: kPopupView!, kControlView: kControlView!) } private func windowView() -> UIView { return UIApplication.sharedApplication().keyWindow! } private func popupView(kPopupView:UIView) { //1、 取到当前window let kWindowView = windowView() kWindowView.backgroundColor = UIColor.clearColor() //2、在当前window上添加点击view let kControlView = UIControl(frame: kWindowView.bounds) kControlView.addTarget(self, action: #selector(UIViewController.dismissViewController), forControlEvents: .TouchUpInside) kControlView.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.3) kWindowView.addSubview(kControlView) kControlView.tag = kControlViewTag kPopupView.tag = kPopupViewTag kPopupView.layer.shadowPath = UIBezierPath(rect: kPopupView.bounds).CGPath kPopupView.layer.masksToBounds = false kPopupView.layer.shadowOffset = CGSizeMake(5, 5) kPopupView.layer.shadowRadius = 5 kPopupView.layer.shadowOpacity = 0.5 kPopupView.layer.shouldRasterize = true kPopupView.layer.rasterizationScale = UIScreen.mainScreen().scale kControlView.addSubview(kPopupView) slideViewIn(kWindowView, kPopupView: kPopupView) } private func slideViewIn(kWindow:UIView,kPopupView:UIView) { let windowSize = kWindow.bounds.size let popupSize = kPopupView.bounds.size var popupStartRect:CGRect popupStartRect = CGRectMake((windowSize.width - popupSize.width) / 2, windowSize.height, popupSize.width, popupSize.height) let popupEndRect = CGRectMake((windowSize.width - popupSize.width) / 2, (windowSize.height - popupSize.height) / 2, popupSize.width, popupSize.height) kPopupView.frame = popupStartRect kPopupView.alpha = 0.0 UIView.animateWithDuration(0.5, animations: { () -> Void in kPopupView.frame = popupEndRect kPopupView.alpha = 1.0 }) { (finish:Bool) -> Void in } } private func slideViewOut(kWindow:UIView,kPopupView:UIView,kControlView:UIView) { let windowSize = kWindow.bounds.size let popupSize = kPopupView.bounds.size let popupEndRect:CGRect popupEndRect = CGRectMake((windowSize.width - popupSize.width) / 2, windowSize.height, popupSize.width, popupSize.height) UIView.animateWithDuration(0.5, animations: { () -> Void in kPopupView.frame = popupEndRect kPopupView.alpha = 1.0 }) { (finish:Bool) -> Void in kControlView.removeFromSuperview() kPopupView.removeFromSuperview() } } }
mit
20fc594f8e48f10a483fcc1572896f6c
28.076271
129
0.655203
4.427097
false
false
false
false
lelandjansen/fatigue
ios/fatigue/UserDefaults.swift
1
3943
import Foundation extension UserDefaults { enum UserDefaultsKeys: String { case firstLaunch, userTriedEditingRow, rangeQuestionTutorialShown, role = "occupation", reminderEnabled, reminderHour, reminderMinute, name, supervisorName, supervisorEmail, supervisorPhone } var firstLaunch: Bool { get { return object(forKey: UserDefaultsKeys.firstLaunch.rawValue) as? Bool ?? true } set { set(newValue, forKey: UserDefaultsKeys.firstLaunch.rawValue) synchronize() } } var userTriedEditingRow: Bool { get { return object(forKey: UserDefaultsKeys.userTriedEditingRow.rawValue) as? Bool ?? false } set { set(newValue, forKey: UserDefaultsKeys.userTriedEditingRow.rawValue) synchronize() } } var rangeQuestionTutorialShown: Bool { get { return object(forKey: UserDefaultsKeys.rangeQuestionTutorialShown.rawValue) as? Bool ?? false } set { set(newValue, forKey: UserDefaultsKeys.rangeQuestionTutorialShown.rawValue) synchronize() } } var role: Role { get { return Role(rawValue: string(forKey: UserDefaultsKeys.role.rawValue) ?? Role.none.rawValue)! } set { set(newValue.rawValue, forKey: UserDefaultsKeys.role.rawValue) synchronize() } } var reminderEnabled: Bool { get { return object(forKey: UserDefaultsKeys.reminderEnabled.rawValue) as? Bool ?? false } set { set(newValue, forKey: UserDefaultsKeys.reminderEnabled.rawValue) synchronize() } } private var defaultReminderTime: DateComponents { var date = DateComponents() date.hour = 09 date.minute = 00 return date } var reminderTime: DateComponents { get { var date = DateComponents() date.hour = object(forKey: UserDefaultsKeys.reminderHour.rawValue) as? Int ?? defaultReminderTime.hour date.minute = object(forKey: UserDefaultsKeys.reminderMinute.rawValue) as? Int ?? defaultReminderTime.minute return date } set { set(newValue.hour ?? defaultReminderTime.hour, forKey: UserDefaultsKeys.reminderHour.rawValue) set(newValue.minute ?? defaultReminderTime.minute, forKey: UserDefaultsKeys.reminderMinute.rawValue) synchronize() } } var name: String? { get { return string(forKey: UserDefaultsKeys.name.rawValue) } set { let name = newValue?.trimmingCharacters(in: .whitespacesAndNewlines) set(name, forKey: UserDefaultsKeys.name.rawValue) synchronize() } } var supervisorName: String? { get { return string(forKey: UserDefaultsKeys.supervisorName.rawValue) } set { set(newValue, forKey: UserDefaultsKeys.supervisorName.rawValue) synchronize() } } var supervisorEmail: String? { get { return string(forKey: UserDefaultsKeys.supervisorEmail.rawValue) } set { set(newValue, forKey: UserDefaultsKeys.supervisorEmail.rawValue) synchronize() } } var supervisorPhone: String? { get { return string(forKey: UserDefaultsKeys.supervisorPhone.rawValue) } set { set(newValue, forKey: UserDefaultsKeys.supervisorPhone.rawValue) synchronize() } } }
apache-2.0
70f4103e2e4d8157a7b618d7556f639b
26.006849
120
0.560741
5.40137
false
false
false
false
shagalalab/marshrutkaios
Marshrutka/AppDelegate.swift
1
5781
// // AppDelegate.swift // Marshrutka // // Created by Aziz Murtazaev on 9/1/15. // Copyright (c) 2015 Shagala Lab. 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. preloadData() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func preloadData() { preloadFromCSV("destinations", parsefunc: parseDestinations) preloadFromCSV("routes", parsefunc: parseRoutes) preloadFromCSV("reverseroutes", parsefunc: parseReverseRoutes) preloadFromCSV("reachabledestinations", parsefunc: parseReachableDestinations) } func parseDestinations(dataloader: DataLoader, values: [String]) { var id = values[0].toInt()! var name = values[1] var destination = Destination(id: id, name: name) dataloader.destinations.append(destination) dataloader.destinationMap[name] = id assert(id == dataloader.destinations.count-1, "ID does not match with array index in destinations") } func parseRoutes(dataloader: DataLoader, values: [String]) { var pathPointIds: [Destination] = [] var id = values[0].toInt()! var isBus = (values[1] == "true") var displayNo = values[2].toInt()! var desc = values[3] var points: [String] = values[4].componentsSeparatedByString(",") for point in points { pathPointIds.append(dataloader.destinations[point.toInt()!]) } var route = Route(id: id, isBus: isBus, displayNo: displayNo, description: desc, pathPointIds: pathPointIds) dataloader.routes.append(route) assert(id == dataloader.routes.count-1, "ID does not match with array index in routes") } func parseReverseRoutes(dataloader: DataLoader, values: [String]) { var routes = [Route]() var destId = values[0].toInt()! var routeIds = values[1].componentsSeparatedByString(",") for routeId in routeIds { routes.append(dataloader.routes[routeId.toInt()!]) } var reverseRoute = ReverseRoutes(destinationId: destId, routeIds: routes) dataloader.reverseRoutes.append(reverseRoute) assert(destId == dataloader.reverseRoutes.count-1, "DestinationID does not match with array index in reverseRoutes") } func parseReachableDestinations(dataloader: DataLoader, values: [String]) { var destinations = [Destination]() var destId = values[0].toInt()! var reachabledestIdlist = values[1].componentsSeparatedByString(",") for reachabledestId in reachabledestIdlist { destinations.append(dataloader.destinations[reachabledestId.toInt()!]) } var reachableDestination = ReachableDestinations(destinationId: destId, reachableDestinationIds: destinations) dataloader.reachableDestinations.append(reachableDestination) } func preloadFromCSV(csvfilename: String, parsefunc: (DataLoader, [String]) -> Void) { // Retrieve data from the source file if let contentsOfURL = NSBundle.mainBundle().URLForResource(csvfilename, withExtension: "csv") { var error: NSError? var dataloader = DataLoader.sharedInstance let delimiter = ", " if let content = String(contentsOfURL: contentsOfURL, encoding: NSUTF8StringEncoding, error: &error) { let lines: [String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String] for (index, line) in enumerate(lines) { if line == "" || index == 0 { continue } var values:[String] = line.componentsSeparatedByString(delimiter) parsefunc(dataloader, values) } } } } }
mit
83451b4b9328f67cf68e0a406748b03c
46.77686
285
0.678083
4.924191
false
false
false
false
poolmyride/DataStoreKit
Pod/Classes/InMemoryDataStack.swift
1
1269
// // TestCoreDataStack.swift // // // Created by Rohit Talwar on 10/08/15. // Copyright (c) 2015 Rajat Talwar. All rights reserved. // import Foundation import CoreData open class InMemoryDataStack: CoreDataStack { override func persistentStoreCoordinator() throws -> NSPersistentStoreCoordinator? { NSLog("Providing Mock SQLite persistent store coordinator") if (self._persistentStoreCoordinator != nil){ return self._persistentStoreCoordinator } let psc: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: super.model) try psc!.addPersistentStore( ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) var ps: NSPersistentStore? do { ps = try psc!.addPersistentStore( ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) } catch _ as NSError { ps = nil } catch { fatalError() } if (ps == nil) { abort() } return psc! } }
mit
cae4caa10a1bbfbd4c1e556a385671f6
24.897959
90
0.546099
5.742081
false
false
false
false
sumitjain7/AppleTouchId
appleTouchId/Classes/AppleAuthenticator.swift
1
3372
// // AppleAuthenticator // // Created by Sumit Jain on 8/28/17. // Copyright (c) 2017 Sumit. All rights reserved. // import Foundation import LocalAuthentication public typealias AuthenticationCompletionBlock = (Void) ->() public typealias AuthenticationErrorBlock = (Int) -> () public class AppleAuthenticator : NSObject { fileprivate var context : LAContext // reason string presented to the user in auth dialog var reason : NSString // Allows fallback button title customization. If set to nil, "Enter Password" is used. var fallbackButtonTitle : NSString // If set to NO it will not customize the fallback title, shows default "Enter Password". If set to YES, title is customizable. Default value is NO. var useDefaultFallbackTitle : Bool // Disable "Enter Password" fallback button. Default value is NO. var hideFallbackButton : Bool // Default value is LAPolicyDeviceOwnerAuthenticationWithBiometrics. This value will be useful if LocalAuthentication.framework introduces new auth policies in future version of iOS. var policy : LAPolicy public static var sharedInstance : AppleAuthenticator { struct Static { static let instance : AppleAuthenticator = AppleAuthenticator() } return Static.instance } override init(){ self.context = LAContext() self.fallbackButtonTitle = "hello" self.useDefaultFallbackTitle = false self.hideFallbackButton = false if #available(iOS 9.0, *) { self.policy = .deviceOwnerAuthentication } else { self.policy = .deviceOwnerAuthenticationWithBiometrics } self.reason = "need this for auth purpose" } class func canAuthenticateWithError(error: NSErrorPointer) -> Bool{ if (UserDefaults.standard.object(forKey: "touch_id_security") != nil){ if UserDefaults.standard.bool(forKey: "touch_id_security") == false{ return false } } else { return false } if ((NSClassFromString("LAContext")) != nil){ if (AppleAuthenticator.sharedInstance.context .canEvaluatePolicy(AppleAuthenticator.sharedInstance.policy, error: nil)){ return true } return false } return false } public func authenticateWithSuccess(_ success: @escaping AuthenticationCompletionBlock, failure: @escaping AuthenticationErrorBlock){ self.context = LAContext() var authError : NSError? if (self.useDefaultFallbackTitle) { self.context.localizedFallbackTitle = self.fallbackButtonTitle as String; }else if (self.hideFallbackButton){ self.context.localizedFallbackTitle = ""; } if (self.context.canEvaluatePolicy(policy, error: &authError)) { self.context.evaluatePolicy(policy, localizedReason: reason as String, reply:{ authenticated, error in if (authenticated) { DispatchQueue.main.async(execute: {success()}) } else { DispatchQueue.main.async(execute: {failure(error!._code)}) } }) } else { failure(authError!.code) } } }
mit
9d49fc5f97fb99e8ebef80cf5929eeaa
34.87234
187
0.632562
5.293564
false
false
false
false
pawan007/ExpenseTracker
ExpenseTracker/ViewController.swift
1
21402
// // ViewController.swift // ExpenseTracker // // Created by Narender Kumar on 10/7/16. // Copyright © 2016 Narender Kumar. All rights reserved. // import GoogleAPIClient import GTMOAuth2 import SwiftSpinner import RealmSwift import UIKit class ViewController: UIViewController { @IBOutlet weak var bgEffectView: UIVisualEffectView! @IBOutlet var bankBtn: [UIButton]! var emailMessages : NSMutableArray = [] private let kTransactionSentence = "transaction of inr " //"subject: transaction alert" private let kKeychainItemName = "Gmail API" private let kClientID = "866202949798-09gknp24snotj0bh87b4jg6ii4chdjd0.apps.googleusercontent.com" // If modifying these scopes, delete your previously saved credentials by // resetting the iOS simulator or uninstall the app. private let scopes = [kGTLAuthScopeGmailReadonly] private let service = GTLServiceGmail() let output = UITextView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. output.frame = view.bounds output.editable = false output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0) output.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] //view.addSubview(output); TODO: look into this if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName( kKeychainItemName, clientID: kClientID, clientSecret: nil) { service.authorizer = auth } bgEffectView.layer.cornerRadius = 3.5 bgEffectView.clipsToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* @IBAction func bankBtnAction(_ sender: UIButton) { for tempBtn in self.bankBtn as [UIButton] { tempBtn.selected = false } sender.selected = true; } */ @IBAction func loginAction(sender: AnyObject) { /* let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let vc : DashboardVC = mainStoryboard.instantiateViewControllerWithIdentifier("DashboardVC") as! DashboardVC self.navigationController?.pushViewController(vc, animated: true) return */ if let authorizer = service.authorizer, let canAuth = authorizer.canAuthorize where canAuth { print("email = \(authorizer.userEmail)") print("userDate = \(service.serviceUserData)") // print("properties = \(authorizer.properties)") // print("properties = \(authResult.userProfile)") // print("properties = \(authResult.signIn.userData)") SwiftSpinner.show("Connecting to your gmail account...") fetchLabels() // SwiftSpinner.hide() // let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) // let vc : DashboardVC = mainStoryboard.instantiateViewControllerWithIdentifier("DashboardVC") as! DashboardVC // self.navigationController?.pushViewController(vc, animated: true) } else { presentViewController(createAuthController(), animated: true, completion: nil) } // presentViewController(createAuthController(), animated: true, completion: nil) } // MARK: Custom Methods // Construct a query and get a list of upcoming labels from the gmail API func fetchLabels() { /* let qualityOfServiceClass = QOS_CLASS_BACKGROUND let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0) dispatch_async(backgroundQueue, { print("This is run on the background queue") SwiftSpinner.show("Connecting to Gmail server...") dispatch_async(dispatch_get_main_queue(), { () -> Void in print("This is run on the main queue, after the previous code in outer block") }) }) */ SwiftSpinner.show("Connecting to Gmail server...") output.text = "Getting messages..." let query = GTLQueryGmail.queryForUsersMessagesList() query.q = kTransactionSentence query.format = kGTLGmailFormatFull service.executeQuery(query, delegate: self, didFinishSelector: #selector(ViewController.displayResultWithTicket(_:finishedWithObject:error:)) ) } // Display the labels in the UITextView func displayResultWithTicket(ticket : GTLServiceTicket, finishedWithObject labelsResponse : GTLGmailListMessagesResponse, error : NSError?) { if let error = error { showAlert("Error", message: error.localizedDescription) return } // HERE let array = labelsResponse.messages as NSArray let batchQuery = GTLBatchQuery () for message in array as! [GTLGmailMessage] { let midentifier = message.identifier let query = GTLQueryGmail.queryForUsersMessagesGet() query.identifier = midentifier query.format = kGTLGmailFormatFull batchQuery.addQuery(query) } self.service.executeQuery(batchQuery, delegate: self, didFinishSelector: #selector(ViewController.displayResultWithTicketEachMessages(_:finishedWithObject:error:))) } func parseEmailMessages() { print("End all mail") print("messages are \(emailMessages)") let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let vc : DashboardVC = mainStoryboard.instantiateViewControllerWithIdentifier("DashboardVC") as! DashboardVC self.navigationController?.pushViewController(vc, animated: true) } func displayResultWithTicketEachMessages(ticket : GTLServiceTicket, finishedWithObject eachMessageResponse : GTLBatchResult, error : NSError?) { SwiftSpinner.hide() if error != nil { print("eroor happende") return } else { /* let msg: String = "You have used your Debit Card linked to Account XXXXXXXX5531 for a transaction of INR 600.00 Info.MPS*EVER GREEN on 23-08-2016 17:12:01. The available balance in your Account is Rs. 2,034.17." */ var i = 0; let expenseMessages = eachMessageResponse.successes.allValues for message in expenseMessages as! [GTLGmailMessage] { var dataValue = 0 var amount: Double = 0.00 var date = NSDate() var gMailId = "" var accountNo = "" var information = "" var debited = "credited" let parts = message.payload.body var decodedBody: NSString? if parts != nil { // let body: AnyObject? = parts.valueForKey("body") if parts!.valueForKey("data") != nil { var base64DataString = parts!.valueForKey("data") as! String base64DataString = base64DataString.stringByReplacingOccurrencesOfString("_", withString: "/", options: NSStringCompareOptions.LiteralSearch, range: nil) base64DataString = base64DataString.stringByReplacingOccurrencesOfString("-", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil) let decodedData = NSData(base64EncodedString: base64DataString, options:NSDataBase64DecodingOptions(rawValue: 0)) decodedBody = NSString(data: decodedData!, encoding: NSUTF8StringEncoding) } } if let shortMessage : String = decodedBody as? String //message.payload.body.data //message.snippet //msg//message.snippet { let currencyPattern : String = "[Ii][Nn][Rr](\\s*.\\s*\\d*)" let accountNumPattern : String = "\\b(Account)(XX)\\b" let timeRegex : String = "(\\d{1,2}[-/.]\\d{1,2}[-/.]\\d{4}[-/. ]\\d\\d?:\\d\\d)" //Account XXXXXXXX5531 let accountRegex : String = "[Aa][/][Cc][ ][0-9]{6} | [A][c][c][o][u][n][t][ ][X]{8}[0-9]{4}" //Info: CASH-ATM/00009204. //Info.MIN*PayTM on //Info.MPS*EVER GREEN on //([^ ]+) .*, //[^\\s]+ -- Ax let infoRegex : String = "[Ii][Nn][Ff][Oo][ -/.: ]([^[on]]+).*" // let infoRegex : String = "[Ii][Nn][Ff][Oo][ -/.: ]([^[on]]+)* | [Ii][Nn][Ff][Oo][ -/.: ][^\\s]+" //debited let debitedPattern : String = "[Dd][Ee][Bb][Ii][Tt][Ee][Dd]" /* Your a/c 027012 is debited INR 2000.00 on 25-10-2015 21:59:26 A/c Bal is INR 15866.53 Info: CASH-ATM/01076095. Get Axis Mobile: m.axisbank.com/cwdl nYour a/c 027012 is debited INR 2.00 on 30-03-2016 22:47:55 Info: PUR/AMAZON INTERNET SERVIC/NEW DELHI/AMAZON INTERNET SERVIC */ i += 1 print (" \(i).") print ("================ Start here====================") print("Mail ID : \(message.identifier)") gMailId = message.identifier do { let regex : NSRegularExpression = try NSRegularExpression.init(pattern: currencyPattern, options: NSRegularExpressionOptions.CaseInsensitive) if let match = regex.firstMatchInString(shortMessage, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, shortMessage.characters.count)) { // print("Amount : \((shortMessage as NSString).substringWithRange(match.range))") let val:String = ((shortMessage as NSString).substringWithRange(match.range)) let replaced = val.stringByReplacingOccurrencesOfString("INR", withString: "") let trimmedString = replaced.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) print("Amount : \(trimmedString)") dataValue += 1 amount = Double(trimmedString)! } } catch let error as NSError { print(error.description) } do { let regex : NSRegularExpression = try NSRegularExpression.init(pattern: accountNumPattern, options: NSRegularExpressionOptions.CaseInsensitive) if let match = regex.firstMatchInString(shortMessage, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, shortMessage.characters.count)) { print("A : \((shortMessage as NSString).substringWithRange(match.range))") } } catch let error as NSError { print(error.description) } do { let regex : NSRegularExpression = try NSRegularExpression.init(pattern: timeRegex, options: NSRegularExpressionOptions.CaseInsensitive) if let match = regex.firstMatchInString(shortMessage, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, shortMessage.characters.count)) { print("Date : \((shortMessage as NSString).substringWithRange(match.range))") dataValue += 1 let dateVal:String = ((shortMessage as NSString).substringWithRange(match.range)) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" //25-10-2015 21:59 //yyyy-MM-dd'T'HH:mm:ss date = dateFormatter.dateFromString(dateVal)! print("DateChange : \(date)") } } catch let error as NSError { print(error.description) print ("Date not found") } do { let regex : NSRegularExpression = try NSRegularExpression.init(pattern: accountRegex, options: NSRegularExpressionOptions.CaseInsensitive) if let match = regex.firstMatchInString(shortMessage, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, shortMessage.characters.count)) { print("Account : \((shortMessage as NSString).substringWithRange(match.range))") dataValue += 1 accountNo = (shortMessage as NSString).substringWithRange(match.range) } else { print ("Account not found 1") } } catch let error as NSError { print(error.description) print ("Account not found") } do { let regex : NSRegularExpression = try NSRegularExpression.init(pattern: infoRegex, options: NSRegularExpressionOptions.CaseInsensitive) if let match = regex.firstMatchInString(shortMessage, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, shortMessage.characters.count)) { print("Information : \((shortMessage as NSString).substringWithRange(match.range))") dataValue += 1 information = (shortMessage as NSString).substringWithRange(match.range) } else { print ("Information : Info not found") } } catch let error as NSError { print(error.description) } do { let regex : NSRegularExpression = try NSRegularExpression.init(pattern: debitedPattern, options: NSRegularExpressionOptions.CaseInsensitive) if regex.firstMatchInString(shortMessage, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, shortMessage.characters.count)) != nil { print("Debited : YES") debited = "debited" } else { print("Debited : NO") } dataValue += 1 } catch let error as NSError { print(error.description) } print ("================ End here====================") print (" ") print (" ") /* ================ Start here==================== Amount : 30148 Account not found 1 Information : Info not found Debited : NO ================ End here==================== */ //let scanner : NSScanner = NSScanner.init(string: shortMessage) // let str = scanner.scanUpToCharactersFrom(NSCharacterSet.symbolCharacterSet()) //let str1 = scanner.scanUpTo(".") emailMessages.addObject(shortMessage) //-------- Get min 2 value or data to insert in db -------------// if(dataValue > 2) { let realm = try! Realm() //let accountInfo = AccountInfo() let accountInfo = AccountInfo.getModel() accountInfo.id = accountInfo.IncrementaID() accountInfo.gMailId = gMailId accountInfo.accountNum = accountNo accountInfo.amount = amount accountInfo.transactionDate = date accountInfo.transactionInfo = information accountInfo.debitCredit = debited let queryRecordID = realm.objects(AccountInfo).filter("gMailId == '\(gMailId)'") if queryRecordID.count == 0 { try! realm.write { realm.add(accountInfo) } } } //-------------------------------------------------------------// } } self.parseEmailMessages() } let current = NSDate() let sevenDaysAgo = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -30, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0)) print("sevenDaysAgo : \(sevenDaysAgo)") let realm = try! Realm() let messages = realm.objects(AccountInfo).filter("transactionDate > %@ AND transactionDate <= %@", sevenDaysAgo!, current) print("restult : \(messages)") } // Creates the auth controller for authorizing access to Gmail API private func createAuthController() -> GTMOAuth2ViewControllerTouch { let scopeString = scopes.joinWithSeparator(" ") return GTMOAuth2ViewControllerTouch( scope: scopeString, clientID: kClientID, clientSecret: nil, keychainItemName: kKeychainItemName, delegate: self, finishedSelector: #selector(ViewController.viewController(_:finishedWithAuth:error:)) ) } // Handle completion of the authorization process, and update the Gmail API // with the new credentials. func viewController(vc : UIViewController, finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) { if let error = error { service.authorizer = nil showAlert("Authentication Error", message: error.localizedDescription) return } service.authorizer = authResult print("email = \(authResult.userEmail)") print("userDate = \(authResult.userData)") print("properties = \(authResult.properties)") // print("properties = \(authResult.userProfile)") // print("properties = \(authResult.signIn.userData)") dismissViewControllerAnimated(true, completion: nil) if let authorizer = service.authorizer, let canAuth = authorizer.canAuthorize where canAuth { fetchLabels() // let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) // let vc : DashboardVC = mainStoryboard.instantiateViewControllerWithIdentifier("DashboardVC") as! DashboardVC // self.navigationController?.pushViewController(vc, animated: true) } else {} } // Helper for showing an alert func showAlert(title : String, message: String) { let alert = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert ) let ok = UIAlertAction( title: "OK", style: UIAlertActionStyle.Default, handler: nil ) alert.addAction(ok) presentViewController(alert, animated: true, completion: nil) } } import UIKit extension String { func fromBase64() -> String? { guard let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0)) else { return nil } return String(data: data, encoding: NSUTF8StringEncoding)! } func toBase64() -> String? { guard let data = self.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } return data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) } }
apache-2.0
dc85658f2a533edc82d90fc08cf8db96
45.829322
224
0.529555
5.693269
false
false
false
false
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/MenuViewController/MenuView/MenuView+Actions.swift
2
5976
// // MenuView+Actions.swift // WikiRaces // // Created by Andrew Finke on 2/23/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import UIKit import GameKit.GKLocalPlayer extension MenuView { // MARK: - Actions - /// Join button pressed @objc func showJoinOptions() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) UISelectionFeedbackGenerator().selectionChanged() animateOptionsOutAndTransition(to: .joinOptions) } @objc func createRace() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) PlayerFirebaseAnalytics.log(event: .revampPressedHost) UISelectionFeedbackGenerator().selectionChanged() PlayerCloudKitLiveRaceManager.shared.isCloudEnabled { isEnabled in DispatchQueue.main.async { if isEnabled || Defaults.isFastlaneSnapshotInstance { self.animateMenuOut { self.listenerUpdate?(.presentCreateRace) } } else { let message = "You must have iCloud Drive enabled for WikiRaces to create a private race. You can still join any race." let alertController = UIAlertController(title: "iCloud Issue", message: message, preferredStyle: .alert) alertController.addCancelAction(title: "Ok") #if targetEnvironment(simulator) let action = UIAlertAction(title: "SIM BYPASS", style: .default) { _ in self.animateMenuOut { self.listenerUpdate?(.presentCreateRace) } } alertController.addAction(action) #endif self.listenerUpdate?(.presentAlert(alertController)) PlayerFirebaseAnalytics.log(event: .revampPressedHostiCloudIssue) } } } } @objc func joinPublicRace() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) PlayerFirebaseAnalytics.log(event: .revampPressedJoinPublic) PlayerUserDefaultsStat.gkPressedJoin.increment() UISelectionFeedbackGenerator().selectionChanged() guard !promptGlobalRacesPopularity() else { return } animateMenuOut { self.listenerUpdate?(.presentJoinPublicRace) } } @objc func joinPrivateRace() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) PlayerFirebaseAnalytics.log(event: .revampPressedJoinPrivate) PlayerUserDefaultsStat.mpcPressedJoin.increment() UISelectionFeedbackGenerator().selectionChanged() animateMenuOut { self.listenerUpdate?(.presentJoinPrivateRace) } } @objc func backButtonPressed() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) UISelectionFeedbackGenerator().selectionChanged() animateOptionsOutAndTransition(to: .joinOrCreate) } @objc func plusButtonPressed() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) UISelectionFeedbackGenerator().selectionChanged() animateOptionsOutAndTransition(to: .plusOptions) } @objc func statsButtonPressed() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) UISelectionFeedbackGenerator().selectionChanged() if PlusStore.shared.isPlus { animateMenuOut { self.listenerUpdate?(.presentStats) } } else { listenerUpdate?(.presentSubscription) } } /// Called when a tile is pressed /// /// - Parameter sender: The pressed tile @objc func menuTilePressed() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) animateMenuOut { self.listenerUpdate?(.presentLeaderboard) } } func triggeredEasterEgg() { PlayerFirebaseAnalytics.log(event: .userAction(#function)) medalView.showMedals() } // MARK: - Menu Animations - /// Animates the views on screen func animateMenuIn(completion: (() -> Void)? = nil) { isUserInteractionEnabled = false movingPuzzleView.start() state = .joinOrCreate setNeedsLayout() UIView.animate( withDuration: WKRAnimationDurationConstants.menuToggle, animations: { self.layoutIfNeeded() }, completion: { _ in self.isUserInteractionEnabled = true completion?() }) } /// Animates the views off screen /// /// - Parameter completion: The completion handler func animateMenuOut(completion: (() -> Void)?) { if state == .noInterface { completion?() return } isUserInteractionEnabled = false state = .noInterface setNeedsLayout() UIView.animate(withDuration: WKRAnimationDurationConstants.menuToggle, animations: { self.layoutIfNeeded() }, completion: { _ in self.movingPuzzleView.stop() completion?() }) } func animateOptionsOutAndTransition(to state: InterfaceState) { self.state = .noOptions setNeedsLayout() UIView.animate( withDuration: WKRAnimationDurationConstants.menuToggle / 2, animations: { self.layoutIfNeeded() }, completion: { _ in self.state = state self.setNeedsLayout() UIView.animate( withDuration: WKRAnimationDurationConstants.menuToggle / 2, delay: WKRAnimationDurationConstants.menuToggle / 4, animations: { self.layoutIfNeeded() }) }) } }
mit
b0951f54483b246a14fdbec9327aa0b2
29.176768
139
0.593473
5.471612
false
false
false
false
Poligun/NihonngoSwift
Nihonngo/MenuItemCell.swift
1
1380
// // MenuItemCell.swift // Nihonngo // // Created by ZhaoYuhan on 14/12/31. // Copyright (c) 2014年 ZhaoYuhan. All rights reserved. // import UIKit class MenuItemCell: BaseCell { private let label: UILabel = UILabel() override class var defaultReuseIdentifier: String { return "MenuItemCell" } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = UIColor.clearColor() let view = UIView() view.backgroundColor = UIColor(hue: 214.0 / 360.0, saturation: 0.94, brightness: 1.0, alpha: 1.0) self.selectedBackgroundView = view label.setTranslatesAutoresizingMaskIntoConstraints(false) label.font = UIFont.boldSystemFontOfSize(17.0) label.textColor = UIColor.whiteColor() label.textAlignment = NSTextAlignment.Center self.contentView.addSubview(label) self.contentView.addConstraints(NSLayoutConstraint.constraints( views: ["label": label], formats: "V:|-8-[label]-8-|", "H:|-0-[label(150)]")) } func setMenuItemTitle(title: NSString) { self.label.text = title } }
mit
f11ca6b1e2fa5af62f2c618e005d305a
27.708333
105
0.630624
4.503268
false
false
false
false
MidnightPulse/Tabman
Sources/Tabman/TabmanBar/Transitioning/TabmanBarTransitionStore.swift
3
2661
// // TabmanBarTransitionHandler.swift // Tabman // // Created by Merrick Sapsford on 14/03/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit /// Store for getting bar/indicator relevant transitions. internal class TabmanBarTransitionStore: Any { // // MARK: Properties // private var transitions: [Int: TabmanTransition] // // MARK: Init // init() { // initialize available transitions let scrollingIndicatorTransition = TabmanScrollingBarIndicatorTransition() let staticIndicatorTransition = TabmanStaticBarIndicatorTransition() let itemColorTransition = TabmanItemColorTransition() let itemMaskTransition = TabmanItemMaskTransition() // create transitions hashmap var transitions: [Int : TabmanTransition] = [:] transitions[scrollingIndicatorTransition.hashValue] = scrollingIndicatorTransition transitions[staticIndicatorTransition.hashValue] = staticIndicatorTransition transitions[itemColorTransition.hashValue] = itemColorTransition transitions[itemMaskTransition.hashValue] = itemMaskTransition self.transitions = transitions } // // MARK: Transitions // /// Get the transition for the indicator of a particular bar. /// /// - Parameter bar: The bar. /// - Returns: The relevant transition. func indicatorTransition(forBar bar: TabmanBar) -> TabmanIndicatorTransition? { guard let transitionType = bar.indicatorTransitionType() else { return nil } let hash = String(describing: transitionType).hashValue guard let transition = self.transitions[hash] as? TabmanIndicatorTransition else { return nil } transition.tabmanBar = bar return transition } /// Get the relevant transition for bar items when using a particular indicator style. /// /// - Parameters: /// - bar: The bar that the indicator is part of. /// - indicatorStyle: The indicator style. /// - Returns: The item transition. func itemTransition(forBar bar: TabmanBar, indicator: TabmanIndicator) -> TabmanItemTransition? { guard let transitionType = indicator.itemTransitionType() else { return nil } let hash = String(describing: transitionType).hashValue guard let transition = self.transitions[hash] as? TabmanItemTransition else { return nil } transition.tabmanBar = bar return transition } }
mit
7ad5b8b66cfa01ff80553c4b641cab1b
31.048193
101
0.652256
5.32
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Graphic/PolylineGraphic.swift
1
5161
// // PolylineGraphic.swift // SwiftyEcharts // // Created by Pluto Y on 12/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 折线类型的 `Graphic` public final class PolylineGraphic: Graphic { /// 折线的位置节点 public final class Shape { /// 是否平滑曲线 /// /// - val: 如果为 val:表示贝塞尔 (bezier) 差值平滑,smooth 指定了平滑等级,范围 [0, 1]。 /// - spline: 如果为 'spline':表示 Catmull-Rom spline 差值平滑。 public enum Smooth: Jsonable { case val(Float) case spline public var jsonString: String { switch self { case let .val(val): return "\(val)" case .spline: return "\"spline\"" } } } /// 点列表,用于定义形状,如 [[22, 44], [44, 55], [11, 44], ...] public var point: [Point]? /// 是否平滑曲线 public var smooth: Smooth? /// 是否将平滑曲线约束在包围盒中。smooth 为 number(bezier)时生效。 public var smoothConstraint: Bool? public init() {} } /// MARK: Graphic public var type: GraphicType { return .polyline } public var id: String? public var action: GraphicAction? public var left: Position? public var right: Position? public var top: Position? public var bottom: Position? public var bounding: GraphicBounding? public var z: Float? public var zlevel: Float? public var silent: Bool? public var invisible: Bool? public var cursor: String? public var draggable: Bool? public var progressive: Bool? /// 折线的位置节点 public var shape: Shape? /// 折线的样式 public var style: CommonGraphicStyle? public init() {} } extension PolylineGraphic.Shape: Enumable { public enum Enums { case point([Point]), smooth(Smooth), smoothConstraint(Bool) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .point(point): self.point = point case let .smooth(smooth): self.smooth = smooth case let .smoothConstraint(smoothConstraint): self.smoothConstraint = smoothConstraint } } } } extension PolylineGraphic.Shape: Mappable { public func mapping(_ map: Mapper) { map["point"] = point map["smooth"] = smooth map["smoothConstraint"] = smoothConstraint } } extension PolylineGraphic: Enumable { public enum Enums { case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), shape(Shape), style(CommonGraphicStyle) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .id(id): self.id = id case let .action(action): self.action = action case let .left(left): self.left = left case let .right(right): self.right = right case let .top(top): self.top = top case let .bottom(bottom): self.bottom = bottom case let .bounding(bounding): self.bounding = bounding case let .z(z): self.z = z case let .zlevel(zlevel): self.zlevel = zlevel case let .silent(silent): self.silent = silent case let .invisible(invisible): self.invisible = invisible case let .cursor(cursor): self.cursor = cursor case let .draggable(draggable): self.draggable = draggable case let .progressive(progressive): self.progressive = progressive case let .shape(shape): self.shape = shape case let .style(style): self.style = style } } } } extension PolylineGraphic: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["id"] = id map["$action"] = action map["left"] = left map["right"] = right map["top"] = top map["bottom"] = bottom map["bounding"] = bounding map["z"] = z map["zlevel"] = zlevel map["silent"] = silent map["invisible"] = invisible map["cursor"] = cursor map["draggable"] = draggable map["progressive"] = progressive map["shape"] = shape map["style"] = style } }
mit
36d05cdd7a993aceccefa4dc84523ab1
28.452381
288
0.530517
4.53945
false
false
false
false
steventhanna/capsul
capsul/capsul/MKLayer.swift
6
7904
// // MKLayer.swift // MaterialKit // // Created by Le Van Nghia on 11/15/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit import QuartzCore enum MKTimingFunction { case Linear case EaseIn case EaseOut case Custom(Float, Float, Float, Float) var function : CAMediaTimingFunction { switch self { case .Linear: return CAMediaTimingFunction(name: "linear") case .EaseIn: return CAMediaTimingFunction(name: "easeIn") case .EaseOut: return CAMediaTimingFunction(name: "easeOut") case .Custom(let cpx1, let cpy1, let cpx2, let cpy2): return CAMediaTimingFunction(controlPoints: cpx1, cpy1, cpx2, cpy2) } } } enum MKRippleLocation { case Center case Left case Right case TapLocation } class MKLayer { private var superLayer: CALayer! private let circleLayer = CALayer() private let backgroundLayer = CALayer() private let maskLayer = CAShapeLayer() var rippleLocation: MKRippleLocation = .TapLocation { didSet { var origin: CGPoint? switch rippleLocation { case .Center: origin = CGPoint(x: superLayer.bounds.width/2, y: superLayer.bounds.height/2) case .Left: origin = CGPoint(x: superLayer.bounds.width * 0.25, y: superLayer.bounds.height/2) case .Right: origin = CGPoint(x: superLayer.bounds.width * 0.75, y: superLayer.bounds.height/2) default: origin = nil } if let originPoint = origin { setCircleLayerLocationAt(originPoint) } } } var circleGrowRatioMax: Float = 0.9 { didSet { if circleGrowRatioMax > 0 { let superLayerWidth = CGRectGetWidth(superLayer.bounds) let superLayerHeight = CGRectGetHeight(superLayer.bounds) let circleSize = CGFloat(max(superLayerWidth, superLayerHeight)) * CGFloat(circleGrowRatioMax) let circleCornerRadius = circleSize/2 circleLayer.cornerRadius = circleCornerRadius setCircleLayerLocationAt(CGPoint(x: superLayerWidth/2, y: superLayerHeight/2)) } } } init(superLayer: CALayer) { self.superLayer = superLayer let superLayerWidth = CGRectGetWidth(superLayer.bounds) let superLayerHeight = CGRectGetHeight(superLayer.bounds) // background layer backgroundLayer.frame = superLayer.bounds backgroundLayer.opacity = 0.0 superLayer.addSublayer(backgroundLayer) // circlelayer let circleSize = CGFloat(max(superLayerWidth, superLayerHeight)) * CGFloat(circleGrowRatioMax) let circleCornerRadius = circleSize/2 circleLayer.opacity = 0.0 circleLayer.cornerRadius = circleCornerRadius setCircleLayerLocationAt(CGPoint(x: superLayerWidth/2, y: superLayerHeight/2)) backgroundLayer.addSublayer(circleLayer) // mask layer setMaskLayerCornerRadius(superLayer.cornerRadius) backgroundLayer.mask = maskLayer } func superLayerDidResize() { CATransaction.begin() CATransaction.setDisableActions(true) backgroundLayer.frame = superLayer.bounds setMaskLayerCornerRadius(superLayer.cornerRadius) CATransaction.commit() setCircleLayerLocationAt(CGPoint(x: superLayer.bounds.width/2, y: superLayer.bounds.height/2)) } func enableOnlyCircleLayer() { backgroundLayer.removeFromSuperlayer() superLayer.addSublayer(circleLayer) } func setBackgroundLayerColor(color: UIColor) { backgroundLayer.backgroundColor = color.CGColor } func setCircleLayerColor(color: UIColor) { circleLayer.backgroundColor = color.CGColor } func didChangeTapLocation(location: CGPoint) { if rippleLocation == .TapLocation { self.setCircleLayerLocationAt(location) } } func setMaskLayerCornerRadius(cornerRadius: CGFloat) { maskLayer.path = UIBezierPath(roundedRect: backgroundLayer.bounds, cornerRadius: cornerRadius).CGPath } func enableMask(enable: Bool = true) { backgroundLayer.mask = enable ? maskLayer : nil } func setBackgroundLayerCornerRadius(cornerRadius: CGFloat) { backgroundLayer.cornerRadius = cornerRadius } private func setCircleLayerLocationAt(center: CGPoint) { let bounds = superLayer.bounds let width = CGRectGetWidth(bounds) let height = CGRectGetHeight(bounds) let subSize = CGFloat(max(width, height)) * CGFloat(circleGrowRatioMax) let subX = center.x - subSize/2 let subY = center.y - subSize/2 // disable animation when changing layer frame CATransaction.begin() CATransaction.setDisableActions(true) circleLayer.frame = CGRect(x: subX, y: subY, width: subSize, height: subSize) CATransaction.commit() } // MARK - Animation func animateScaleForCircleLayer(fromScale: Float, toScale: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { let circleLayerAnim = CABasicAnimation(keyPath: "transform.scale") circleLayerAnim.fromValue = fromScale circleLayerAnim.toValue = toScale let opacityAnim = CABasicAnimation(keyPath: "opacity") opacityAnim.fromValue = 1.0 opacityAnim.toValue = 0.0 let groupAnim = CAAnimationGroup() groupAnim.duration = duration groupAnim.timingFunction = timingFunction.function groupAnim.removedOnCompletion = false groupAnim.fillMode = kCAFillModeForwards groupAnim.animations = [circleLayerAnim, opacityAnim] circleLayer.addAnimation(groupAnim, forKey: nil) } func animateAlphaForBackgroundLayer(timingFunction: MKTimingFunction, duration: CFTimeInterval) { let backgroundLayerAnim = CABasicAnimation(keyPath: "opacity") backgroundLayerAnim.fromValue = 1.0 backgroundLayerAnim.toValue = 0.0 backgroundLayerAnim.duration = duration backgroundLayerAnim.timingFunction = timingFunction.function backgroundLayer.addAnimation(backgroundLayerAnim, forKey: nil) } func animateSuperLayerShadow(fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { animateShadowForLayer(superLayer, fromRadius: fromRadius, toRadius: toRadius, fromOpacity: fromOpacity, toOpacity: toOpacity, timingFunction: timingFunction, duration: duration) } func animateMaskLayerShadow() { } private func animateShadowForLayer(layer: CALayer, fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { let radiusAnimation = CABasicAnimation(keyPath: "shadowRadius") radiusAnimation.fromValue = fromRadius radiusAnimation.toValue = toRadius let opacityAnimation = CABasicAnimation(keyPath: "shadowOpacity") opacityAnimation.fromValue = fromOpacity opacityAnimation.toValue = toOpacity let groupAnimation = CAAnimationGroup() groupAnimation.duration = duration groupAnimation.timingFunction = timingFunction.function groupAnimation.removedOnCompletion = false groupAnimation.fillMode = kCAFillModeForwards groupAnimation.animations = [radiusAnimation, opacityAnimation] layer.addAnimation(groupAnimation, forKey: nil) } }
mit
23ce58a5192287207bbc0806b9627923
36.107981
194
0.663588
5.670014
false
false
false
false
nathawes/swift
test/Constraints/patterns.swift
4
13209
// RUN: %target-typecheck-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is ExpressibleByIntegerLiteral case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () default: () } switch (1, 2) { case (var a, a): // expected-error {{cannot find 'a' in scope}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () default: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() default: () } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () default: () } // Raise an error if pattern productions are used in expressions. var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}} () case Watch.Edition: // expected-warning {{cast from 'HairType' to unrelated type 'Watch' always fails}} () case .HairForceOne: // expected-error{{type 'HairType' has no member 'HairForceOne'}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{10-11=_}} case nil: break } func SR2066(x: Int?) { // nil literals should still work when wrapped in parentheses switch x { case (nil): break case _?: break } switch x { case ((nil)): break case _?: break } switch (x, x) { case ((nil), _): break case (_?, _): break } } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x as Any, terminator: "") case let x?: print(x as Any, terminator: "") case 4???: break case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}} default: break } switch ("foo" as String?) { case "what": break default: break } // Test some value patterns. let x : Int? extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value default: break } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}} let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}} switch $0 { case .A: return 1 default: return 2 } } } // SR-2057 enum SR2057 { case foo } let sr2057: SR2057? if case .foo = sr2057 { } // Ok // Invalid 'is' pattern class SomeClass {} if case let doesNotExist as SomeClass:AlsoDoesNotExist {} // expected-error@-1 {{cannot find type 'AlsoDoesNotExist' in scope}} // expected-error@-2 {{variable binding in a condition requires an initializer}} // `.foo` and `.bar(...)` pattern syntax should also be able to match // static members as expr patterns struct StaticMembers: Equatable { init() {} init(_: Int) {} init?(opt: Int) {} static var prop = StaticMembers() static var optProp: Optional = StaticMembers() static func method(_: Int) -> StaticMembers { return prop } static func method(withLabel: Int) -> StaticMembers { return prop } static func optMethod(_: Int) -> StaticMembers? { return optProp } static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true } } let staticMembers = StaticMembers() let optStaticMembers: Optional = StaticMembers() switch staticMembers { case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(): break case .init(0): break case .init(_): break // expected-error{{'_' can only appear in a pattern}} case .init(let x): break // expected-error{{cannot appear in an expression}} case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} // expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} case .prop: break case .optProp: break case .method: break // expected-error{{member 'method' expects argument of type 'Int'}} case .method(0): break case .method(_): break // expected-error{{'_' can only appear in a pattern}} case .method(let x): break // expected-error{{cannot appear in an expression}} case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}} case .method(withLabel: 0): break case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}} case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}} case .optMethod(0): break } _ = 0 // rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining struct S_32241441 { enum E_32241441 { case foo case bar } var type: E_32241441 = E_32241441.foo } func rdar32241441() { let s: S_32241441? = S_32241441() switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}} case .foo: // Ok break; case .bar: // Ok break; } } // SR-6100 struct One<Two> { // expected-note{{'Two' declared as parameter to type 'One'}} public enum E: Error { // if you remove associated value, everything works case SomeError(String) } } func testOne() { do { } catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}} if case One.E.SomeError = error {} // expected-error{{generic parameter 'Two' could not be inferred}} } } // SR-8347 // constrain initializer expressions of optional some pattern bindings to be optional func test8347() -> String { struct C { subscript (s: String) -> String? { return "" } subscript (s: String) -> [String] { return [""] } func f() -> String? { return "" } func f() -> Int { return 3 } func g() -> String { return "" } func h() -> String { return "" } func h() -> Double { return 3.0 } func h() -> Int? { //expected-note{{found this candidate}} return 2 } func h() -> Float? { //expected-note{{found this candidate}} return nil } } let c = C() if let s = c[""] { return s } if let s = c.f() { return s } if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}} return s } if let s = c.h() { //expected-error{{ambiguous use of 'h()'}} return s } } enum SR_7799 { case baz case bar } let sr7799: SR_7799? = .bar switch sr7799 { case .bar?: break // Ok case .baz: break // Ok default: break } let sr7799_1: SR_7799?? = .baz switch sr7799_1 { case .bar?: break // Ok case .baz: break // Ok default: break } if case .baz = sr7799_1 {} // Ok if case .bar? = sr7799_1 {} // Ok // rdar://problem/60048356 - `if case` fails when `_` pattern doesn't have a label func rdar_60048356() { typealias Info = (code: ErrorCode, reason: String) enum ErrorCode { case normalClosure } enum Failure { case closed(Info) // expected-note {{'closed' declared here}} } enum Reason { case close(Failure) } func test(_ reason: Reason) { if case .close(.closed((code: .normalClosure, _))) = reason { // Ok } } // rdar://problem/60061646 func test(e: Failure) { if case .closed(code: .normalClosure, _) = e { // Ok // expected-warning@-1 {{enum case 'closed' has one associated value that is a tuple of 2 elements}} } } enum E { case foo((x: Int, y: Int)) // expected-note {{declared here}} case bar(x: Int, y: Int) // expected-note {{declared here}} } func test_destructing(e: E) { if case .foo(let x, let y) = e { // Ok (destructring) // expected-warning@-1 {{enum case 'foo' has one associated value that is a tuple of 2 elements}} _ = x == y } if case .bar(let tuple) = e { // Ok (matching via tuple) // expected-warning@-1 {{enum case 'bar' has 2 associated values; matching them as a tuple is deprecated}} _ = tuple.0 == tuple.1 } } } // rdar://problem/63510989 - valid pattern doesn't type-check func rdar63510989() { enum Value : P { func p() {} } enum E { case single(P?) case double(P??) case triple(P???) } func test(e: E) { if case .single(_ as Value) = e {} // Ok if case .single(let v as Value) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .double(_ as Value) = e {} // Ok if case .double(let v as Value) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .double(let v as Value?) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .triple(_ as Value) = e {} // Ok if case .triple(let v as Value) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .triple(let v as Value?) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .triple(let v as Value??) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} } } // rdar://problem/64157451 - compiler crash when using undefined type in pattern func rdar64157451() { enum E { case foo(Int) } func test(e: E) { if case .foo(let v as DoeNotExist) = e {} // expected-error {{cannot find type 'DoeNotExist' in scope}} } }
apache-2.0
99493568998d9c9c99f80c73b13cb50c
24.598837
208
0.6273
3.555585
false
false
false
false
PavelGnatyuk/SimplePurchase
SimplePurchase/SimplePurchaseTests/AppProductInfoUpdater_Tests.swift
1
4575
// // AppProductInfoUpdater_Tests.swift // FairyTales // // Created by Pavel Gnatyuk on 28/04/2017. // // import XCTest class AppProductInfoUpdater_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 testUpdaterCreation() { let timeout: TimeInterval = 123 let mock = TestPurchaseController() let updater = AppProductInfoUpdater(purchaseController: mock, timeout: timeout) XCTAssertTrue(updater.timeout == timeout, "Timeout in the updater is not initialized correctly") XCTAssertFalse(updater.updateNeeded, "Update should be true. The Updater instance was just created.") } func testUpdaterFirstRequest() { let timeout: TimeInterval = 123 let mock = TestPurchaseController() mock.identifiers = ["1"] // Dummy product identifier mock.isReadyToRequest = true let updater = AppProductInfoUpdater(purchaseController: mock, timeout: timeout) XCTAssertTrue(updater.updateNeeded, "Updater gives a wrong result. The product info has not been requested") XCTAssertTrue(updater.lastTime == nil, "Last time is supposed to be nil for this case") } func testUpdaterRequest() { let timeout: TimeInterval = 123 let mock = TestPurchaseController() mock.identifiers = ["1"] // Dummy product identifier mock.isReadyToRequest = true let updater = AppProductInfoUpdater(purchaseController: mock, timeout: timeout) let requested = updater.updateIfNeeded() XCTAssertTrue(requested, "Product info was not requested. But it should. The updater was just created.") XCTAssert(mock.requestCounter == 1, "Product info should be requested one time") XCTAssertTrue(updater.lastTime != nil, "Last time cannot be nil after the request") } func testUpdaterRequestTimeOut() { let timeout: TimeInterval = 123 let mock = TestPurchaseController() mock.identifiers = ["1"] // Dummy product identifier mock.isReadyToRequest = true let updater = AppProductInfoUpdater(purchaseController: mock, timeout: timeout) var requested = updater.updateIfNeeded() XCTAssertTrue(requested, "Product info was not requested. But it should. The updater was just created.") XCTAssert(mock.requestCounter == 1, "Product info should be requested one time") XCTAssertTrue(updater.lastTime != nil, "Last time cannot be nil after the request") mock.requestCounter = 0 let stamp = updater.lastTime! requested = updater.updateIfNeeded() XCTAssertFalse(requested, "Product info was requested. But it should not") XCTAssert(mock.requestCounter == 0, "Product info should not be requested") XCTAssertEqual(stamp, updater.lastTime!, "Last time is not supposed to change here") } func testUpdaterRequestAfterTimeOut() { let timeout: TimeInterval = 1.5 let mock = TestPurchaseController() mock.identifiers = ["1"] // Dummy product identifier mock.isReadyToRequest = true let updater = AppProductInfoUpdater(purchaseController: mock, timeout: timeout) var requested = updater.updateIfNeeded() XCTAssertTrue(requested, "Product info was not requested. But it should. The updater was just created.") XCTAssert(mock.requestCounter == 1, "Product info should be requested one time") XCTAssertTrue(updater.lastTime != nil, "Last time cannot be nil after the request") mock.requestCounter = 0 mock.isReadyToRequest = true let stamp = updater.lastTime! let expecting = expectation(description: "Wait") DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) { requested = updater.updateIfNeeded() XCTAssertTrue(requested, "Product info was requested. But it should not") XCTAssert(mock.requestCounter == 1, "Product info should be requested") XCTAssertNotEqual(stamp, updater.lastTime!, "Last time is not supposed to change here") expecting.fulfill() } wait(for: [expecting], timeout: 1200) } }
apache-2.0
bab8f770a19cea8300a5d6a7c7954b53
42.571429
116
0.666011
4.940605
false
true
false
false
playstones/NEKit
src/Utils.swift
1
3734
import Foundation public struct Utils { public struct HTTPData { public static let DoubleCRLF = "\r\n\r\n".data(using: String.Encoding.utf8)! public static let CRLF = "\r\n".data(using: String.Encoding.utf8)! public static let ConnectSuccessResponse = "HTTP/1.1 200 Connection Established\r\n\r\n".data(using: String.Encoding.utf8)! } public struct DNS { // swiftlint:disable:next nesting public enum QueryType { // swiftlint:disable:next type_name case a, aaaa, unspec } public static func resolve(_ name: String, type: QueryType = .unspec) -> String { let remoteHostEnt = gethostbyname2((name as NSString).utf8String, AF_INET) if remoteHostEnt == nil { return "" } let remoteAddr = UnsafeMutableRawPointer(remoteHostEnt?.pointee.h_addr_list[0]) var output = [Int8](repeating: 0, count: Int(INET6_ADDRSTRLEN)) inet_ntop(AF_INET, remoteAddr, &output, socklen_t(INET6_ADDRSTRLEN)) return NSString(utf8String: output)! as String } } // swiftlint:disable:next type_name public struct IP { public static func isIPv4(_ ipAddress: String) -> Bool { if IPv4ToInt(ipAddress) != nil { return true } else { return false } } public static func isIPv6(_ ipAddress: String) -> Bool { let utf8Str = (ipAddress as NSString).utf8String var dst = [UInt8](repeating: 0, count: 16) return inet_pton(AF_INET6, utf8Str, &dst) == 1 } public static func isIP(_ ipAddress: String) -> Bool { return isIPv4(ipAddress) || isIPv6(ipAddress) } public static func IPv4ToInt(_ ipAddress: String) -> UInt32? { let utf8Str = (ipAddress as NSString).utf8String var dst = in_addr(s_addr: 0) if inet_pton(AF_INET, utf8Str, &(dst.s_addr)) == 1 { return UInt32(dst.s_addr) } else { return nil } } public static func IPv4ToBytes(_ ipAddress: String) -> [UInt8]? { if let ipv4int = IPv4ToInt(ipAddress) { return Utils.toByteArray(ipv4int).reversed() } else { return nil } } public static func IPv6ToBytes(_ ipAddress: String) -> [UInt8]? { let utf8Str = (ipAddress as NSString).utf8String var dst = [UInt8](repeating: 0, count: 16) if inet_pton(AF_INET6, utf8Str, &dst) == 1 { return Utils.toByteArray(dst).reversed() } else { return nil } } } struct GeoIPLookup { static func Lookup(_ ipAddress: String) -> String? { if Utils.IP.isIP(ipAddress) { guard let result = GeoIP.LookUp(ipAddress) else { return "--" } return result.isoCode } else { return nil } } } static func toByteArray<T>(_ value: T) -> [UInt8] { var value = value return withUnsafeBytes(of: &value) { Array($0) } } struct Random { static func fill(data: inout Data, from: Int = 0, to: Int = -1) { data.withUnsafeMutableBytes { arc4random_buf($0.advanced(by: from), to == -1 ? data.count - from : to - from) } } static func fill(data: inout Data, from: Int = 0, length: Int) { fill(data: &data, from: from, to: from + length) } } }
bsd-3-clause
a13a8881a361e54d747614a76488dc3a
32.044248
131
0.527584
4.172067
false
false
false
false
adamdahan/SwiftStructures
Source/Factories/Graph.swift
10
11017
// // GraphFactory.swift // SwiftStructures // // Created by Wayne Bishop on 6/7/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation public class SwiftGraph { //declare a default directed graph canvas private var canvas: Array<Vertex> public var isDirected: Bool init() { canvas = Array<Vertex>() isDirected = true } //create a new vertex func addVertex(#key: String) -> Vertex { //set the key var childVertex: Vertex = Vertex() childVertex.key = key //add the vertex to the graph canvas canvas.append(childVertex) return childVertex } //add edge to source vertex func addEdge(#source: Vertex, neighbor: Vertex, weight: Int) { //create a new edge var newEdge = Edge() //establish the default properties newEdge.neighbor = neighbor newEdge.weight = weight source.neighbors.append(newEdge) println("The neighbor of vertex: \(source.key as String!) is \(neighbor.key as String!)..") //check condition for an undirected graph if (isDirected == false) { //create a new reversed edge var reverseEdge = Edge() //estabish the reversed properties reverseEdge.neighbor = source reverseEdge.weight = weight neighbor.neighbors.append(reverseEdge) println("The neighbor of vertex: \(neighbor.key as String!) is \(source.key as String!)..") } } /* reverse the sequence of paths given the shortest path. process analagous to reversing a linked list. */ func reversePath(var head: Path!, source: Vertex) -> Path! { if head == nil { return nil } var current: Path! = head var prev: Path! var next: Path! while(current != nil) { next = current.previous current.previous = prev prev = current current = next } //append the source path to the sequence var sourcePath: Path = Path() sourcePath.destination = source sourcePath.previous = prev sourcePath.total = nil head = sourcePath return head } //process Dijkstra's shortest path algorthim func processDijkstra(source: Vertex, destination: Vertex) -> Path? { var frontier: Array<Path> = Array<Path>() var finalPaths: Array<Path> = Array<Path>() //use source edges to create the frontier for e in source.neighbors { var newPath: Path = Path() newPath.destination = e.neighbor newPath.previous = nil newPath.total = e.weight //add the new path to the frontier frontier.append(newPath) } //construct the best path var bestPath: Path = Path() while frontier.count != 0 { //support path changes using the greedy approach bestPath = Path() var pathIndex: Int = 0 for x in 0..<frontier.count { var itemPath: Path = frontier[x] if (bestPath.total == nil) || (itemPath.total < bestPath.total) { bestPath = itemPath pathIndex = x } } //enumerate the bestPath edges for e in bestPath.destination.neighbors { var newPath: Path = Path() newPath.destination = e.neighbor newPath.previous = bestPath newPath.total = bestPath.total + e.weight //add the new path to the frontier frontier.append(newPath) } //preserve the bestPath finalPaths.append(bestPath) //remove the bestPath from the frontier frontier.removeAtIndex(pathIndex) } //end while //establish the shortest path as an optional var shortestPath: Path! = Path() for itemPath in finalPaths { if (itemPath.destination.key == destination.key) { if (shortestPath.total == nil) || (itemPath.total < shortestPath.total) { shortestPath = itemPath } } } return shortestPath } ///an optimized version of Dijkstra's shortest path algorthim func processDijkstraWithHeap(source: Vertex, destination: Vertex) -> Path! { var frontier: PathHeap = PathHeap() var finalPaths: PathHeap = PathHeap() //use source edges to create the frontier for e in source.neighbors { var newPath: Path = Path() newPath.destination = e.neighbor newPath.previous = nil newPath.total = e.weight //add the new path to the frontier frontier.enQueue(newPath) } //construct the best path var bestPath: Path = Path() while frontier.count != 0 { //use the greedy approach to obtain the best path bestPath = Path() bestPath = frontier.peek() //enumerate the bestPath edges for e in bestPath.destination.neighbors { var newPath: Path = Path() newPath.destination = e.neighbor newPath.previous = bestPath newPath.total = bestPath.total + e.weight //add the new path to the frontier frontier.enQueue(newPath) } //preserve the bestPaths that match destination if (bestPath.destination.key == destination.key) { finalPaths.enQueue(bestPath) } //remove the bestPath from the frontier frontier.deQueue() } //end while //obtain the shortest path from the heap var shortestPath: Path! = Path() shortestPath = finalPaths.peek() return shortestPath } //MARK: traversal algorithms //bfs traversal with inout closure function func traverse(startingv: Vertex, formula: (inout node: Vertex) -> ()) { //establish a new queue var graphQueue: Queue<Vertex> = Queue<Vertex>() //queue a starting vertex graphQueue.enQueue(startingv) while !graphQueue.isEmpty() { //traverse the next queued vertex var vitem: Vertex = graphQueue.deQueue() as Vertex! //add unvisited vertices to the queue for e in vitem.neighbors { if e.neighbor.visited == false { println("adding vertex: \(e.neighbor.key!) to queue..") graphQueue.enQueue(e.neighbor) } } /* notes: this demonstrates how to invoke a closure with an inout parameter. By passing by reference no return value is required. */ //invoke formula formula(node: &vitem) } //end while println("graph traversal complete..") } //breadth first search func traverse(startingv: Vertex) { //establish a new queue var graphQueue: Queue<Vertex> = Queue<Vertex>() //queue a starting vertex graphQueue.enQueue(startingv) while !graphQueue.isEmpty() { //traverse the next queued vertex var vitem = graphQueue.deQueue() as Vertex! //add unvisited vertices to the queue for e in vitem.neighbors { if e.neighbor.visited == false { println("adding vertex: \(e.neighbor.key!) to queue..") graphQueue.enQueue(e.neighbor) } } vitem.visited = true println("traversed vertex: \(vitem.key!)..") } //end while println("graph traversal complete..") } //end function //use bfs with trailing closure to update all values func update(startingv: Vertex, formula:(Vertex -> Bool)) { //establish a new queue var graphQueue: Queue<Vertex> = Queue<Vertex>() //queue a starting vertex graphQueue.enQueue(startingv) while !graphQueue.isEmpty() { //traverse the next queued vertex var vitem = graphQueue.deQueue() as Vertex! //add unvisited vertices to the queue for e in vitem.neighbors { if e.neighbor.visited == false { println("adding vertex: \(e.neighbor.key!) to queue..") graphQueue.enQueue(e.neighbor) } } //apply formula.. if formula(vitem) == false { println("formula unable to update: \(vitem.key)") } else { println("traversed vertex: \(vitem.key!)..") } vitem.visited = true } //end while println("graph traversal complete..") } }
mit
80e01a45c8b5f00ed07411a97dfac0e8
23.927602
103
0.454843
5.897752
false
false
false
false
SoufianeLasri/Sisley
Sisley/CarouselController.swift
1
3221
// // CarouselController.swift // Sisley // // Created by Soufiane Lasri on 28/12/2015. // Copyright © 2015 Soufiane Lasri. All rights reserved. // import UIKit protocol CustomCarouselDelegate: class { func toggleButtons( index: Int ) } class CustomCarouselView: UIScrollView, UIScrollViewDelegate { var views: [ UIView ]! var dots: [ DotView ] = [] var customDelegate: CustomCarouselDelegate? init( frame: CGRect, data: [ String : AnyObject ], comments: Bool ) { super.init( frame: frame ) self.backgroundColor = UIColor.whiteColor() self.bounces = false self.pagingEnabled = true self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.delegate = self if comments == true { self.views = [ PackShotView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ), data: data[ "packShotView" ] as! [ String : String ] ), DetailsView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ), data: data[ "detailsView" ] as! [ String : String ] ), CommentView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ) ), ReactionsView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ), data: data[ "reactionsView" ] as! [ [ String : String ] ] ) ] } else { self.views = [ PackShotView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ), data: data[ "packShotView" ] as! [ String : String ] ), DetailsView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ), data: data[ "detailsView" ] as! [ String : String ] ), ReactionsView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ), data: data[ "reactionsView" ] as! [ [ String : String ] ] ) ] } for ( index, item ) in self.views.enumerate() { item.frame.origin.x = self.frame.width * CGFloat( index ) self.addSubview( item ) } for i in 0..<self.views.count { let xPosition = self.frame.width / 2 + CGFloat( 15 * ( i - 2 ) ) + 42 let dot = DotView( frame: CGRect( x: xPosition, y: self.frame.height - 50, width: 7, height: 7 ) ) self.dots.append( dot ) } self.contentSize = CGSize( width: self.frame.width * CGFloat( self.views.count ), height: self.frame.height ) scrollViewDidScroll( self ) } func scrollViewDidScroll(scrollView: UIScrollView) { let indexOfPage: Int = Int( ( self.contentOffset.x + self.frame.width / 2 ) / self.frame.width ) for ( index, item ) in self.dots.enumerate() { if indexOfPage == index { item.toggleDot( true ) } else { item.toggleDot( false ) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
22bbd60ff4c7b381804c95f74651fd25
40.818182
171
0.573602
3.955774
false
false
false
false
lyp1992/douyu-Swift
YPTV/YPTV/Classes/Tools/NibLoadable.swift
1
505
// // NibLoadable.swift // YPTV // // Created by 赖永鹏 on 2019/1/9. // Copyright © 2019年 LYP. All rights reserved. // import UIKit protocol NibLoadable { } extension NibLoadable where Self : UIView { static func loadFromNib (_ nibName : String? = nil) -> Self{ // let loadName = nibName == nil ? "\(self)" : nibName! let loadName = nibName ?? "\(self)" return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self } }
mit
dee2d2e900f508b0c05d7c1f43abe26d
20.565217
91
0.602823
3.568345
false
false
false
false
15cm/AMM
AMM/UIComponent/AMMMenuItemBox.swift
1
906
// // MenuItemBox.swift // AMM // // Created by Sinkerine on 02/02/2017. // Copyright © 2017 sinkerine. All rights reserved. // import Cocoa class AMMMenuItemBox: NSBox, AMMHighlightable { var normalBackgroundColor: NSColor? = nil override func draw(_ dirtyRect: NSRect) { // Drawing code here. if let isHighlighted = enclosingMenuItem?.isHighlighted { if isHighlighted { highlight() } else { noHighlight() } } else { noHighlight() } super.draw(dirtyRect) } override func awakeFromNib() { normalBackgroundColor = self.fillColor self.borderWidth = 0.5 } func highlight() { self.fillColor = AMMHighLightColors.background.color() } func noHighlight() { self.fillColor = normalBackgroundColor! } }
gpl-3.0
489d20271a0a2876c568854a02dc9348
21.073171
65
0.574586
4.547739
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/String+LinkParsing.swift
1
5177
/// Detect Wiki namespace in strings. For example, detect that "/wiki/Talk:Dog" is a talk page and "/wiki/Special:ApiSandbox" is a special page extension String { static let namespaceRegex = try! NSRegularExpression(pattern: "^(.+?)_*:_*(.*)$") // Assumes the input is the remainder of a /wiki/ path func namespaceOfWikiResourcePath(with languageCode: String) -> PageNamespace { guard let namespaceString = String.namespaceRegex.firstReplacementString(in: self) else { return .main } return WikipediaURLTranslations.commonNamespace(for: namespaceString, in: languageCode) ?? .main } public func namespaceAndTitleOfWikiResourcePath(with languageCode: String) -> (namespace: PageNamespace, title: String) { guard let result = String.namespaceRegex.firstMatch(in: self) else { return (.main, self) } let namespaceString = String.namespaceRegex.replacementString(for: result, in: self, offset: 0, template: "$1") guard let namespace = WikipediaURLTranslations.commonNamespace(for: namespaceString, in: languageCode) else { return (.main, self) } let title = String.namespaceRegex.replacementString(for: result, in: self, offset: 0, template: "$2") return (namespace, title) } static let wikiResourceRegex = try! NSRegularExpression(pattern: "^/wiki/(.+)$", options: .caseInsensitive) var wikiResourcePath: String? { return String.wikiResourceRegex.firstReplacementString(in: self) } static let wResourceRegex = try! NSRegularExpression(pattern: "^/w/(.+)$", options: .caseInsensitive) public var wResourcePath: String? { return String.wResourceRegex.firstReplacementString(in: self) } public var fullRange: NSRange { return NSRange(startIndex..<endIndex, in: self) } public func extractingArticleTitleFromTalkPage(languageCode: String) -> String? { if let namespaceString = String.namespaceRegex.firstReplacementString(in: self) { let namespaceStringWithColon = "\(namespaceString):" if namespaceOfWikiResourcePath(with: languageCode) == .talk { return replacingOccurrences(of: namespaceStringWithColon, with: "") } } return nil } } /// Page title transformation public extension String { var percentEncodedPageTitleForPathComponents: String? { return denormalizedPageTitle?.addingPercentEncoding(withAllowedCharacters: .encodeURIComponentAllowed) } var normalizedPageTitle: String? { return replacingOccurrences(of: "_", with: " ").precomposedStringWithCanonicalMapping } var denormalizedPageTitle: String? { return replacingOccurrences(of: " ", with: "_").precomposedStringWithCanonicalMapping } var asTalkPageFragment: String? { let denormalizedName = replacingOccurrences(of: " ", with: "_") let unlinkedName = denormalizedName.replacingOccurrences(of: "[[", with: "").replacingOccurrences(of: "]]", with: "") return unlinkedName.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.wmf_encodeURIComponentAllowed()) } // assumes string is already normalized var googleFormPercentEncodedPageTitle: String? { return googleFormPageTitle?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) } var googleFormPageTitle: String? { return replacingOccurrences(of: " ", with: "+").precomposedStringWithCanonicalMapping } var unescapedNormalizedPageTitle: String? { return removingPercentEncoding?.normalizedPageTitle } var isReferenceFragment: Bool { return contains("ref_") } var isCitationFragment: Bool { return contains("cite_note") } var isEndNoteFragment: Bool { return contains("endnote_") } } @objc extension NSString { /// Deprecated - use namespace methods @objc var wmf_isWikiResource: Bool { return (self as String).wikiResourcePath != nil } /// Deprecated - use swift methods @objc var wmf_pathWithoutWikiPrefix: String? { return (self as String).wikiResourcePath } /// Deprecated - use swift methods @objc var wmf_denormalizedPageTitle: String? { return (self as String).denormalizedPageTitle } /// Deprecated - use swift methods @objc var wmf_normalizedPageTitle: String? { return (self as String).normalizedPageTitle } /// Deprecated - use swift methods @objc var wmf_unescapedNormalizedPageTitle: String? { return (self as String).unescapedNormalizedPageTitle } /// Deprecated - use swift methods @objc var wmf_isReferenceFragment: Bool { return (self as String).isReferenceFragment } /// Deprecated - use swift methods @objc var wmf_isCitationFragment: Bool { return (self as String).isCitationFragment } /// Deprecated - use swift methods @objc var wmf_isEndNoteFragment: Bool { return (self as String).isEndNoteFragment } }
mit
d39cd8425dbb9d0180d9300f1b7199ac
37.066176
143
0.674715
4.911765
false
false
false
false
BPForEveryone/BloodPressureForEveryone
BPApp/Shared/BPNormsTable.swift
1
68790
// // BPNormsTable.swift // BPApp // // Created by MiningMarsh on 10/31/17. // Copyright © 2017 BlackstoneBuilds. All rights reserved. // import Foundation class BPNormsTable { private class NormsTable { // Binary tree implementing range checks. // First you add all nodes, then you call balance() private class HeightRangeTree { // The tree gets flattened into a list. private var rangeTree: [BPNormsEntry] = [] public var RangeTree: [BPNormsEntry] { get { balance() return self.rangeTree } } // Whether the tree is currently balanced. private var balanced: Bool = true // Add a range. public func append(newElement: BPNormsEntry) { rangeTree.append(newElement) balanced = false } // Balance the tree. private func balance() { // Sort the list so we can balance around the center node. rangeTree = rangeTree.sorted { return $0.heightInMeters < $1.heightInMeters } // Tree is now "balanced" in that we can do a binary search on it now. } // Index by value. public subscript(heightInMeters: Double) -> BPNormsEntry { get { // Make sure tree is balanced. if (!balanced) { balance() } // Upper limit of binary search. var upper: Int = rangeTree.count // Lower limit of binary search. var lower: Int = 0 // If the height is lower than first entry, use first entry. if (heightInMeters <= rangeTree[0].heightInMeters) { return self.rangeTree[0] } // If the age is higher than last entry, use last entry. if (heightInMeters >= rangeTree[rangeTree.count - 1].heightInMeters) { return self.rangeTree[rangeTree.count - 1] } // Find node. while (true) { // The target index to check. let index: Int = (upper + lower) / 2 // Check the height is in the target range. if (heightInMeters >= rangeTree[index].heightInMeters && (index != rangeTree.count && heightInMeters < rangeTree[index + 1].heightInMeters)) { return self.rangeTree[index] } // Recurse. if (heightInMeters < rangeTree[index].heightInMeters) { upper = index } else { lower = index } } } } } // Indexed by age, then sex, then contains a height object. private var table: [[HeightRangeTree?]] = [] // Get age from date. private func age(from: Date) -> Int { return NSCalendar.current.dateComponents( Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year]), from: from, to: Date() ).year! } init?(norms: BPNormsEntry...) { // Push all norms to tree. for norm in norms { let normAge = norm.age - 1 // Make sure the table has room for this entry. while table.count <= normAge { table.append([nil, nil]) } // Convert sex to index. let sexIndex = norm.sex == Patient.Sex.male ? 0 : 1 // Make sure the range tree exists. if table[normAge][sexIndex] == nil { table[normAge][sexIndex] = HeightRangeTree() } // Add entry. table[normAge][sexIndex]!.append(newElement: norm) } } // Index the table. public func index(patient: Patient) -> BPNormsEntry { // Convert sex to index. let sexIndex = patient.sex == Patient.Sex.male ? 0 : 1 let page = age(from: patient.birthDate) - 1; // Edge cases. if (page <= 1) { return table[0][sexIndex]![patient.height.meters]; } // Edge cases. if (page >= table.count - 1) { return table[table.count - 1][sexIndex]![patient.height.meters]; } return table[page][sexIndex]![patient.height.meters] } // Index the table using only Sex and Age public func indexForArray(patient: Patient) -> [BPNormsEntry] { // Convert sex to index. let sexIndex = patient.sex == Patient.Sex.male ? 0 : 1 let page = age(from: patient.birthDate) - 1; // Edge cases. if (page <= 1) { return table[0][sexIndex]!.RangeTree } // Edge cases. if (page >= table.count - 1) { return table[table.count - 1][sexIndex]!.RangeTree } return table[page][sexIndex]!.RangeTree } } public static func index(patient: Patient) -> BPNormsEntry { return self.normsTable.index(patient: patient); } public static func indexForArray(patient: Patient) -> [BPNormsEntry] { return self.normsTable.indexForArray(patient: patient); } // The following table is autogenerated by a script, do not touch! static private var normsTable: NormsTable = NormsTable(norms: BPNormsEntry( age: 1, sex: Patient.Sex.male, heightInMeters: 0.77200000000000002, systolic50: 85, systolic90: 98, systolic95: 102, systolic95plus: 114, diastolic50: 40, diastolic90: 52, diastolic95: 54, diastolic95plus: 66 )!, BPNormsEntry( age: 1, sex: Patient.Sex.male, heightInMeters: 0.78299999999999992, systolic50: 85, systolic90: 99, systolic95: 102, systolic95plus: 114, diastolic50: 40, diastolic90: 52, diastolic95: 54, diastolic95plus: 66 )!, BPNormsEntry( age: 1, sex: Patient.Sex.male, heightInMeters: 0.80200000000000005, systolic50: 86, systolic90: 99, systolic95: 103, systolic95plus: 115, diastolic50: 40, diastolic90: 53, diastolic95: 55, diastolic95plus: 67 )!, BPNormsEntry( age: 1, sex: Patient.Sex.male, heightInMeters: 0.82400000000000007, systolic50: 86, systolic90: 100, systolic95: 103, systolic95plus: 115, diastolic50: 41, diastolic90: 53, diastolic95: 55, diastolic95plus: 67 )!, BPNormsEntry( age: 1, sex: Patient.Sex.male, heightInMeters: 0.84599999999999997, systolic50: 87, systolic90: 100, systolic95: 104, systolic95plus: 116, diastolic50: 41, diastolic90: 54, diastolic95: 56, diastolic95plus: 68 )!, BPNormsEntry( age: 1, sex: Patient.Sex.male, heightInMeters: 0.86699999999999999, systolic50: 88, systolic90: 101, systolic95: 105, systolic95plus: 117, diastolic50: 42, diastolic90: 54, diastolic95: 57, diastolic95plus: 69 )!, BPNormsEntry( age: 1, sex: Patient.Sex.male, heightInMeters: 0.879, systolic50: 88, systolic90: 101, systolic95: 105, systolic95plus: 117, diastolic50: 42, diastolic90: 54, diastolic95: 57, diastolic95plus: 69 )!, BPNormsEntry( age: 2, sex: Patient.Sex.male, heightInMeters: 0.86099999999999999, systolic50: 87, systolic90: 100, systolic95: 104, systolic95plus: 116, diastolic50: 43, diastolic90: 55, diastolic95: 57, diastolic95plus: 69 )!, BPNormsEntry( age: 2, sex: Patient.Sex.male, heightInMeters: 0.87400000000000011, systolic50: 87, systolic90: 100, systolic95: 105, systolic95plus: 117, diastolic50: 43, diastolic90: 55, diastolic95: 58, diastolic95plus: 70 )!, BPNormsEntry( age: 2, sex: Patient.Sex.male, heightInMeters: 0.89599999999999991, systolic50: 88, systolic90: 101, systolic95: 105, systolic95plus: 117, diastolic50: 44, diastolic90: 56, diastolic95: 58, diastolic95plus: 70 )!, BPNormsEntry( age: 2, sex: Patient.Sex.male, heightInMeters: 0.92099999999999993, systolic50: 89, systolic90: 102, systolic95: 106, systolic95plus: 118, diastolic50: 44, diastolic90: 56, diastolic95: 59, diastolic95plus: 71 )!, BPNormsEntry( age: 2, sex: Patient.Sex.male, heightInMeters: 0.94700000000000006, systolic50: 89, systolic90: 103, systolic95: 107, systolic95plus: 119, diastolic50: 45, diastolic90: 57, diastolic95: 60, diastolic95plus: 72 )!, BPNormsEntry( age: 2, sex: Patient.Sex.male, heightInMeters: 0.97099999999999997, systolic50: 90, systolic90: 103, systolic95: 107, systolic95plus: 119, diastolic50: 46, diastolic90: 58, diastolic95: 61, diastolic95plus: 73 )!, BPNormsEntry( age: 2, sex: Patient.Sex.male, heightInMeters: 0.98499999999999999, systolic50: 91, systolic90: 104, systolic95: 108, systolic95plus: 120, diastolic50: 46, diastolic90: 58, diastolic95: 61, diastolic95plus: 73 )!, BPNormsEntry( age: 3, sex: Patient.Sex.male, heightInMeters: 0.92500000000000004, systolic50: 88, systolic90: 101, systolic95: 106, systolic95plus: 118, diastolic50: 45, diastolic90: 58, diastolic95: 60, diastolic95plus: 72 )!, BPNormsEntry( age: 3, sex: Patient.Sex.male, heightInMeters: 0.93900000000000006, systolic50: 89, systolic90: 102, systolic95: 106, systolic95plus: 118, diastolic50: 46, diastolic90: 58, diastolic95: 61, diastolic95plus: 73 )!, BPNormsEntry( age: 3, sex: Patient.Sex.male, heightInMeters: 0.96299999999999997, systolic50: 89, systolic90: 102, systolic95: 107, systolic95plus: 119, diastolic50: 46, diastolic90: 59, diastolic95: 61, diastolic95plus: 73 )!, BPNormsEntry( age: 3, sex: Patient.Sex.male, heightInMeters: 0.98999999999999999, systolic50: 90, systolic90: 103, systolic95: 107, systolic95plus: 119, diastolic50: 47, diastolic90: 59, diastolic95: 62, diastolic95plus: 74 )!, BPNormsEntry( age: 3, sex: Patient.Sex.male, heightInMeters: 1.018, systolic50: 91, systolic90: 104, systolic95: 108, systolic95plus: 120, diastolic50: 48, diastolic90: 60, diastolic95: 63, diastolic95plus: 75 )!, BPNormsEntry( age: 3, sex: Patient.Sex.male, heightInMeters: 1.0429999999999999, systolic50: 92, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 49, diastolic90: 61, diastolic95: 64, diastolic95plus: 76 )!, BPNormsEntry( age: 3, sex: Patient.Sex.male, heightInMeters: 1.0580000000000001, systolic50: 92, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 49, diastolic90: 61, diastolic95: 64, diastolic95plus: 76 )!, BPNormsEntry( age: 4, sex: Patient.Sex.male, heightInMeters: 0.98499999999999999, systolic50: 90, systolic90: 102, systolic95: 107, systolic95plus: 119, diastolic50: 48, diastolic90: 60, diastolic95: 63, diastolic95plus: 75 )!, BPNormsEntry( age: 4, sex: Patient.Sex.male, heightInMeters: 1.002, systolic50: 90, systolic90: 103, systolic95: 107, systolic95plus: 119, diastolic50: 49, diastolic90: 61, diastolic95: 64, diastolic95plus: 76 )!, BPNormsEntry( age: 4, sex: Patient.Sex.male, heightInMeters: 1.0290000000000001, systolic50: 91, systolic90: 104, systolic95: 108, systolic95plus: 120, diastolic50: 49, diastolic90: 62, diastolic95: 65, diastolic95plus: 77 )!, BPNormsEntry( age: 4, sex: Patient.Sex.male, heightInMeters: 1.0590000000000002, systolic50: 92, systolic90: 105, systolic95: 108, systolic95plus: 120, diastolic50: 50, diastolic90: 62, diastolic95: 66, diastolic95plus: 78 )!, BPNormsEntry( age: 4, sex: Patient.Sex.male, heightInMeters: 1.089, systolic50: 93, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 51, diastolic90: 63, diastolic95: 67, diastolic95plus: 79 )!, BPNormsEntry( age: 4, sex: Patient.Sex.male, heightInMeters: 1.115, systolic50: 94, systolic90: 106, systolic95: 110, systolic95plus: 122, diastolic50: 52, diastolic90: 64, diastolic95: 67, diastolic95plus: 79 )!, BPNormsEntry( age: 4, sex: Patient.Sex.male, heightInMeters: 1.1320000000000001, systolic50: 94, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 52, diastolic90: 64, diastolic95: 68, diastolic95plus: 80 )!, BPNormsEntry( age: 5, sex: Patient.Sex.male, heightInMeters: 1.044, systolic50: 91, systolic90: 103, systolic95: 107, systolic95plus: 119, diastolic50: 51, diastolic90: 63, diastolic95: 66, diastolic95plus: 78 )!, BPNormsEntry( age: 5, sex: Patient.Sex.male, heightInMeters: 1.0620000000000001, systolic50: 92, systolic90: 104, systolic95: 108, systolic95plus: 120, diastolic50: 51, diastolic90: 64, diastolic95: 67, diastolic95plus: 79 )!, BPNormsEntry( age: 5, sex: Patient.Sex.male, heightInMeters: 1.091, systolic50: 93, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 52, diastolic90: 65, diastolic95: 68, diastolic95plus: 80 )!, BPNormsEntry( age: 5, sex: Patient.Sex.male, heightInMeters: 1.1240000000000001, systolic50: 94, systolic90: 106, systolic95: 109, systolic95plus: 121, diastolic50: 53, diastolic90: 65, diastolic95: 69, diastolic95plus: 81 )!, BPNormsEntry( age: 5, sex: Patient.Sex.male, heightInMeters: 1.157, systolic50: 95, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 54, diastolic90: 66, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 5, sex: Patient.Sex.male, heightInMeters: 1.1859999999999999, systolic50: 96, systolic90: 108, systolic95: 111, systolic95plus: 123, diastolic50: 55, diastolic90: 67, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 5, sex: Patient.Sex.male, heightInMeters: 1.2030000000000001, systolic50: 96, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 55, diastolic90: 67, diastolic95: 71, diastolic95plus: 83 )!, BPNormsEntry( age: 6, sex: Patient.Sex.male, heightInMeters: 1.103, systolic50: 93, systolic90: 105, systolic95: 108, systolic95plus: 120, diastolic50: 54, diastolic90: 66, diastolic95: 69, diastolic95plus: 81 )!, BPNormsEntry( age: 6, sex: Patient.Sex.male, heightInMeters: 1.1220000000000001, systolic50: 93, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 54, diastolic90: 66, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 6, sex: Patient.Sex.male, heightInMeters: 1.153, systolic50: 94, systolic90: 106, systolic95: 110, systolic95plus: 122, diastolic50: 55, diastolic90: 67, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 6, sex: Patient.Sex.male, heightInMeters: 1.1890000000000001, systolic50: 95, systolic90: 107, systolic95: 111, systolic95plus: 123, diastolic50: 56, diastolic90: 68, diastolic95: 71, diastolic95plus: 83 )!, BPNormsEntry( age: 6, sex: Patient.Sex.male, heightInMeters: 1.224, systolic50: 96, systolic90: 109, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 68, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 6, sex: Patient.Sex.male, heightInMeters: 1.256, systolic50: 97, systolic90: 110, systolic95: 113, systolic95plus: 125, diastolic50: 57, diastolic90: 69, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 6, sex: Patient.Sex.male, heightInMeters: 1.2749999999999999, systolic50: 98, systolic90: 110, systolic95: 114, systolic95plus: 126, diastolic50: 58, diastolic90: 69, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 7, sex: Patient.Sex.male, heightInMeters: 1.161, systolic50: 94, systolic90: 106, systolic95: 110, systolic95plus: 122, diastolic50: 56, diastolic90: 68, diastolic95: 71, diastolic95plus: 83 )!, BPNormsEntry( age: 7, sex: Patient.Sex.male, heightInMeters: 1.1799999999999999, systolic50: 94, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 56, diastolic90: 68, diastolic95: 71, diastolic95plus: 83 )!, BPNormsEntry( age: 7, sex: Patient.Sex.male, heightInMeters: 1.214, systolic50: 95, systolic90: 108, systolic95: 111, systolic95plus: 123, diastolic50: 57, diastolic90: 69, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 7, sex: Patient.Sex.male, heightInMeters: 1.2509999999999999, systolic50: 97, systolic90: 109, systolic95: 112, systolic95plus: 124, diastolic50: 58, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 7, sex: Patient.Sex.male, heightInMeters: 1.2890000000000001, systolic50: 98, systolic90: 110, systolic95: 114, systolic95plus: 126, diastolic50: 58, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 7, sex: Patient.Sex.male, heightInMeters: 1.3240000000000001, systolic50: 98, systolic90: 111, systolic95: 115, systolic95plus: 127, diastolic50: 59, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 7, sex: Patient.Sex.male, heightInMeters: 1.345, systolic50: 99, systolic90: 111, systolic95: 116, systolic95plus: 128, diastolic50: 59, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 8, sex: Patient.Sex.male, heightInMeters: 1.214, systolic50: 95, systolic90: 107, systolic95: 111, systolic95plus: 123, diastolic50: 57, diastolic90: 69, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 8, sex: Patient.Sex.male, heightInMeters: 1.2350000000000001, systolic50: 96, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 8, sex: Patient.Sex.male, heightInMeters: 1.27, systolic50: 97, systolic90: 109, systolic95: 112, systolic95plus: 124, diastolic50: 58, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 8, sex: Patient.Sex.male, heightInMeters: 1.3100000000000001, systolic50: 98, systolic90: 110, systolic95: 114, systolic95plus: 126, diastolic50: 59, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 8, sex: Patient.Sex.male, heightInMeters: 1.351, systolic50: 99, systolic90: 111, systolic95: 115, systolic95plus: 127, diastolic50: 59, diastolic90: 72, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 8, sex: Patient.Sex.male, heightInMeters: 1.3880000000000001, systolic50: 99, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 60, diastolic90: 72, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 8, sex: Patient.Sex.male, heightInMeters: 1.4099999999999999, systolic50: 100, systolic90: 112, systolic95: 117, systolic95plus: 129, diastolic50: 60, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 9, sex: Patient.Sex.male, heightInMeters: 1.26, systolic50: 96, systolic90: 107, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 70, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 9, sex: Patient.Sex.male, heightInMeters: 1.2830000000000001, systolic50: 97, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 58, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 9, sex: Patient.Sex.male, heightInMeters: 1.321, systolic50: 98, systolic90: 109, systolic95: 113, systolic95plus: 125, diastolic50: 59, diastolic90: 72, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 9, sex: Patient.Sex.male, heightInMeters: 1.3630000000000002, systolic50: 99, systolic90: 110, systolic95: 115, systolic95plus: 127, diastolic50: 60, diastolic90: 73, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 9, sex: Patient.Sex.male, heightInMeters: 1.4069999999999998, systolic50: 100, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 61, diastolic90: 74, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 9, sex: Patient.Sex.male, heightInMeters: 1.4469999999999998, systolic50: 101, systolic90: 113, systolic95: 118, systolic95plus: 130, diastolic50: 62, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 9, sex: Patient.Sex.male, heightInMeters: 1.4709999999999999, systolic50: 101, systolic90: 114, systolic95: 119, systolic95plus: 131, diastolic50: 62, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 10, sex: Patient.Sex.male, heightInMeters: 1.3019999999999998, systolic50: 97, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 59, diastolic90: 72, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 10, sex: Patient.Sex.male, heightInMeters: 1.327, systolic50: 98, systolic90: 109, systolic95: 113, systolic95plus: 125, diastolic50: 60, diastolic90: 73, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 10, sex: Patient.Sex.male, heightInMeters: 1.367, systolic50: 99, systolic90: 111, systolic95: 114, systolic95plus: 126, diastolic50: 61, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 10, sex: Patient.Sex.male, heightInMeters: 1.413, systolic50: 100, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 62, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 10, sex: Patient.Sex.male, heightInMeters: 1.4590000000000001, systolic50: 101, systolic90: 113, systolic95: 118, systolic95plus: 130, diastolic50: 63, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 10, sex: Patient.Sex.male, heightInMeters: 1.5009999999999999, systolic50: 102, systolic90: 115, systolic95: 120, systolic95plus: 132, diastolic50: 63, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 10, sex: Patient.Sex.male, heightInMeters: 1.5269999999999999, systolic50: 103, systolic90: 116, systolic95: 121, systolic95plus: 133, diastolic50: 64, diastolic90: 76, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 11, sex: Patient.Sex.male, heightInMeters: 1.347, systolic50: 99, systolic90: 110, systolic95: 114, systolic95plus: 126, diastolic50: 61, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 11, sex: Patient.Sex.male, heightInMeters: 1.3730000000000002, systolic50: 99, systolic90: 111, systolic95: 114, systolic95plus: 126, diastolic50: 61, diastolic90: 74, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 11, sex: Patient.Sex.male, heightInMeters: 1.415, systolic50: 101, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 62, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 11, sex: Patient.Sex.male, heightInMeters: 1.464, systolic50: 102, systolic90: 114, systolic95: 118, systolic95plus: 130, diastolic50: 63, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 11, sex: Patient.Sex.male, heightInMeters: 1.5130000000000001, systolic50: 103, systolic90: 116, systolic95: 120, systolic95plus: 132, diastolic50: 63, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 11, sex: Patient.Sex.male, heightInMeters: 1.5580000000000001, systolic50: 104, systolic90: 117, systolic95: 123, systolic95plus: 135, diastolic50: 63, diastolic90: 76, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 11, sex: Patient.Sex.male, heightInMeters: 1.5859999999999999, systolic50: 106, systolic90: 118, systolic95: 124, systolic95plus: 136, diastolic50: 63, diastolic90: 76, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 12, sex: Patient.Sex.male, heightInMeters: 1.403, systolic50: 101, systolic90: 113, systolic95: 116, systolic95plus: 128, diastolic50: 61, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 12, sex: Patient.Sex.male, heightInMeters: 1.4299999999999999, systolic50: 101, systolic90: 114, systolic95: 117, systolic95plus: 129, diastolic50: 62, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 12, sex: Patient.Sex.male, heightInMeters: 1.4750000000000001, systolic50: 102, systolic90: 115, systolic95: 118, systolic95plus: 130, diastolic50: 62, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 12, sex: Patient.Sex.male, heightInMeters: 1.5269999999999999, systolic50: 104, systolic90: 117, systolic95: 121, systolic95plus: 133, diastolic50: 62, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 12, sex: Patient.Sex.male, heightInMeters: 1.579, systolic50: 106, systolic90: 119, systolic95: 124, systolic95plus: 136, diastolic50: 62, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 12, sex: Patient.Sex.male, heightInMeters: 1.6259999999999999, systolic50: 108, systolic90: 121, systolic95: 126, systolic95plus: 138, diastolic50: 63, diastolic90: 76, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 12, sex: Patient.Sex.male, heightInMeters: 1.655, systolic50: 109, systolic90: 122, systolic95: 128, systolic95plus: 140, diastolic50: 63, diastolic90: 76, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 13, sex: Patient.Sex.male, heightInMeters: 1.47, systolic50: 103, systolic90: 115, systolic95: 119, systolic95plus: 131, diastolic50: 61, diastolic90: 74, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 13, sex: Patient.Sex.male, heightInMeters: 1.5, systolic50: 104, systolic90: 116, systolic95: 120, systolic95plus: 132, diastolic50: 60, diastolic90: 74, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 13, sex: Patient.Sex.male, heightInMeters: 1.5490000000000002, systolic50: 105, systolic90: 118, systolic95: 122, systolic95plus: 134, diastolic50: 61, diastolic90: 74, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 13, sex: Patient.Sex.male, heightInMeters: 1.6030000000000002, systolic50: 108, systolic90: 121, systolic95: 125, systolic95plus: 137, diastolic50: 62, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 13, sex: Patient.Sex.male, heightInMeters: 1.6569999999999998, systolic50: 110, systolic90: 124, systolic95: 128, systolic95plus: 140, diastolic50: 63, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 13, sex: Patient.Sex.male, heightInMeters: 1.7050000000000001, systolic50: 111, systolic90: 126, systolic95: 130, systolic95plus: 142, diastolic50: 64, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 13, sex: Patient.Sex.male, heightInMeters: 1.734, systolic50: 112, systolic90: 126, systolic95: 131, systolic95plus: 143, diastolic50: 65, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 14, sex: Patient.Sex.male, heightInMeters: 1.538, systolic50: 105, systolic90: 119, systolic95: 123, systolic95plus: 135, diastolic50: 60, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 14, sex: Patient.Sex.male, heightInMeters: 1.569, systolic50: 106, systolic90: 120, systolic95: 125, systolic95plus: 137, diastolic50: 60, diastolic90: 74, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 14, sex: Patient.Sex.male, heightInMeters: 1.6200000000000001, systolic50: 109, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 62, diastolic90: 75, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 14, sex: Patient.Sex.male, heightInMeters: 1.675, systolic50: 111, systolic90: 126, systolic95: 130, systolic95plus: 142, diastolic50: 64, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 14, sex: Patient.Sex.male, heightInMeters: 1.7269999999999999, systolic50: 112, systolic90: 127, systolic95: 132, systolic95plus: 144, diastolic50: 65, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 14, sex: Patient.Sex.male, heightInMeters: 1.774, systolic50: 113, systolic90: 128, systolic95: 133, systolic95plus: 145, diastolic50: 66, diastolic90: 79, diastolic95: 83, diastolic95plus: 95 )!, BPNormsEntry( age: 14, sex: Patient.Sex.male, heightInMeters: 1.8009999999999999, systolic50: 113, systolic90: 129, systolic95: 134, systolic95plus: 146, diastolic50: 67, diastolic90: 80, diastolic95: 84, diastolic95plus: 96 )!, BPNormsEntry( age: 15, sex: Patient.Sex.male, heightInMeters: 1.5900000000000001, systolic50: 108, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 61, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 15, sex: Patient.Sex.male, heightInMeters: 1.6200000000000001, systolic50: 110, systolic90: 124, systolic95: 129, systolic95plus: 141, diastolic50: 62, diastolic90: 76, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 15, sex: Patient.Sex.male, heightInMeters: 1.669, systolic50: 112, systolic90: 126, systolic95: 131, systolic95plus: 143, diastolic50: 64, diastolic90: 78, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 15, sex: Patient.Sex.male, heightInMeters: 1.722, systolic50: 113, systolic90: 128, systolic95: 132, systolic95plus: 144, diastolic50: 65, diastolic90: 79, diastolic95: 83, diastolic95plus: 95 )!, BPNormsEntry( age: 15, sex: Patient.Sex.male, heightInMeters: 1.7719999999999998, systolic50: 114, systolic90: 129, systolic95: 134, systolic95plus: 146, diastolic50: 66, diastolic90: 80, diastolic95: 84, diastolic95plus: 96 )!, BPNormsEntry( age: 15, sex: Patient.Sex.male, heightInMeters: 1.8159999999999998, systolic50: 114, systolic90: 130, systolic95: 135, systolic95plus: 147, diastolic50: 67, diastolic90: 81, diastolic95: 85, diastolic95plus: 97 )!, BPNormsEntry( age: 15, sex: Patient.Sex.male, heightInMeters: 1.8419999999999999, systolic50: 114, systolic90: 130, systolic95: 135, systolic95plus: 147, diastolic50: 68, diastolic90: 81, diastolic95: 85, diastolic95plus: 97 )!, BPNormsEntry( age: 16, sex: Patient.Sex.male, heightInMeters: 1.621, systolic50: 111, systolic90: 126, systolic95: 130, systolic95plus: 142, diastolic50: 63, diastolic90: 77, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 16, sex: Patient.Sex.male, heightInMeters: 1.6499999999999999, systolic50: 112, systolic90: 127, systolic95: 131, systolic95plus: 143, diastolic50: 64, diastolic90: 78, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 16, sex: Patient.Sex.male, heightInMeters: 1.696, systolic50: 114, systolic90: 128, systolic95: 133, systolic95plus: 145, diastolic50: 66, diastolic90: 79, diastolic95: 83, diastolic95plus: 95 )!, BPNormsEntry( age: 16, sex: Patient.Sex.male, heightInMeters: 1.746, systolic50: 115, systolic90: 129, systolic95: 134, systolic95plus: 146, diastolic50: 67, diastolic90: 80, diastolic95: 84, diastolic95plus: 96 )!, BPNormsEntry( age: 16, sex: Patient.Sex.male, heightInMeters: 1.7949999999999999, systolic50: 115, systolic90: 131, systolic95: 135, systolic95plus: 147, diastolic50: 68, diastolic90: 81, diastolic95: 85, diastolic95plus: 97 )!, BPNormsEntry( age: 16, sex: Patient.Sex.male, heightInMeters: 1.8380000000000001, systolic50: 116, systolic90: 131, systolic95: 136, systolic95plus: 148, diastolic50: 69, diastolic90: 82, diastolic95: 86, diastolic95plus: 98 )!, BPNormsEntry( age: 16, sex: Patient.Sex.male, heightInMeters: 1.8640000000000001, systolic50: 116, systolic90: 132, systolic95: 137, systolic95plus: 149, diastolic50: 69, diastolic90: 82, diastolic95: 86, diastolic95plus: 98 )!, BPNormsEntry( age: 17, sex: Patient.Sex.male, heightInMeters: 1.6380000000000001, systolic50: 114, systolic90: 128, systolic95: 132, systolic95plus: 144, diastolic50: 65, diastolic90: 78, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 17, sex: Patient.Sex.male, heightInMeters: 1.665, systolic50: 115, systolic90: 129, systolic95: 133, systolic95plus: 145, diastolic50: 66, diastolic90: 79, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 17, sex: Patient.Sex.male, heightInMeters: 1.7090000000000001, systolic50: 116, systolic90: 130, systolic95: 134, systolic95plus: 146, diastolic50: 67, diastolic90: 80, diastolic95: 84, diastolic95plus: 96 )!, BPNormsEntry( age: 17, sex: Patient.Sex.male, heightInMeters: 1.758, systolic50: 117, systolic90: 131, systolic95: 135, systolic95plus: 147, diastolic50: 68, diastolic90: 81, diastolic95: 85, diastolic95plus: 97 )!, BPNormsEntry( age: 17, sex: Patient.Sex.male, heightInMeters: 1.8069999999999999, systolic50: 117, systolic90: 132, systolic95: 137, systolic95plus: 149, diastolic50: 69, diastolic90: 82, diastolic95: 86, diastolic95plus: 98 )!, BPNormsEntry( age: 17, sex: Patient.Sex.male, heightInMeters: 1.849, systolic50: 118, systolic90: 133, systolic95: 138, systolic95plus: 150, diastolic50: 70, diastolic90: 82, diastolic95: 86, diastolic95plus: 98 )!, BPNormsEntry( age: 17, sex: Patient.Sex.male, heightInMeters: 1.875, systolic50: 118, systolic90: 134, systolic95: 138, systolic95plus: 150, diastolic50: 70, diastolic90: 83, diastolic95: 87, diastolic95plus: 99 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 0.754, systolic50: 84, systolic90: 98, systolic95: 101, systolic95plus: 113, diastolic50: 41, diastolic90: 54, diastolic95: 59, diastolic95plus: 71 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 0.7659999999999999, systolic50: 85, systolic90: 99, systolic95: 102, systolic95plus: 114, diastolic50: 42, diastolic90: 55, diastolic95: 59, diastolic95plus: 71 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 0.78599999999999992, systolic50: 86, systolic90: 99, systolic95: 102, systolic95plus: 114, diastolic50: 42, diastolic90: 56, diastolic95: 60, diastolic95plus: 72 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 0.80799999999999994, systolic50: 86, systolic90: 100, systolic95: 103, systolic95plus: 115, diastolic50: 43, diastolic90: 56, diastolic95: 60, diastolic95plus: 72 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 0.82999999999999996, systolic50: 87, systolic90: 101, systolic95: 104, systolic95plus: 116, diastolic50: 44, diastolic90: 57, diastolic95: 61, diastolic95plus: 73 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 0.84900000000000009, systolic50: 88, systolic90: 102, systolic95: 105, systolic95plus: 117, diastolic50: 45, diastolic90: 58, diastolic95: 62, diastolic95plus: 74 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 0.86099999999999999, systolic50: 88, systolic90: 102, systolic95: 105, systolic95plus: 117, diastolic50: 46, diastolic90: 58, diastolic95: 62, diastolic95plus: 74 )!, BPNormsEntry( age: 2, sex: Patient.Sex.female, heightInMeters: 0.84900000000000009, systolic50: 87, systolic90: 101, systolic95: 104, systolic95plus: 116, diastolic50: 45, diastolic90: 58, diastolic95: 62, diastolic95plus: 74 )!, BPNormsEntry( age: 2, sex: Patient.Sex.female, heightInMeters: 0.86299999999999999, systolic50: 87, systolic90: 101, systolic95: 105, systolic95plus: 117, diastolic50: 46, diastolic90: 58, diastolic95: 63, diastolic95plus: 75 )!, BPNormsEntry( age: 2, sex: Patient.Sex.female, heightInMeters: 0.8859999999999999, systolic50: 88, systolic90: 102, systolic95: 106, systolic95plus: 118, diastolic50: 47, diastolic90: 59, diastolic95: 63, diastolic95plus: 75 )!, BPNormsEntry( age: 2, sex: Patient.Sex.female, heightInMeters: 0.91099999999999992, systolic50: 89, systolic90: 103, systolic95: 106, systolic95plus: 118, diastolic50: 48, diastolic90: 60, diastolic95: 64, diastolic95plus: 76 )!, BPNormsEntry( age: 2, sex: Patient.Sex.female, heightInMeters: 0.93700000000000006, systolic50: 90, systolic90: 104, systolic95: 107, systolic95plus: 119, diastolic50: 49, diastolic90: 61, diastolic95: 65, diastolic95plus: 77 )!, BPNormsEntry( age: 2, sex: Patient.Sex.female, heightInMeters: 0.95999999999999996, systolic50: 91, systolic90: 105, systolic95: 108, systolic95plus: 120, diastolic50: 50, diastolic90: 62, diastolic95: 66, diastolic95plus: 78 )!, BPNormsEntry( age: 2, sex: Patient.Sex.female, heightInMeters: 0.97400000000000009, systolic50: 91, systolic90: 106, systolic95: 109, systolic95plus: 121, diastolic50: 51, diastolic90: 62, diastolic95: 66, diastolic95plus: 78 )!, BPNormsEntry( age: 3, sex: Patient.Sex.female, heightInMeters: 0.91000000000000003, systolic50: 88, systolic90: 102, systolic95: 106, systolic95plus: 118, diastolic50: 48, diastolic90: 60, diastolic95: 64, diastolic95plus: 76 )!, BPNormsEntry( age: 3, sex: Patient.Sex.female, heightInMeters: 0.92400000000000004, systolic50: 89, systolic90: 103, systolic95: 106, systolic95plus: 118, diastolic50: 48, diastolic90: 61, diastolic95: 65, diastolic95plus: 77 )!, BPNormsEntry( age: 3, sex: Patient.Sex.female, heightInMeters: 0.94900000000000007, systolic50: 89, systolic90: 104, systolic95: 107, systolic95plus: 119, diastolic50: 49, diastolic90: 61, diastolic95: 65, diastolic95plus: 77 )!, BPNormsEntry( age: 3, sex: Patient.Sex.female, heightInMeters: 0.97599999999999998, systolic50: 90, systolic90: 104, systolic95: 108, systolic95plus: 120, diastolic50: 50, diastolic90: 62, diastolic95: 66, diastolic95plus: 78 )!, BPNormsEntry( age: 3, sex: Patient.Sex.female, heightInMeters: 1.0049999999999999, systolic50: 91, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 51, diastolic90: 63, diastolic95: 67, diastolic95plus: 79 )!, BPNormsEntry( age: 3, sex: Patient.Sex.female, heightInMeters: 1.0309999999999999, systolic50: 92, systolic90: 106, systolic95: 110, systolic95plus: 122, diastolic50: 53, diastolic90: 64, diastolic95: 68, diastolic95plus: 80 )!, BPNormsEntry( age: 3, sex: Patient.Sex.female, heightInMeters: 1.046, systolic50: 93, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 53, diastolic90: 65, diastolic95: 69, diastolic95plus: 81 )!, BPNormsEntry( age: 4, sex: Patient.Sex.female, heightInMeters: 0.97199999999999998, systolic50: 89, systolic90: 103, systolic95: 107, systolic95plus: 119, diastolic50: 50, diastolic90: 62, diastolic95: 66, diastolic95plus: 78 )!, BPNormsEntry( age: 4, sex: Patient.Sex.female, heightInMeters: 0.98799999999999999, systolic50: 90, systolic90: 104, systolic95: 108, systolic95plus: 120, diastolic50: 51, diastolic90: 63, diastolic95: 67, diastolic95plus: 79 )!, BPNormsEntry( age: 4, sex: Patient.Sex.female, heightInMeters: 1.014, systolic50: 91, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 51, diastolic90: 64, diastolic95: 68, diastolic95plus: 80 )!, BPNormsEntry( age: 4, sex: Patient.Sex.female, heightInMeters: 1.0449999999999999, systolic50: 92, systolic90: 106, systolic95: 109, systolic95plus: 121, diastolic50: 53, diastolic90: 65, diastolic95: 69, diastolic95plus: 81 )!, BPNormsEntry( age: 4, sex: Patient.Sex.female, heightInMeters: 1.0759999999999998, systolic50: 93, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 54, diastolic90: 66, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 4, sex: Patient.Sex.female, heightInMeters: 1.105, systolic50: 94, systolic90: 108, systolic95: 111, systolic95plus: 123, diastolic50: 55, diastolic90: 67, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 4, sex: Patient.Sex.female, heightInMeters: 1.1220000000000001, systolic50: 94, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 55, diastolic90: 67, diastolic95: 71, diastolic95plus: 83 )!, BPNormsEntry( age: 5, sex: Patient.Sex.female, heightInMeters: 1.036, systolic50: 90, systolic90: 104, systolic95: 108, systolic95plus: 120, diastolic50: 52, diastolic90: 64, diastolic95: 68, diastolic95plus: 80 )!, BPNormsEntry( age: 5, sex: Patient.Sex.female, heightInMeters: 1.0529999999999999, systolic50: 91, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 52, diastolic90: 65, diastolic95: 69, diastolic95plus: 81 )!, BPNormsEntry( age: 5, sex: Patient.Sex.female, heightInMeters: 1.0820000000000001, systolic50: 92, systolic90: 106, systolic95: 109, systolic95plus: 121, diastolic50: 53, diastolic90: 66, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 5, sex: Patient.Sex.female, heightInMeters: 1.115, systolic50: 93, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 55, diastolic90: 67, diastolic95: 71, diastolic95plus: 83 )!, BPNormsEntry( age: 5, sex: Patient.Sex.female, heightInMeters: 1.149, systolic50: 94, systolic90: 108, systolic95: 111, systolic95plus: 123, diastolic50: 56, diastolic90: 68, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 5, sex: Patient.Sex.female, heightInMeters: 1.181, systolic50: 95, systolic90: 109, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 69, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 5, sex: Patient.Sex.female, heightInMeters: 1.2, systolic50: 96, systolic90: 110, systolic95: 113, systolic95plus: 125, diastolic50: 57, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 6, sex: Patient.Sex.female, heightInMeters: 1.1000000000000001, systolic50: 92, systolic90: 105, systolic95: 109, systolic95plus: 121, diastolic50: 54, diastolic90: 67, diastolic95: 70, diastolic95plus: 82 )!, BPNormsEntry( age: 6, sex: Patient.Sex.female, heightInMeters: 1.1179999999999999, systolic50: 92, systolic90: 106, systolic95: 109, systolic95plus: 121, diastolic50: 54, diastolic90: 67, diastolic95: 71, diastolic95plus: 83 )!, BPNormsEntry( age: 6, sex: Patient.Sex.female, heightInMeters: 1.149, systolic50: 93, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 55, diastolic90: 68, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 6, sex: Patient.Sex.female, heightInMeters: 1.1840000000000002, systolic50: 94, systolic90: 108, systolic95: 111, systolic95plus: 123, diastolic50: 56, diastolic90: 69, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 6, sex: Patient.Sex.female, heightInMeters: 1.2209999999999999, systolic50: 96, systolic90: 109, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 6, sex: Patient.Sex.female, heightInMeters: 1.256, systolic50: 97, systolic90: 110, systolic95: 113, systolic95plus: 125, diastolic50: 58, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 6, sex: Patient.Sex.female, heightInMeters: 1.2770000000000001, systolic50: 97, systolic90: 111, systolic95: 114, systolic95plus: 126, diastolic50: 59, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 7, sex: Patient.Sex.female, heightInMeters: 1.159, systolic50: 92, systolic90: 106, systolic95: 109, systolic95plus: 121, diastolic50: 55, diastolic90: 68, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 7, sex: Patient.Sex.female, heightInMeters: 1.1779999999999999, systolic50: 93, systolic90: 106, systolic95: 110, systolic95plus: 122, diastolic50: 55, diastolic90: 68, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 7, sex: Patient.Sex.female, heightInMeters: 1.2109999999999999, systolic50: 94, systolic90: 107, systolic95: 111, systolic95plus: 123, diastolic50: 56, diastolic90: 69, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 7, sex: Patient.Sex.female, heightInMeters: 1.2490000000000001, systolic50: 95, systolic90: 109, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 7, sex: Patient.Sex.female, heightInMeters: 1.288, systolic50: 97, systolic90: 110, systolic95: 113, systolic95plus: 125, diastolic50: 58, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 7, sex: Patient.Sex.female, heightInMeters: 1.325, systolic50: 98, systolic90: 111, systolic95: 114, systolic95plus: 126, diastolic50: 59, diastolic90: 72, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 7, sex: Patient.Sex.female, heightInMeters: 1.347, systolic50: 99, systolic90: 112, systolic95: 115, systolic95plus: 127, diastolic50: 60, diastolic90: 72, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 8, sex: Patient.Sex.female, heightInMeters: 1.21, systolic50: 93, systolic90: 107, systolic95: 110, systolic95plus: 122, diastolic50: 56, diastolic90: 69, diastolic95: 72, diastolic95plus: 84 )!, BPNormsEntry( age: 8, sex: Patient.Sex.female, heightInMeters: 1.23, systolic50: 94, systolic90: 107, systolic95: 111, systolic95plus: 123, diastolic50: 56, diastolic90: 70, diastolic95: 73, diastolic95plus: 85 )!, BPNormsEntry( age: 8, sex: Patient.Sex.female, heightInMeters: 1.2649999999999999, systolic50: 95, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 8, sex: Patient.Sex.female, heightInMeters: 1.306, systolic50: 97, systolic90: 110, systolic95: 113, systolic95plus: 125, diastolic50: 59, diastolic90: 72, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 8, sex: Patient.Sex.female, heightInMeters: 1.347, systolic50: 98, systolic90: 111, systolic95: 115, systolic95plus: 127, diastolic50: 60, diastolic90: 72, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 8, sex: Patient.Sex.female, heightInMeters: 1.385, systolic50: 99, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 61, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 8, sex: Patient.Sex.female, heightInMeters: 1.409, systolic50: 100, systolic90: 113, systolic95: 117, systolic95plus: 129, diastolic50: 61, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 9, sex: Patient.Sex.female, heightInMeters: 1.2529999999999999, systolic50: 95, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 57, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 9, sex: Patient.Sex.female, heightInMeters: 1.276, systolic50: 95, systolic90: 108, systolic95: 112, systolic95plus: 124, diastolic50: 58, diastolic90: 71, diastolic95: 74, diastolic95plus: 86 )!, BPNormsEntry( age: 9, sex: Patient.Sex.female, heightInMeters: 1.3130000000000002, systolic50: 97, systolic90: 109, systolic95: 113, systolic95plus: 125, diastolic50: 59, diastolic90: 72, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 9, sex: Patient.Sex.female, heightInMeters: 1.3559999999999999, systolic50: 98, systolic90: 111, systolic95: 114, systolic95plus: 126, diastolic50: 60, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 9, sex: Patient.Sex.female, heightInMeters: 1.401, systolic50: 99, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 60, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 9, sex: Patient.Sex.female, heightInMeters: 1.4409999999999998, systolic50: 100, systolic90: 113, systolic95: 117, systolic95plus: 129, diastolic50: 61, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 9, sex: Patient.Sex.female, heightInMeters: 1.466, systolic50: 101, systolic90: 114, systolic95: 118, systolic95plus: 130, diastolic50: 61, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.2969999999999999, systolic50: 96, systolic90: 109, systolic95: 113, systolic95plus: 125, diastolic50: 58, diastolic90: 72, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.3219999999999998, systolic50: 97, systolic90: 110, systolic95: 114, systolic95plus: 126, diastolic50: 59, diastolic90: 73, diastolic95: 75, diastolic95plus: 87 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.3630000000000002, systolic50: 98, systolic90: 111, systolic95: 114, systolic95plus: 126, diastolic50: 59, diastolic90: 73, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4099999999999999, systolic50: 99, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 60, diastolic90: 73, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4580000000000002, systolic50: 101, systolic90: 113, systolic95: 117, systolic95plus: 129, diastolic50: 61, diastolic90: 73, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5019999999999998, systolic50: 102, systolic90: 115, systolic95: 119, systolic95plus: 131, diastolic50: 61, diastolic90: 73, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.528, systolic50: 103, systolic90: 116, systolic95: 120, systolic95plus: 132, diastolic50: 62, diastolic90: 73, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.3559999999999999, systolic50: 98, systolic90: 111, systolic95: 115, systolic95plus: 127, diastolic50: 60, diastolic90: 74, diastolic95: 76, diastolic95plus: 88 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.383, systolic50: 99, systolic90: 112, systolic95: 116, systolic95plus: 128, diastolic50: 60, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4280000000000002, systolic50: 101, systolic90: 113, systolic95: 117, systolic95plus: 129, diastolic50: 60, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4780000000000002, systolic50: 102, systolic90: 114, systolic95: 118, systolic95plus: 130, diastolic50: 61, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.528, systolic50: 104, systolic90: 116, systolic95: 120, systolic95plus: 132, diastolic50: 62, diastolic90: 74, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5730000000000002, systolic50: 105, systolic90: 118, systolic95: 123, systolic95plus: 135, diastolic50: 63, diastolic90: 75, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6000000000000001, systolic50: 106, systolic90: 120, systolic95: 124, systolic95plus: 136, diastolic50: 64, diastolic90: 75, diastolic95: 77, diastolic95plus: 89 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4280000000000002, systolic50: 102, systolic90: 114, systolic95: 118, systolic95plus: 130, diastolic50: 61, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4550000000000001, systolic50: 102, systolic90: 115, systolic95: 119, systolic95plus: 131, diastolic50: 61, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4990000000000001, systolic50: 104, systolic90: 116, systolic95: 120, systolic95plus: 132, diastolic50: 61, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.548, systolic50: 105, systolic90: 118, systolic95: 122, systolic95plus: 134, diastolic50: 62, diastolic90: 75, diastolic95: 78, diastolic95plus: 90 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5959999999999999, systolic50: 107, systolic90: 120, systolic95: 124, systolic95plus: 136, diastolic50: 64, diastolic90: 76, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6380000000000001, systolic50: 108, systolic90: 122, systolic95: 125, systolic95plus: 137, diastolic50: 65, diastolic90: 76, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6640000000000001, systolic50: 108, systolic90: 122, systolic95: 126, systolic95plus: 138, diastolic50: 65, diastolic90: 76, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.4809999999999999, systolic50: 104, systolic90: 116, systolic95: 121, systolic95plus: 133, diastolic50: 62, diastolic90: 75, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.506, systolic50: 105, systolic90: 117, systolic95: 122, systolic95plus: 134, diastolic50: 62, diastolic90: 75, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5469999999999999, systolic50: 106, systolic90: 119, systolic95: 123, systolic95plus: 135, diastolic50: 63, diastolic90: 75, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5919999999999999, systolic50: 107, systolic90: 121, systolic95: 124, systolic95plus: 136, diastolic50: 64, diastolic90: 76, diastolic95: 79, diastolic95plus: 91 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6369999999999998, systolic50: 108, systolic90: 122, systolic95: 126, systolic95plus: 138, diastolic50: 65, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6780000000000002, systolic50: 108, systolic90: 123, systolic95: 126, systolic95plus: 138, diastolic50: 65, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.702, systolic50: 109, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 66, diastolic90: 76, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.506, systolic50: 105, systolic90: 118, systolic95: 123, systolic95plus: 135, diastolic50: 63, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.53, systolic50: 106, systolic90: 118, systolic95: 123, systolic95plus: 135, diastolic50: 63, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.569, systolic50: 107, systolic90: 120, systolic95: 124, systolic95plus: 136, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6130000000000002, systolic50: 108, systolic90: 122, systolic95: 125, systolic95plus: 137, diastolic50: 65, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6569999999999998, systolic50: 109, systolic90: 123, systolic95: 126, systolic95plus: 138, diastolic50: 66, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6969999999999998, systolic50: 109, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 66, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.7209999999999999, systolic50: 109, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 66, diastolic90: 77, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5169999999999999, systolic50: 105, systolic90: 118, systolic95: 124, systolic95plus: 136, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.54, systolic50: 106, systolic90: 119, systolic95: 124, systolic95plus: 136, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.579, systolic50: 107, systolic90: 121, systolic95: 125, systolic95plus: 137, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6230000000000002, systolic50: 108, systolic90: 122, systolic95: 126, systolic95plus: 138, diastolic50: 65, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6669999999999998, systolic50: 109, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 66, diastolic90: 77, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.706, systolic50: 109, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 67, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.73, systolic50: 109, systolic90: 124, systolic95: 128, systolic95plus: 140, diastolic50: 67, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5209999999999999, systolic50: 106, systolic90: 119, systolic95: 124, systolic95plus: 136, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5449999999999999, systolic50: 107, systolic90: 120, systolic95: 125, systolic95plus: 137, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5840000000000001, systolic50: 108, systolic90: 122, systolic95: 125, systolic95plus: 137, diastolic50: 65, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6280000000000001, systolic50: 109, systolic90: 123, systolic95: 127, systolic95plus: 139, diastolic50: 66, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.671, systolic50: 109, systolic90: 124, systolic95: 127, systolic95plus: 139, diastolic50: 66, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.7109999999999999, systolic50: 110, systolic90: 124, systolic95: 128, systolic95plus: 140, diastolic50: 67, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.734, systolic50: 110, systolic90: 124, systolic95: 128, systolic95plus: 140, diastolic50: 67, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.524, systolic50: 107, systolic90: 120, systolic95: 125, systolic95plus: 137, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.5469999999999999, systolic50: 108, systolic90: 121, systolic95: 125, systolic95plus: 137, diastolic50: 64, diastolic90: 76, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.587, systolic50: 109, systolic90: 123, systolic95: 126, systolic95plus: 138, diastolic50: 65, diastolic90: 77, diastolic95: 80, diastolic95plus: 92 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6299999999999999, systolic50: 110, systolic90: 124, systolic95: 127, systolic95plus: 139, diastolic50: 66, diastolic90: 77, diastolic95: 81, diastolic95plus: 93 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.6740000000000002, systolic50: 110, systolic90: 124, systolic95: 128, systolic95plus: 140, diastolic50: 66, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.7130000000000001, systolic50: 110, systolic90: 125, systolic95: 128, systolic95plus: 140, diastolic50: 66, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )!, BPNormsEntry( age: 1, sex: Patient.Sex.female, heightInMeters: 1.7369999999999999, systolic50: 111, systolic90: 125, systolic95: 128, systolic95plus: 140, diastolic50: 67, diastolic90: 78, diastolic95: 82, diastolic95plus: 94 )! )! }
mit
b9caf1ac09f7a51212857a7230a6fb51
19.940335
91
0.637006
2.794597
false
false
false
false
Obisoft2017/BeautyTeamiOS
BeautyTeam/BeautyTeam/AddPersonalTaskVC.swift
1
3306
// // AddPersonalTaskVC.swift // BeautyTeam // // Created by Carl Lee on 4/21/16. // Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved. // import UIKit class AddPersonalTaskVC: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Add Personal Task" // 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() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
549a6081790be7f1d1bdaace9e235f8f
33.789474
157
0.687443
5.480929
false
false
false
false
jayesh15111988/JKWayfairPriceGame
JKWayfairPriceGame/ProductWebViewController.swift
1
4632
// // ProductWebViewer.swift // JKWayfairPriceGame // // Created by Jayesh Kawli Backup on 8/20/16. // Copyright © 2016 Jayesh Kawli Backup. All rights reserved. // import Foundation import UIKit import WebKit class ProductWebViewController: UIViewController, WKNavigationDelegate { let viewModel: ProductWebViewerViewModel let webView: WKWebView let activityIndicatorView: UIActivityIndicatorView var errorMessage: String var loadingLabel: UILabel init (viewModel: ProductWebViewerViewModel) { self.viewModel = viewModel self.webView = WKWebView(frame: .zero) self.webView.translatesAutoresizingMaskIntoConstraints = false self.webView.contentScaleFactor = 1.0 self.activityIndicatorView = UIActivityIndicatorView() self.activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false self.activityIndicatorView.hidesWhenStopped = true self.activityIndicatorView.activityIndicatorViewStyle = .WhiteLarge self.activityIndicatorView.color = Appearance.defaultAppColor() self.errorMessage = "" self.loadingLabel = UILabel() self.loadingLabel.translatesAutoresizingMaskIntoConstraints = false self.loadingLabel.numberOfLines = 0 self.loadingLabel.font = Appearance.extraLargeFont() super.init(nibName: nil, bundle: nil) self.webView.navigationDelegate = self } override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.view.backgroundColor = .whiteColor() self.title = self.viewModel.product.name self.view.addSubview(self.webView) self.view.addSubview(self.activityIndicatorView) self.view.addSubview(self.loadingLabel) let topLayoutGuide = self.topLayoutGuide let views: [String: AnyObject] = ["webView": webView, "topLayoutGuide": topLayoutGuide] self.view.addConstraint(NSLayoutConstraint(item: self.activityIndicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.activityIndicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide][webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) self.view.addConstraint(NSLayoutConstraint(item: self.loadingLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.loadingLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: -44)) self.webView.loadRequest(NSURLRequest(URL: self.viewModel.product.productURL!)) RACObserve(self.webView, keyPath: "estimatedProgress").subscribeNext { [unowned self] (progress) in if let progress = progress as? Double { self.loadingLabel.text = String(Int(progress * 100.0)) + "%" } } RACObserve(self.webView, keyPath: "loading").subscribeNext { [unowned self] (loading) in if let loading = loading as? Bool { if loading == true { self.activityIndicatorView.startAnimating() } else { self.activityIndicatorView.stopAnimating() } self.loadingLabel.hidden = !loading } } } func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { activityIndicatorView.stopAnimating() let errorMessage = error.localizedDescription let alertController = UIAlertController(title: self.viewModel.product.name, message: errorMessage, preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(OKAction) self.presentViewController(alertController, animated: true, completion: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0baebd25723da346508dfe1def6290a9
47.757895
195
0.691643
5.28653
false
false
false
false
crypton-watanabe/morurun-ios
morurun/views/TimeLineTableView/YoutubeView.swift
1
1273
// // YoutubeView.swift // morurun // // Created by watanabe on 2016/11/02. // Copyright © 2016年 Crypton Future Media, INC. All rights reserved. // import UIKit import WebKit import RxSwift import RxCocoa public class YoutubeView: UIView { private let disposeBag = DisposeBag() private var webView: WKWebView? var url: URL? { didSet { if let url = self.url { let request = URLRequest(url: url) _ = self.webView?.load(request) } else { _ = self.webView?.loadHTMLString("", baseURL: nil) } } } override public func awakeFromNib() { super.awakeFromNib() let webView = WKWebView() self.addSubviewFill(webView) webView .rx.observe(Bool.self, "loading") .bindNext({ webView.isHidden = $0 ?? true }) .addDisposableTo(self.disposeBag) self.webView = webView self.webView?.scrollView.isScrollEnabled = false } } extension Reactive where Base: YoutubeView { public var url: UIBindingObserver<Base, URL?> { return UIBindingObserver(UIElement: self.base) { view, url in view.url = url } } }
mit
a5e44406a1464fb74e32cddb2bc05a05
23.901961
69
0.568504
4.503546
false
false
false
false
kinwahlai/YetAnotherHTTPStub
YetAnotherHTTPStub/StubResponse.swift
1
2293
// // StubResponse.swift // YetAnotherHTTPStub // // Created by Darren Lai on 7/8/17. // Copyright © 2017 KinWahLai. All rights reserved. // import Foundation // MARK: - StubResponse public enum Response { case success(response: HTTPURLResponse, content: StubContent) case failure(StubError) } public typealias Builder = (URLRequest) -> (Response) public class StubResponse: NSObject { private(set) var builder: Builder? private(set) var queue: DispatchQueue fileprivate var postReplyClosure: (() -> Void) = { } private(set) var delay: TimeInterval = 0 private(set) var repeatCount: Int = 1 var isPartial: Bool { return builder == nil } init(queue: DispatchQueue? = nil) { if let queue = queue { self.queue = queue } else { self.queue = DispatchQueue(label: "kinwahlai.stubresponse.queue") } } @discardableResult func setup(with parameter: StubResponse.Parameter) -> StubResponse { delay = parameter.delay repeatCount = parameter.repeatCount postReplyClosure = parameter.postReplyClosure builder = parameter.builder return self } // Deduct 1 from repeatCount and return the count value public func deductRepeatCount() -> Int { repeatCount -= 1 return repeatCount } public func reply(via urlProtocol: URLProtocol) { guard let builder = builder else { return } queue.asyncAfter(deadline: DispatchTime.now() + delay) { let request = urlProtocol.request let response = builder(request) let client = urlProtocol.client switch response { case .success(let urlResponse, let content): client?.urlProtocol(urlProtocol, didReceive: urlResponse, cacheStoragePolicy: URLCache.StoragePolicy.notAllowed) if case .data(let data) = content { client?.urlProtocol(urlProtocol, didLoad: data) } client?.urlProtocolDidFinishLoading(urlProtocol) case .failure(let error): client?.urlProtocol(urlProtocol, didFailWithError: error.toNSError) } self.postReplyClosure() } } }
mit
e1affb569424ae8f99390d72b89d5221
30.833333
128
0.623473
4.815126
false
false
false
false
pyngit/PickerSample
PickerSample/ui/AppPickerView.swift
1
2234
// // AppDatePicker.swift // PickerSample // // Created by pyngit on 2015/11/15. // // import UIKit class AppPickerView : UIPickerView,UIPickerViewDelegate,UIPickerViewDataSource{ /* 月 */ let MONTH_LIST = ["01","02","03","04","05","06","07","08","09","10","11","12"]; /* 日 */ let DAY_LIST = ["01","02","03","04","05","06","07","08","09","10" ,"11","12","13","14","15","16","17","18","19","20" ,"21","22","23","24","25","26","27","28","29","30","31"] /* 月の選択した値 */ var monthValue:String = "1"; /* 日の選択した値 */ var dayValue:String = "01"; override init(frame: CGRect) { print("AppPickerView init"); super.init(frame: frame); delegate = self; dataSource = self; } required init(coder aDecoder: NSCoder) { print("AppPickerView init \(aDecoder)"); super.init(coder: aDecoder)! delegate = self; dataSource = self; } //UI Picer用設定 //表示列 func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { // print("AppPickerView numberOfComponentsInPickerView"); return 2 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { // print("AppPickerView pickerView \(component)"); if(component == 0){ return MONTH_LIST.count; // 1列目の選択肢の数 }else{ return DAY_LIST.count; // 2列目の選択肢の数 } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if(component == 0){ return MONTH_LIST[row] // 1列目のrow番目に表示する値 }else{ return DAY_LIST[row] // 2列目のrow番目に表示する値 } } /* pickerが選択された際に呼ばれるデリゲートメソッド. */ func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if(component == 0){ //月 monthValue = MONTH_LIST[row]; }else{ //日 dayValue = DAY_LIST[row]; } } }
apache-2.0
7ed3e64a985530b6835d9eede201c7a5
26.573333
109
0.549323
3.732852
false
false
false
false
getsenic/nuimo-websocket-server-osx
Pods/NuimoSwift/SDK/NuimoGesture.swift
2
2009
// // NuimoGesture.swift // Nuimo // // Created by Lars Blumberg on 9/23/15. // Copyright © 2015 Senic. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. @objc public enum NuimoGesture : Int { case Undefined = 0, // TODO: Do we really need this enum value? We don't need to handle an "undefined" gesture ButtonPress, ButtonDoublePress, ButtonRelease, Rotate, TouchLeft, TouchRight, TouchTop, TouchBottom, SwipeLeft, SwipeRight, SwipeUp, SwipeDown, FlyLeft, FlyRight, FlyBackwards, FlyTowards, FlyUpDown public init?(identifier: String) { guard let gesture = gestureForIdentifier[identifier] else { return nil } self = gesture } public var identifier: String { return identifierForGesture[self]! } } public enum NuimoGestureError: ErrorType { case InvalidIdentifier } private let identifierForGesture: [NuimoGesture : String] = [ .Undefined : "Undefined", .ButtonPress : "ButtonPress", .ButtonRelease : "ButtonRelease", .ButtonDoublePress : "ButtonDoublePress", .Rotate : "Rotate", .TouchLeft : "TouchLeft", .TouchRight : "TouchRight", .TouchTop : "TouchTop", .TouchBottom : "TouchBottom", .SwipeLeft : "SwipeLeft", .SwipeRight : "SwipeRight", .SwipeUp : "SwipeUp", .SwipeDown : "SwipeDown", .FlyLeft : "FlyLeft", .FlyRight : "FlyRight", .FlyBackwards : "FlyBackwards", .FlyTowards : "FlyTowards", .FlyUpDown : "FlyUpDown" ] private let gestureForIdentifier: [String : NuimoGesture] = { var dictionary = [String : NuimoGesture]() for (gesture, identifier) in identifierForGesture { dictionary[identifier] = gesture } return dictionary }()
mit
7b291038cdafcb979db43e00aea66069
27.28169
109
0.609562
4.016
false
false
false
false
tejen/codepath-instagram
Instagram/Instagram/NewPostViewController.swift
1
4345
// // NewPostViewController.swift // Instagram // // Created by Tejen Hasmukh Patel on 3/9/16. // Copyright © 2016 Tejen. All rights reserved. // import UIKit class NewPostViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var captionView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textView: UITextView! @IBOutlet weak var addLocationSuperview: UIView! @IBOutlet weak var facebookSuperview: UIView! @IBOutlet weak var twitterSuperview: UIView! @IBOutlet weak var tumblrSuperview: UIView! @IBOutlet weak var flickrSuperview: UIView! @IBOutlet weak var shareActionView: UIView! @IBOutlet weak var activityIndicatorView: UIView! var newPostImage: UIImage?; var textViewPlaceholder: String?; var submitting = false; var newPost: Post?; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view [captionView, addLocationSuperview, facebookSuperview, twitterSuperview, tumblrSuperview, flickrSuperview].map { view in view.layer.borderColor = UIColor(white: 0.75, alpha: 1).CGColor; view.layer.borderWidth = 1; } imageView.image = newPostImage; imageView.userInteractionEnabled = true; imageView.layer.cornerRadius = 5; textViewPlaceholder = textView.text; textView.delegate = self; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onCancelButton(sender: AnyObject) { if(submitting != true) { dismissViewControllerAnimated(true, completion: nil); } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(true) } func textViewDidBeginEditing(textView: UITextView) { if(textView.text == textViewPlaceholder) { textView.text = ""; textView.textColor = UIColor.blackColor(); } textView.becomeFirstResponder(); } func textViewDidEndEditing(textView: UITextView) { if(textView.text == "") { textView.text = textViewPlaceholder; textView.textColor = UIColor(white: 2/3, alpha: 1); } textView.resignFirstResponder(); } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if(text == "\n") { textView.resignFirstResponder(); return false; } return true; } @IBAction func onTapImage(sender: AnyObject) { performSegueWithIdentifier("toPreview", sender: self); } @IBAction func onShareButton(sender: AnyObject) { submitting = true; activityIndicatorView.hidden = false; UIView.animateWithDuration(1.0) { () -> Void in self.activityIndicatorView.alpha = 1; } var captionText = textView.text; if(captionText == textViewPlaceholder) { captionText = ""; } newPost = Post(image: newPostImage, withCaption: captionText) { (success: Bool, error: NSError?) -> Void in let captionText = self.textView.text; if(captionText != self.textViewPlaceholder) { self.newPost?.comment(captionText); } let tabBarController = appDelegate.window?.rootViewController as! TabBarController; tabBarController.selectedIndex = 0; let nVc = tabBarController.viewControllers?.first as! UINavigationController; let hVc = nVc.viewControllers.first as! HomeViewController; hVc.reloadTable(); self.dismissViewControllerAnimated(true, completion: nil); }; } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "toPreview") { let vc = segue.destinationViewController as! UINavigationController; let pVc = vc.viewControllers.first as! PreviewViewController; pVc.image = newPostImage; } } }
apache-2.0
f43747f590e424538ad76a05d23f6cf9
30.941176
128
0.62454
5.27825
false
false
false
false
squiffy/AlienKit
Pod/Classes/Comment.swift
1
6129
// // Comment.swift // Pods // // Created by Will Estes on 3/21/16. // // import Foundation import SwiftyJSON public class Comment: Thing { /// the time of creation in local epoch-second format. public let created: Int? /// the time of creation in UTC epoch-second format. public let createdUTC: Int? /// who approved this comment. `null` if nobody or you are not a mod public let approvedBy: String? /// the account name of the poster public let author: String? /// the CSS class of the author's flair. subreddit specific public let authorFlairCSSClass: String? /// the text of the author's flair. subreddit specific public let authorFlairText: String? /// who removed this comment. `null` if nobody or you are not a mod public let bannedBy: String? /** the raw text. this is the unformatted text which includes the raw markup characters such as `**` for bold. `<`, `>`, and `&` are escaped. */ public let body: String? /** the formatted HTML text as displayed on reddit. For example, text that is emphasised by `*` will now have `<em>` tags wrapping it. Additionally, bullets and numbered lists will now be in HTML list format. **NOTE**: The HTMLstring will be escaped. You must unescape to get the raw HTML. */ public let body_html: String? /// `true` if the comment has been edited; `false` otherwise. public let edited: Bool? /** For newer posts, this will be the date UTC epoch-seconds. Old comments, this will be `nil` */ public let editedDate: Int? /// the number of times this comment received reddit gold public let gilded: Int? /** how the logged-in user has voted on the comment - `True` = upvoted, `False` = downvoted, `nil` = no vote */ public let likes: Bool? /// the number of upvotes. (includes own) public let ups: Int? /// the number of downvotes. (includes own) public let downs: Int? /** Present if the comment is being displayed outside its thread (user pages, etc) Contains the author of the parent link. */ public let linkAuthor: String? /// ID of the link this comment is in public let linkID: String? /** Present if the comment is being displayed outside its thread (user pages, etc) Contains the title of the parent link. */ public let linkTitle: String? /// ID of the link this comment is in public let linkURL: String? /// how many times this comment has been reported, `nil` if not a mod public let numReports: Int? /// ID of the thing this comment is a reply to, either the link or a comment in it public let parentId: String? /// A list of replies to this comment public let replies: Listing? /// `true` if this post is saved by the logged in user public let saved: Bool? /// the net-score of the comment public let score: Int? /// Whether the comment's score is currently hidden. public let scoreHidden: Bool? /// subreddit of thing excluding the /r/ prefix. public let subreddit: String? /// the id of the subreddit in which the thing is located public let subredditId: String? /** to allow determining whether they have been distinguished by moderators/admins. `nil` = not distinguished. `moderator` = the green [M]. `admin` = the red [A]. special = various other special distinguishes defined [here](http://redd.it/19ak1b) */ public let distinguished: String? /** initialize an `Comment` object - parameter data: JSON data from the API endpoint - returns: an `Comment` object. */ init(data: JSON) { if let created = data["created"].float { self.created = Int(created) } else { created = nil } if let createdUTC = data["created_utc"].float { self.createdUTC = Int(createdUTC) } else { createdUTC = nil } self.approvedBy = data["approvedBy"].string self.author = data["author"].string self.authorFlairCSSClass = data["author_flair_css_class"].string self.authorFlairText = data["author_flair_text"].string self.bannedBy = data["banned_by"].string self.body = data["body"].string self.body_html = data["body_html"].string // editing is a special case due to bad reddit API design :\ // attempt to get it as a date if let epoch = data["edited"].float { self.edited = true self.editedDate = Int(epoch) } else { self.edited = data["edited"].bool self.editedDate = nil } self.gilded = data["gilded"].int! self.likes = data["likes"].bool self.ups = data["ups"].int self.downs = data["downs"].int self.linkAuthor = data["link_author"].string self.linkID = data["link_id"].string self.linkTitle = data["link_title"].string self.linkURL = data["link_url"].string self.numReports = data["num_reports"].int self.parentId = data["parentId"].string if let replies = data["replies"].dictionary { if let data = replies["data"] { self.replies = Parser.parseListFromJSON(data) } else { self.replies = nil } } else { self.replies = nil } self.saved = data["saved"].bool self.score = data["score"].int self.scoreHidden = data["score_hidden"].bool self.subreddit = data["subreddit"].string self.subredditId = data["subreddit_id"].string self.distinguished = data["distinguished"].string super.init(id: data["id"].string, name: data["name"].string) } }
mit
15516ea5df0f4eb7248e677e583415cf
30.116751
86
0.589493
4.441304
false
false
false
false
enriquez/swifterate
test/fixtures/MyPlistEnum.swift
1
1008
enum MyPlistEnum: String { case CFBundleName = "CFBundleName" case CFBundleShortVersionString = "CFBundleShortVersionString" case CFBundleVersion = "CFBundleVersion" case UISupportedInterfaceOrientationsipad = "UISupportedInterfaceOrientations~ipad" private var infoDictionary: [NSObject : AnyObject] { return NSBundle.mainBundle().infoDictionary! } var dictionary: [NSObject : AnyObject] { return infoDictionary[rawValue] as! [NSObject : AnyObject] } var array: [AnyObject] { return infoDictionary[rawValue] as! [AnyObject] } var data: NSData { return infoDictionary[rawValue] as! NSData } var date: NSDate { return infoDictionary[rawValue] as! NSDate } var number: NSNumber { return infoDictionary[rawValue] as! NSNumber } var string: String { return infoDictionary[rawValue] as! String } init(_ key: MyPlistEnum) { self = key } }
mit
e3a3970b8ad6229fc0420879da4a6aea
23.585366
87
0.650794
4.990099
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/partially_generic_func/enum/main.swift
2
1035
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- enum Generic<T> { case Case1 case Case2 case Case3 } func foo<T0>(_ x: Generic<T0>) { print(x) //% self.expect('frame variable -d run -- x', substrs=['Case1']) //% self.expect('frame variable -d run -- x', substrs=['Case2'], matching=False) //% self.expect('frame variable -d run -- x', substrs=['Case3'], matching=False) //% self.expect('expression -d run -- x', substrs=['Case1']) //% self.expect('expression -d run -- x', substrs=['Case2'], matching=False) //% self.expect('expression -d run -- x', substrs=['Case3'], matching=False) } foo(Generic<Int>.Case1)
apache-2.0
f8d1171e4a4c03f53765580028a0b025
37.333333
82
0.618357
3.736462
false
false
false
false
einsteinx2/iSub
Carthage/Checkouts/swifter/Sources/Socket.swift
3
5875
// // Socket.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation public enum SocketError: Error { case socketCreationFailed(String) case socketSettingReUseAddrFailed(String) case bindFailed(String) case listenFailed(String) case writeFailed(String) case getPeerNameFailed(String) case convertingPeerNameFailed case getNameInfoFailed(String) case acceptFailed(String) case recvFailed(String) case getSockNameFailed(String) } open class Socket: Hashable, Equatable { let socketFileDescriptor: Int32 private var shutdown = false public init(socketFileDescriptor: Int32) { self.socketFileDescriptor = socketFileDescriptor } deinit { close() } public var hashValue: Int { return Int(self.socketFileDescriptor) } public func close() { if shutdown { return } shutdown = true Socket.close(self.socketFileDescriptor) } public func port() throws -> in_port_t { var addr = sockaddr_in() return try withUnsafePointer(to: &addr) { pointer in var len = socklen_t(MemoryLayout<sockaddr_in>.size) if getsockname(socketFileDescriptor, UnsafeMutablePointer(OpaquePointer(pointer)), &len) != 0 { throw SocketError.getSockNameFailed(Errno.description()) } let sin_port = pointer.pointee.sin_port #if os(Linux) return ntohs(sin_port) #else return Int(OSHostByteOrder()) != OSLittleEndian ? sin_port.littleEndian : sin_port.bigEndian #endif } } public func isIPv4() throws -> Bool { var addr = sockaddr_in() return try withUnsafePointer(to: &addr) { pointer in var len = socklen_t(MemoryLayout<sockaddr_in>.size) if getsockname(socketFileDescriptor, UnsafeMutablePointer(OpaquePointer(pointer)), &len) != 0 { throw SocketError.getSockNameFailed(Errno.description()) } return Int32(pointer.pointee.sin_family) == AF_INET } } public func writeUTF8(_ string: String) throws { try writeUInt8(ArraySlice(string.utf8)) } public func writeUInt8(_ data: [UInt8]) throws { try writeUInt8(ArraySlice(data)) } public func writeUInt8(_ data: ArraySlice<UInt8>) throws { try data.withUnsafeBufferPointer { try writeBuffer($0.baseAddress!, length: data.count) } } public func writeData(_ data: NSData) throws { try writeBuffer(data.bytes, length: data.length) } public func writeData(_ data: Data) throws { try data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) -> Void in try self.writeBuffer(pointer, length: data.count) } } private func writeBuffer(_ pointer: UnsafeRawPointer, length: Int) throws { var sent = 0 while sent < length { #if os(Linux) let s = send(self.socketFileDescriptor, pointer + sent, Int(length - sent), Int32(MSG_NOSIGNAL)) #else let s = write(self.socketFileDescriptor, pointer + sent, Int(length - sent)) #endif if s <= 0 { throw SocketError.writeFailed(Errno.description()) } sent += s } } open func read() throws -> UInt8 { var buffer = [UInt8](repeating: 0, count: 1) #if os(Linux) let next = recv(self.socketFileDescriptor as Int32, &buffer, Int(buffer.count), Int32(MSG_NOSIGNAL)) #else let next = recv(self.socketFileDescriptor as Int32, &buffer, Int(buffer.count), 0) #endif if next <= 0 { throw SocketError.recvFailed(Errno.description()) } return buffer[0] } private static let CR = UInt8(13) private static let NL = UInt8(10) public func readLine() throws -> String { var characters: String = "" var n: UInt8 = 0 repeat { n = try self.read() if n > Socket.CR { characters.append(Character(UnicodeScalar(n))) } } while n != Socket.NL return characters } public func peername() throws -> String { var addr = sockaddr(), len: socklen_t = socklen_t(MemoryLayout<sockaddr>.size) if getpeername(self.socketFileDescriptor, &addr, &len) != 0 { throw SocketError.getPeerNameFailed(Errno.description()) } var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 { throw SocketError.getNameInfoFailed(Errno.description()) } return String(cString: hostBuffer) } public class func setNoSigPipe(_ socket: Int32) { #if os(Linux) // There is no SO_NOSIGPIPE in Linux (nor some other systems). You can instead use the MSG_NOSIGNAL flag when calling send(), // or use signal(SIGPIPE, SIG_IGN) to make your entire application ignore SIGPIPE. #else // Prevents crashes when blocking calls are pending and the app is paused ( via Home button ). var no_sig_pipe: Int32 = 1 setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(MemoryLayout<Int32>.size)) #endif } public class func close(_ socket: Int32) { #if os(Linux) let _ = Glibc.close(socket) #else let _ = Darwin.close(socket) #endif } } public func == (socket1: Socket, socket2: Socket) -> Bool { return socket1.socketFileDescriptor == socket2.socketFileDescriptor }
gpl-3.0
af2dacc07a0cc3e8cb540a6913ec81da
32.565714
137
0.601464
4.383582
false
false
false
false
ZackKingS/Tasks
task/Classes/LoginRegist/Model/User.swift
1
2337
// // User.swift // task // // Created by 柏超曾 on 2017/9/28. // Copyright © 2017年 柏超曾. All rights reserved. // import SwiftyJSON import Foundation class User : NSObject, NSCoding { var avatar : String? var alipay : String? var credit_card : String? var id : String? var nickname : String? var account : String? var finished : String? var username : String? var email : String? var tel : String? var usersig : String? // MARK:- 自定义构造函数 KVC实现字典转模型 init(dict : [String : JSON]) { super.init() print(dict) tel = dict["tel"]?.stringValue as String! nickname = dict["nickname"]?.stringValue as String! id = dict["id"]?.stringValue as String! account = dict["account"]?.stringValue as String! finished = dict["finished"]?.stringValue as String! } class func GetUser() -> User { let dataa = UserDefaults.standard.object(forKey: "user") as! NSData let user : User = NSKeyedUnarchiver.unarchiveObject(with: dataa as Data ) as! User return user } override func setValue(_ value: Any?, forUndefinedKey key: String) {} struct PropertyKey { static let id = "id" static let nickname = "nickname" static let account = "account" static let tel = "tel" static let finished = "finished" } required init?(coder aDecoder: NSCoder) { id = aDecoder.decodeObject(forKey: PropertyKey.id) as? String nickname = aDecoder.decodeObject(forKey: PropertyKey.nickname) as? String tel = aDecoder.decodeObject(forKey: PropertyKey.tel) as? String account = aDecoder.decodeObject(forKey: PropertyKey.account) as? String finished = aDecoder.decodeObject(forKey: PropertyKey.finished) as? String } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: PropertyKey.id) aCoder.encode(nickname, forKey: PropertyKey.nickname) aCoder.encode(tel, forKey: PropertyKey.tel) aCoder.encode(finished, forKey: PropertyKey.finished) aCoder.encode(account, forKey: PropertyKey.account) } }
apache-2.0
b5e3e320a242488be74ed8177c444ec6
23.404255
91
0.601133
4.30394
false
false
false
false
AnnMic/FestivalArchitect
EntitasSwift/Entity.swift
1
2277
import Foundation public typealias ComponentName = String public typealias ComponentTypeSet = Dictionary<ComponentName, Void> public class Component { public class func name() -> String { assert(false, "Must override `class func name()`") return "" } public init() { } } public protocol Entity { func setComponent<C: Component>(c:C) func setComponent<C: Component>(c:C, overwrite:Bool) func component<C: Component>(ct:C.Type) -> C? func removeComponent<C: Component>(ct:C.Type) } internal class EntityImpl : Entity { private let environment:Environment private var _components:[String:Component] internal var components:[String:Component] { get { return _components } } internal init (env:Environment) { environment = env _components = [:] } internal func setComponent<C: Component>(c:C) { self.setComponent(c, overwrite:false) } internal func setComponent<C: Component>(c:C, overwrite:Bool) { let componentName = c.dynamicType.name() if components[componentName] === c { return } if self.component(c.dynamicType) != nil && !overwrite { let exp = NSException(name: NSInvalidArgumentException, reason: "Illegal overwrite error", userInfo: nil) exp.raise() } if overwrite { self.removeComponent(c.dynamicType) } _components[componentName] = c; environment.entityDidAddComponent(self, type:componentName) } internal func component<C: Component>(ct:C.Type) -> C? { if let c = components[ct.name()] { return c as? C } return nil } internal func removeComponent<C: Component>(ct:C.Type) { let componentName = ct.name() if components.indexForKey(componentName) == nil { return } environment.entityWillRemoveComponent(self, type:componentName) _components.removeValueForKey(componentName) } } public func isIdentical(a:Entity, b:Entity) -> Bool { return (a as EntityImpl) === (b as EntityImpl) }
mit
467ab6dc5748bddb69c2f302fc1cd2dc
22.968421
117
0.593764
4.438596
false
false
false
false
judi0713/TouTiao
TouTiaoLauncher/AppDelegate.swift
2
1573
// // AppDelegate.swift // TouTiaoLauncher // // Created by tesths on 25/03/2017. // Copyright © 2017 tesths. All rights reserved. // import Cocoa extension Notification.Name { static let killme = Notification.Name("killme") } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let mainAppIdentifier = "com.tt.TouTiao" func applicationDidFinishLaunching(_ aNotification: Notification) { let running = NSWorkspace.shared().runningApplications var alreadyRunning = false for app in running { if app.bundleIdentifier == mainAppIdentifier { alreadyRunning = true break } } if !alreadyRunning { DistributedNotificationCenter.default().addObserver(self, selector: #selector(self.terminate), name: .killme, object: mainAppIdentifier) let path = Bundle.main.bundlePath as NSString var components = path.pathComponents components.removeLast() components.removeLast() components.removeLast() components.append("MacOS") components.append("TouTiao") //main app name let newPath = NSString.path(withComponents: components) NSWorkspace.shared().launchApplication(newPath) } else { self.terminate() } } func terminate() { // NSLog("I'll be back!") NSApp.terminate(nil) } }
mit
9052135c297c68762296f98fa92afee7
24.770492
148
0.585878
5.275168
false
false
false
false
Royal-J/TestKitchen1607
TestKitchen1607/TestKitchen1607/classes/ingredient(食材)/recommend(推荐)/FoodCourse食材课程/model/FoodCourseDetail.swift
1
5378
// // FoodCourseDetail.swift // TestKitchen1607 // // Created by HJY on 2016/11/3. // Copyright © 2016年 HJY. All rights reserved. // import UIKit import SwiftyJSON class FoodCourseDetail: NSObject { var code: String? var data: FoodCourseDetailData? var msg: String? var timestamp: NSNumber? var version: String? class func parseData(data: NSData) -> FoodCourseDetail { let json = JSON(data: data) let model = FoodCourseDetail() model.code = json["code"].string model.data = FoodCourseDetailData.parse(json["data"]) model.msg = json["msg"].string model.timestamp = json["timestamp"].number model.version = json["version"].string return model } } class FoodCourseDetailData: NSObject { /* "album" : "蓝猪坊", "album_logo" : "1478067938916_1376458904.jpg", "create_time" : "2016-10-09 15:03:35", "data" : [] "episode" : 5, "last_update" : "2016-11-02 14:25:39", "order_no" : "1", "play" : 26348, "relate_activity" : "109", "series_id" : "121", "series_image" : "http://img.szzhangchu.com/1478067938583_7799533263.jpg", "series_name" : "#蓝猪坊#双色蔬菜水饺", "series_title" : "说到团圆,除了月饼以外还有一种食物也象征着团圆,那就是饺子!饺子是我国很古老的一种食物。尤其是在过年的时候,家家户户都在吃饺子,饺子也就自然被人们意为团圆的象征。 今天的这道饺子,以高颜值霸占饭桌好几载!趁着中秋假!给饭桌增添一抹赏心悦目的绿色!", "share_description" : null, "share_image" : null, "share_title" : null, "share_url" : "http://m.izhangchu.com/micro/shike.php?&material_id=121", "tag" : "" */ var album: String? var album_logo: String? var create_time: String? var data: Array<FoodCourseSerial>? var episode: NSNumber? var last_update: String? var order_no: String? var play: NSNumber? var relate_activity: String? var series_id: String? var series_image: String? var series_name: String? var series_title: String? var share_description: String? var share_image: String? var share_title: String? var share_url: String? var tag: String? class func parse(json: JSON) -> FoodCourseDetailData { let model = FoodCourseDetailData() model.album = json["album"].string model.album_logo = json["album_logo"].string model.create_time = json["create_time"].string var array = Array<FoodCourseSerial>() for (_, subjson) in json["data"] { let serialModel = FoodCourseSerial.parse(subjson) array.append(serialModel) } model.data = array model.episode = json["episode"].number model.last_update = json["last_update"].string model.order_no = json["order_no"].string model.play = json["play"].number model.relate_activity = json["relate_activity"].string model.series_id = json["series_id"].string model.series_image = json["series_image"].string model.series_name = json["series_name"].string model.series_title = json["series_title"].string model.share_description = json["share_description"].string model.share_image = json["share_image"].string model.share_title = json["share_title"].string model.share_url = json["share_url"].string model.tag = json["tag"].string return model } } class FoodCourseSerial: NSObject { /* "course_id" : 1539, "course_image" : "http://img.szzhangchu.com/1475996698928_3739207663.jpg", "course_introduce" : "", "course_name" : "韭菜盒子", "course_subject" : "韭菜盒子表皮金黄酥脆,馅心韭香脆嫩,滋味优美,是适时佳点。", "course_video" : "http://video.szzhangchu.com/1475994552338_6022348552.mp4", "episode" : 1, "is_collect" : 0, "is_like" : 0, "ischarge" : "0", "price" : "0", "video_watchcount" : 5016 */ var course_id: NSNumber? var course_image: String? var course_introduce: String? var course_name: String? var course_subject: String? var course_video: String? var episode: NSNumber? var is_collect: NSNumber? var is_like: NSNumber? var ischarge: String? var price: String? var video_watchcount: NSNumber? class func parse(json: JSON) -> FoodCourseSerial { let model = FoodCourseSerial() model.course_id = json["course_id"].number model.course_image = json["course_image"].string model.course_introduce = json["course_introduce"].string model.course_name = json["course_name"].string model.course_subject = json["course_subject"].string model.course_video = json["course_video"].string model.episode = json["episode"].number model.is_collect = json["is_collect"].number model.is_like = json["is_like"].number model.ischarge = json["ischarge"].string model.price = json["price"].string model.video_watchcount = json["video_watchcount"].number return model } }
mit
ef7bebdeca2b6769d047f7dbab475a85
30.50625
151
0.610395
3.358428
false
false
false
false
ZhangMingNan/MenSao
MenSao/Class/Common/Table/View/MainCell.swift
1
1585
// // MainCell.swift // MenSao // // Created by 张明楠 on 16/2/2. // Copyright © 2016年 张明楠. All rights reserved. // import UIKit class MainCell: UITableViewCell { let onSelectedView = UIView() override func awakeFromNib() { super.awakeFromNib() } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = UITableViewCellSelectionStyle.None self.onSelectedView.frame = CGRectMake(0, 0, 6, self.contentView.height()) self.onSelectedView.backgroundColor = UIColor(red: 219/255, green: 21/255, blue: 26/255, alpha: 1) self.onSelectedView.hidden = true self.contentView.addSubview(self.onSelectedView) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // self.leftView?.frame = CGRectMake(0, 0, 8, self.contentView.size().height) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) self.onSelectedView.hidden = !selected if selected { settingSelected() }else { settingUnSelected() } } func settingSelected(){ self.textLabel?.textColor = UIColor(red: 219/255, green: 21/255, blue: 26/255, alpha: 1) } func settingUnSelected(){ self.textLabel?.textColor = UIColor.grayColor() } }
apache-2.0
5c142e5417a6c1a8a58f49ef92b61c72
23.153846
106
0.644586
4.22043
false
false
false
false
malcommac/SwiftDate
Sources/SwiftDate/DateRepresentable.swift
2
18866
// // SwiftDate // Parse, validate, manipulate, and display dates, time and timezones in Swift // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. // import Foundation public protocol DateRepresentable { // MARK: - Date Components var year: Int { get } /// Represented month var month: Int { get } /// Represented month name with given style. /// /// - Parameter style: style in which the name must be formatted. /// - Returns: name of the month func monthName(_ style: SymbolFormatStyle) -> String /// Number of the days in the receiver. var monthDays: Int { get } /// Day unit of the receiver. var day: Int { get } /// Day of year unit of the receiver var dayOfYear: Int { get } /// The number of day in ordinal style format for the receiver in current locale. /// For example, in the en_US locale, the number 3 is represented as 3rd; /// in the fr_FR locale, the number 3 is represented as 3e. @available(iOS 9.0, macOS 10.11, *) var ordinalDay: String { get } /// Hour unit of the receiver. var hour: Int { get } /// Nearest rounded hour from the date var nearestHour: Int { get } /// Minute unit of the receiver. var minute: Int { get } /// Second unit of the receiver. var second: Int { get } /// Nanosecond unit of the receiver. var nanosecond: Int { get } /// Milliseconds in day of the receiver /// This field behaves exactly like a composite of all time-related fields, not including the zone fields. /// As such, it also reflects discontinuities of those fields on DST transition days. /// On a day of DST onset, it will jump forward. On a day of DST cessation, it will jump backward. /// This reflects the fact that is must be combined with the offset field to obtain a unique local time value. var msInDay: Int { get } /// Weekday unit of the receiver. /// The weekday units are the numbers 1-N (where for the Gregorian calendar N=7 and 1 is Sunday). var weekday: Int { get } /// Name of the weekday expressed in given format style. /// /// - Parameter style: style to express the value. /// - Parameter locale: locale to use; ignore it to use default's region locale. /// - Returns: weekday name func weekdayName(_ style: SymbolFormatStyle, locale: LocaleConvertible?) -> String /// Week of a year of the receiver. var weekOfYear: Int { get } /// Week of a month of the receiver. var weekOfMonth: Int { get } /// Ordinal position within the month unit of the corresponding weekday unit. /// For example, in the Gregorian calendar a weekday ordinal unit of 2 for a /// weekday unit 3 indicates "the second Tuesday in the month". var weekdayOrdinal: Int { get } /// Return the first day number of the week where the receiver date is located. var firstDayOfWeek: Int { get } /// Return the last day number of the week where the receiver date is located. var lastDayOfWeek: Int { get } /// Relative year for a week within a year calendar unit. var yearForWeekOfYear: Int { get } /// Quarter value of the receiver. var quarter: Int { get } /// Quarter name expressed in given format style. /// /// - Parameter style: style to express the value. /// - Parameter locale: locale to use; ignore it to use default's region locale. /// - Returns: quarter name func quarterName(_ style: SymbolFormatStyle, locale: LocaleConvertible?) -> String /// Era value of the receiver. var era: Int { get } /// Name of the era expressed in given format style. /// /// - Parameter style: style to express the value. /// - Parameter locale: locale to use; ignore it to use default's region locale. /// - Returns: era func eraName(_ style: SymbolFormatStyle, locale: LocaleConvertible?) -> String /// The current daylight saving time offset of the represented date. var DSTOffset: TimeInterval { get } // MARK: - Common Properties /// Absolute representation of the date var date: Date { get } /// Associated region var region: Region { get } /// Associated calendar var calendar: Calendar { get } /// Extract the date components from the date var dateComponents: DateComponents { get } /// Returns whether the given date is in today as boolean. var isToday: Bool { get } /// Returns whether the given date is in yesterday. var isYesterday: Bool { get } /// Returns whether the given date is in tomorrow. var isTomorrow: Bool { get } /// Returns whether the given date is in the weekend. var isInWeekend: Bool { get } /// Return true if given date represent a passed date var isInPast: Bool { get } /// Return true if given date represent a future date var isInFuture: Bool { get } /// Use this object to format the date object. /// By default this object return the `customFormatter` instance (if set) or the /// local thread shared formatter (via `sharedFormatter()` func; this is the most typical scenario). /// /// - Parameters: /// - format: format string to set. /// - configuration: optional callback used to configure the object inline. /// - Returns: formatter instance func formatter(format: String?, configuration: ((DateFormatter) -> Void)?) -> DateFormatter /// User this object to get an DateFormatter already configured to format the data object with the associated region. /// By default this object return the `customFormatter` instance (if set) configured for region or the /// local thread shared formatter even configured for region (via `sharedFormatter()` func; this is the most typical scenario). /// /// - format: format string to set. /// - configuration: optional callback used to configure the object inline. /// - Returns: formatter instance func formatterForRegion(format: String?, configuration: ((inout DateFormatter) -> Void)?) -> DateFormatter /// Set a custom formatter for this object. /// Typically you should not need to set a value for this property. /// With a `nil` value SwiftDate will uses the threa shared formatter returned by `sharedFormatter()` function. /// In case you need to a custom formatter instance you can override the default behaviour by setting a value here. var customFormatter: DateFormatter? { get set } /// Return a formatter instance created as singleton into the current caller's thread. /// This object is used for formatting when no `dateFormatter` is set for the object /// (this is the common scenario where you want to avoid multiple formatter instances to /// parse dates; instances of DateFormatter are very expensive to create and you should /// use a single instance in each thread to perform this kind of tasks). /// /// - Returns: formatter instance var sharedFormatter: DateFormatter { get } // MARK: - Init /// Initialize a new date by parsing a string. /// /// - Parameters: /// - string: string with the date. /// - format: format used to parse date. Pass `nil` to use built-in formats /// (if you know you should pass it to optimize the parsing process) /// - region: region in which the date in `string` is expressed. init?(_ string: String, format: String?, region: Region) /// Initialize a new date from a number of seconds since the Unix Epoch. /// /// - Parameters: /// - interval: seconds since the Unix Epoch timestamp. /// - region: region in which the date must be expressed. init(seconds interval: TimeInterval, region: Region) /// Initialize a new date corresponding to the number of milliseconds since the Unix Epoch. /// /// - Parameters: /// - interval: seconds since the Unix Epoch timestamp. /// - region: region in which the date must be expressed. init(milliseconds interval: Int, region: Region) /// Initialize a new date with the opportunity to configure single date components via builder pattern. /// Date is therfore expressed in passed region (`DateComponents`'s `timezone`,`calendar` and `locale` are ignored /// and overwritten by the region if not `nil`). /// /// - Parameters: /// - configuration: configuration callback /// - region: region in which the date is expressed. Ignore to use `SwiftDate.defaultRegion`, /// `nil` to use `DateComponents` data. init?(components configuration: ((inout DateComponents) -> Void), region: Region?) /// Initialize a new date with time components passed. /// /// - Parameters: /// - components: date components /// - region: region in which the date is expressed. Ignore to use `SwiftDate.defaultRegion`, /// `nil` to use `DateComponents` data. init?(components: DateComponents, region: Region?) /// Initialize a new date with given components. init(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nanosecond: Int, region: Region) // MARK: - Conversion /// Convert a date to another region. /// /// - Parameter region: destination region in which the date must be represented. /// - Returns: converted date func convertTo(region: Region) -> DateInRegion // MARK: - To String Formatting /// Convert date to a string using passed pre-defined style. /// /// - Parameter style: formatter style, `nil` to use `standard` style /// - Returns: string representation of the date func toString(_ style: DateToStringStyles?) -> String /// Convert date to a string using custom date format. /// /// - Parameters: /// - format: format of the string representation /// - locale: locale to fix a custom locale, `nil` to use associated region's locale /// - Returns: string representation of the date func toFormat(_ format: String, locale: LocaleConvertible?) -> String /// Convert a date to a string representation relative to another reference date (or current /// if not passed). func toRelative(since: DateInRegion?, dateTimeStyle: RelativeDateTimeFormatter.DateTimeStyle, unitsStyle: RelativeDateTimeFormatter.UnitsStyle) -> String /// Return ISO8601 representation of the date /// /// - Parameter options: optional options, if nil extended iso format is used func toISO(_ options: ISOFormatter.Options?) -> String /// Return DOTNET compatible representation of the date. /// /// - Returns: string representation of the date func toDotNET() -> String /// Return SQL compatible representation of the date. /// /// - Returns: string represenation of the date func toSQL() -> String /// Return RSS compatible representation of the date /// /// - Parameter alt: `true` to return altRSS version, `false` to return the standard RSS representation /// - Returns: string representation of the date func toRSS(alt: Bool) -> String // MARK: - Extract Components /// Extract time components for elapsed interval between the receiver date /// and a reference date. /// /// - Parameters: /// - units: units to extract. /// - refDate: reference date /// - Returns: extracted time units func toUnits(_ units: Set<Calendar.Component>, to refDate: DateRepresentable) -> [Calendar.Component: Int] /// Extract time unit component from given date. /// /// - Parameters: /// - unit: time component to extract /// - refDate: reference date /// - Returns: extracted time unit value func toUnit(_ unit: Calendar.Component, to refDate: DateRepresentable) -> Int } public extension DateRepresentable { // MARK: - Common Properties var calendar: Calendar { return region.calendar } // MARK: - Date Components Properties var year: Int { return dateComponents.year! } var month: Int { return dateComponents.month! } var monthDays: Int { return calendar.range(of: .day, in: .month, for: date)!.count } func monthName(_ style: SymbolFormatStyle) -> String { let formatter = self.formatter(format: nil) let idx = (month - 1) switch style { case .default: return formatter.monthSymbols[idx] case .defaultStandalone: return formatter.standaloneMonthSymbols[idx] case .short: return formatter.shortMonthSymbols[idx] case .standaloneShort: return formatter.shortStandaloneMonthSymbols[idx] case .veryShort: return formatter.veryShortMonthSymbols[idx] case .standaloneVeryShort: return formatter.veryShortStandaloneMonthSymbols[idx] } } var day: Int { return dateComponents.day! } var dayOfYear: Int { return calendar.ordinality(of: .day, in: .year, for: date)! } @available(iOS 9.0, macOS 10.11, *) var ordinalDay: String { let day = self.day return DateFormatter.sharedOrdinalNumberFormatter(locale: region.locale).string(from: day as NSNumber) ?? "\(day)" } var hour: Int { return dateComponents.hour! } var nearestHour: Int { let newDate = (date + (date.minute >= 30 ? 60 - date.minute : -date.minute).minutes) return newDate.in(region: region).hour } var minute: Int { return dateComponents.minute! } var second: Int { return dateComponents.second! } var nanosecond: Int { return dateComponents.nanosecond! } var msInDay: Int { return (calendar.ordinality(of: .second, in: .day, for: date)! * 1000) } var weekday: Int { return dateComponents.weekday! } func weekdayName(_ style: SymbolFormatStyle, locale: LocaleConvertible? = nil) -> String { let formatter = self.formatter(format: nil) { $0.locale = (locale ?? self.region.locale).toLocale() } let idx = (weekday - 1) switch style { case .default: return formatter.weekdaySymbols[idx] case .defaultStandalone: return formatter.standaloneWeekdaySymbols[idx] case .short: return formatter.shortWeekdaySymbols[idx] case .standaloneShort: return formatter.shortStandaloneWeekdaySymbols[idx] case .veryShort: return formatter.veryShortWeekdaySymbols[idx] case .standaloneVeryShort: return formatter.veryShortStandaloneWeekdaySymbols[idx] } } var weekOfYear: Int { return dateComponents.weekOfYear! } var weekOfMonth: Int { return dateComponents.weekOfMonth! } var weekdayOrdinal: Int { return dateComponents.weekdayOrdinal! } var yearForWeekOfYear: Int { return dateComponents.yearForWeekOfYear! } var firstDayOfWeek: Int { return date.dateAt(.startOfWeek).day } var lastDayOfWeek: Int { return date.dateAt(.endOfWeek).day } var quarter: Int { let monthsInQuarter = Double(Calendar.current.monthSymbols.count) / 4.0 return Int(ceil( Double(month) / monthsInQuarter)) } var isToday: Bool { return calendar.isDateInToday(date) } var isYesterday: Bool { return calendar.isDateInYesterday(date) } var isTomorrow: Bool { return calendar.isDateInTomorrow(date) } var isInWeekend: Bool { return calendar.isDateInWeekend(date) } var isInPast: Bool { return date < Date() } var isInFuture: Bool { return date > Date() } func quarterName(_ style: SymbolFormatStyle, locale: LocaleConvertible? = nil) -> String { let formatter = self.formatter(format: nil) { $0.locale = (locale ?? self.region.locale).toLocale() } let idx = (quarter - 1) switch style { case .default: return formatter.quarterSymbols[idx] case .defaultStandalone: return formatter.standaloneQuarterSymbols[idx] case .short, .veryShort: return formatter.shortQuarterSymbols[idx] case .standaloneShort, .standaloneVeryShort: return formatter.shortStandaloneQuarterSymbols[idx] } } var era: Int { return dateComponents.era! } func eraName(_ style: SymbolFormatStyle, locale: LocaleConvertible? = nil) -> String { let formatter = self.formatter(format: nil) { $0.locale = (locale ?? self.region.locale).toLocale() } let idx = (era - 1) switch style { case .default, .defaultStandalone: return formatter.longEraSymbols[idx] case .short, .standaloneShort, .veryShort, .standaloneVeryShort: return formatter.eraSymbols[idx] } } var DSTOffset: TimeInterval { return region.timeZone.daylightSavingTimeOffset(for: date) } // MARK: - Date Formatters func formatter(format: String? = nil, configuration: ((DateFormatter) -> Void)? = nil) -> DateFormatter { let formatter = (customFormatter ?? sharedFormatter) if let dFormat = format { formatter.dateFormat = dFormat } configuration?(formatter) return formatter } func formatterForRegion(format: String? = nil, configuration: ((inout DateFormatter) -> Void)? = nil) -> DateFormatter { var formatter = self.formatter(format: format, configuration: { $0.timeZone = self.region.timeZone $0.calendar = self.calendar $0.locale = self.region.locale }) configuration?(&formatter) return formatter } var sharedFormatter: DateFormatter { return DateFormatter.sharedFormatter(forRegion: region) } func toString(_ style: DateToStringStyles? = nil) -> String { guard let style = style else { return DateToStringStyles.standard.toString(self) } return style.toString(self) } func toFormat(_ format: String, locale: LocaleConvertible? = nil) -> String { guard let fixedLocale = locale else { return DateToStringStyles.custom(format).toString(self) } let fixedRegion = Region(calendar: region.calendar, zone: region.timeZone, locale: fixedLocale) let fixedDate = DateInRegion(date.date, region: fixedRegion) return DateToStringStyles.custom(format).toString(fixedDate) } func toRelative(since: DateInRegion?, dateTimeStyle: RelativeDateTimeFormatter.DateTimeStyle = .named, unitsStyle: RelativeDateTimeFormatter.UnitsStyle = .short) -> String { let formatter = RelativeDateTimeFormatter() formatter.dateTimeStyle = dateTimeStyle formatter.unitsStyle = unitsStyle return formatter.localizedString(for: self.date, relativeTo: since?.date ?? Date()) } func toISO(_ options: ISOFormatter.Options? = nil) -> String { return DateToStringStyles.iso( (options ?? ISOFormatter.Options([.withInternetDateTime])) ).toString(self) } func toDotNET() -> String { return DOTNETFormatter.format(self, options: nil) } func toRSS(alt: Bool) -> String { switch alt { case true: return DateToStringStyles.altRSS.toString(self) case false: return DateToStringStyles.rss.toString(self) } } func toSQL() -> String { return DateToStringStyles.sql.toString(self) } // MARK: - Conversion func convertTo(region: Region) -> DateInRegion { return DateInRegion(date, region: region) } // MARK: - Extract Time Components func toUnits(_ units: Set<Calendar.Component>, to refDate: DateRepresentable) -> [Calendar.Component: Int] { let cal = region.calendar let components = cal.dateComponents(units, from: date, to: refDate.date) return components.toDict() } func toUnit(_ unit: Calendar.Component, to refDate: DateRepresentable) -> Int { let cal = region.calendar let components = cal.dateComponents([unit], from: date, to: refDate.date) return components.value(for: unit)! } }
mit
59e74ecce4d6cd2c1ba6a0f63ae83ddc
32.038529
128
0.710363
3.853145
false
false
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 10 - Extensions - Share/Imgvue/ImgvueKit/ImageFilterService.swift
1
2809
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import UIKit public class ImageFilterService { public init() { } public func availableFilters() -> Dictionary<String, String> { return ["Sepia": "CISepiaTone", "Invert": "CIColorInvert", "Vintage": "CIPhotoEffectTransfer", "Black & White": "CIPhotoEffectMono"] } public func applyFilter(filterName: String, toImage image: UIImage) -> UIImage { let filter = CIFilter(name: filterName) filter!.setDefaults() let orientation = orientationFromImageOrientation(image.imageOrientation) let ciImage = CIImage(CGImage: image.CGImage!) let inputImage = ciImage.imageByApplyingOrientation(orientation) filter!.setValue(inputImage, forKey: kCIInputImageKey) let outputImage = filter!.outputImage let context = CIContext(options: nil) let cgImageRef = context.createCGImage(outputImage!, fromRect: outputImage!.extent) let filteredImage = UIImage(CGImage: cgImageRef) return filteredImage // if let filteredImage = UIImage(CGImage: cgImageRef) { // return filteredImage // } else { // return image // } } private func orientationFromImageOrientation(imageOrientation: UIImageOrientation) -> CInt { var orientation: CInt = 0 switch (imageOrientation) { case .Up: orientation = 1 case .Down: orientation = 3 case .Left: orientation = 8 case .Right: orientation = 6 case .UpMirrored: orientation = 2 case .DownMirrored: orientation = 4 case .LeftMirrored: orientation = 5 case .RightMirrored: orientation = 7 } return orientation } }
mit
5ad3c372a6735915dd8f4cd5947ed287
33.691358
94
0.700961
4.721008
false
false
false
false
dreamsxin/swift
benchmark/single-source/DictionarySwap.swift
5
2486
//===--- DictionarySwap.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Dictionary element swapping benchmark // rdar://problem/19804127 import TestsUtils @inline(never) public func run_DictionarySwap(_ N: Int) { let size = 100 var dict = [Int: Int](minimumCapacity: size) // Fill dictionary for i in 1...size { dict[i] = i } CheckResults(dict.count == size, "Incorrect dict count: \(dict.count) != \(size).") var swapped = false for _ in 1...10000*N { swap(&dict[25]!, &dict[75]!) swapped = !swapped if !swappedCorrectly(swapped, dict[25]!, dict[75]!) { break } } CheckResults(swappedCorrectly(swapped, dict[25]!, dict[75]!), "Dictionary value swap failed") } // Return true if correctly swapped, false otherwise func swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool { return swapped && (p25 == 75 && p75 == 25) || !swapped && (p25 == 25 && p75 == 75) } class Box<T : Hashable where T : Equatable> : Hashable { var value: T init(_ v: T) { value = v } var hashValue : Int { return value.hashValue } } extension Box : Equatable { } func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool { return lhs.value == rhs.value } @inline(never) public func run_DictionarySwapOfObjects(_ N: Int) { let size = 100 var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size) // Fill dictionary for i in 1...size { dict[Box(i)] = Box(i) } CheckResults(dict.count == size, "Incorrect dict count: \(dict.count) != \(size).") var swapped = false for _ in 1...10000*N { swap(&dict[Box(25)]!, &dict[Box(75)]!) swapped = !swapped if !swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value) { break } } CheckResults(swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value), "Dictionary value swap failed") }
apache-2.0
f0e58e9a5ac9daa299a16eb3ba9643bf
26.622222
87
0.565165
3.92733
false
false
false
false
codeforgreenville/trolley-tracker-ios-client
TrolleyTracker/Dependencies/UIKitHelpers.swift
1
3725
// // UIKitHelpers.swift // Created by Austin on 5/6/17. // import UIKit extension UICollectionView { var flowLayout: UICollectionViewFlowLayout? { return collectionViewLayout as? UICollectionViewFlowLayout } public func dequeueCell<T>(ofType type: T.Type, identifier: String? = nil, for indexPath: IndexPath) -> T where T: UICollectionViewCell { let cellId = identifier ?? String(describing: type) let cell = dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) guard let typedCell = cell as? T else { fatalError("Dequeued cell with identifier: \(String(describing: identifier)), " + "expecting it to be of type: \(type), " + "but instead it was: \(cell.self)") } return typedCell } public func dequeueReusableView<T>(ofType type: T.Type, ofKind kind: String, identifier: String? = nil, at indexPath: IndexPath) -> T where T: UICollectionReusableView { let id = identifier ?? String(describing: type) let view = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: id, for: indexPath) guard let typedView = view as? T else { fatalError() } return typedView } public func registerCell<T>(ofType type: T.Type) where T: UICollectionViewCell { let identifier = String(describing: type) register(type, forCellWithReuseIdentifier: identifier) } public func registerSupplementaryView<T>(ofType type: T.Type, ofKind kind: String) where T: UICollectionReusableView { let identifier = String(describing: type) register(type, forSupplementaryViewOfKind: kind, withReuseIdentifier: identifier) } } extension UITableView { public func dequeueCell<T>(ofType type: T.Type, identifier: String? = nil, for indexPath: IndexPath) -> T where T: UITableViewCell { let cellId = identifier ?? String(describing: type) let cell = dequeueReusableCell(withIdentifier: cellId, for: indexPath) guard let typedCell = cell as? T else { fatalError("Dequeued cell with identifier: \(String(describing: identifier)), " + "expecting it to be of type: \(type), " + "but instead it was: \(cell.self)") } return typedCell } public func deqeueView<T>(ofType type: T.Type, identifier: String? = nil) -> T where T: UITableViewHeaderFooterView { let viewId = identifier ?? String(describing: type) let view = dequeueReusableHeaderFooterView(withIdentifier: viewId) guard let typedView = view as? T else { fatalError("Dequeued cell with identifier: \(String(describing: viewId)), " + "expecting it to be of type: \(type), " + "but instead it was: \(String(describing: view.self))") } return typedView } public func registerCell<T>(ofType type: T.Type) where T: UITableViewCell { let identifier = String(describing: type) register(type, forCellReuseIdentifier: identifier) } public func registerView<T>(ofType type: T.Type) where T: UITableViewHeaderFooterView { let identifier = String(describing: type) register(type, forHeaderFooterViewReuseIdentifier: identifier) } }
mit
a0d761ab874d3a32fc6226960584362e
36.626263
101
0.587651
5.313837
false
false
false
false
xocialize/Kiosk
kiosk/HRToast+UIView.swift
2
16315
// // HRToast + UIView.swift // ToastDemo // // Created by Rannie on 14/7/6. // Copyright (c) 2014年 Rannie. All rights reserved. // import UIKit /* * Infix overload method */ func /(lhs: CGFloat, rhs: Int) -> CGFloat { return lhs / CGFloat(rhs) } /* * Toast Config */ let HRToastDefaultDuration = 2.0 let HRToastFadeDuration = 0.2 let HRToastHorizontalMargin : CGFloat = 10.0 let HRToastVerticalMargin : CGFloat = 10.0 let HRToastPositionDefault = "bottom" let HRToastPositionTop = "top" let HRToastPositionCenter = "center" // activity let HRToastActivityWidth : CGFloat = 100.0 let HRToastActivityHeight : CGFloat = 100.0 let HRToastActivityPositionDefault = "center" // image size let HRToastImageViewWidth : CGFloat = 80.0 let HRToastImageViewHeight: CGFloat = 80.0 // label setting let HRToastMaxWidth : CGFloat = 0.8; // 80% of parent view width let HRToastMaxHeight : CGFloat = 0.8; let HRToastFontSize : CGFloat = 16.0 let HRToastMaxTitleLines = 0 let HRToastMaxMessageLines = 0 // shadow appearance let HRToastShadowOpacity : CGFloat = 0.8 let HRToastShadowRadius : CGFloat = 6.0 let HRToastShadowOffset : CGSize = CGSizeMake(CGFloat(4.0), CGFloat(4.0)) let HRToastOpacity : CGFloat = 0.8 let HRToastCornerRadius : CGFloat = 10.0 var HRToastActivityView: UnsafePointer<UIView> = nil var HRToastTimer: UnsafePointer<NSTimer> = nil var HRToastView: UnsafePointer<UIView> = nil /* * Custom Config */ let HRToastHidesOnTap = true let HRToastDisplayShadow = true //HRToast (UIView + Toast using Swift) extension UIView { /* * public methods */ func makeToast(message msg: String) { self.makeToast(message: msg, duration: HRToastDefaultDuration, position: HRToastPositionDefault) } func makeToast(message msg: String, duration: Double, position: AnyObject) { var toast = self.viewForMessage(msg, title: nil, image: nil) self.showToast(toast: toast!, duration: duration, position: position) } func makeToast(message msg: String, duration: Double, position: AnyObject, title: String) { var toast = self.viewForMessage(msg, title: title, image: nil) self.showToast(toast: toast!, duration: duration, position: position) } func makeToast(message msg: String, duration: Double, position: AnyObject, image: UIImage) { var toast = self.viewForMessage(msg, title: nil, image: image) self.showToast(toast: toast!, duration: duration, position: position) } func makeToast(message msg: String, duration: Double, position: AnyObject, title: String, image: UIImage) { var toast = self.viewForMessage(msg, title: title, image: image) self.showToast(toast: toast!, duration: duration, position: position) } func showToast(#toast: UIView) { self.showToast(toast: toast, duration: HRToastDefaultDuration, position: HRToastPositionDefault) } func showToast(#toast: UIView, duration: Double, position: AnyObject) { var existToast = objc_getAssociatedObject(self, &HRToastView) as! UIView? if existToast != nil { if let timer: NSTimer = objc_getAssociatedObject(existToast, &HRToastTimer) as? NSTimer { timer.invalidate(); } self.hideToast(toast: existToast!, force: false); } toast.center = self.centerPointForPosition(position, toast: toast) toast.alpha = 0.0 if HRToastHidesOnTap { var tapRecognizer = UITapGestureRecognizer(target: toast, action: Selector("handleToastTapped:")) toast.addGestureRecognizer(tapRecognizer) toast.userInteractionEnabled = true; toast.exclusiveTouch = true; } self.addSubview(toast) objc_setAssociatedObject(self, &HRToastView, toast, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN)) UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: (.CurveEaseOut | .AllowUserInteraction), animations: { toast.alpha = 1.0 }, completion: { (finished: Bool) in var timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("toastTimerDidFinish:"), userInfo: toast, repeats: false) objc_setAssociatedObject(toast, &HRToastTimer, timer, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) }) } func makeToastActivity() { self.makeToastActivity(position: HRToastActivityPositionDefault) } func makeToastActivityWithMessage(message msg: String){ self.makeToastActivity(position: HRToastActivityPositionDefault, message: msg) } func makeToastActivity(position pos: AnyObject, message msg: String = "") { var existingActivityView: UIView? = objc_getAssociatedObject(self, &HRToastActivityView) as? UIView if existingActivityView != nil { return } var activityView = UIView(frame: CGRectMake(0, 0, HRToastActivityWidth, HRToastActivityHeight)) activityView.center = self.centerPointForPosition(pos, toast: activityView) activityView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(HRToastOpacity) activityView.alpha = 0.0 activityView.autoresizingMask = (.FlexibleLeftMargin | .FlexibleTopMargin | .FlexibleRightMargin | .FlexibleBottomMargin) activityView.layer.cornerRadius = HRToastCornerRadius if HRToastDisplayShadow { activityView.layer.shadowColor = UIColor.blackColor().CGColor activityView.layer.shadowOpacity = Float(HRToastShadowOpacity) activityView.layer.shadowRadius = HRToastShadowRadius activityView.layer.shadowOffset = HRToastShadowOffset } var activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) activityIndicatorView.center = CGPointMake(activityView.bounds.size.width / 2, activityView.bounds.size.height / 2) activityView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() if (!msg.isEmpty){ activityIndicatorView.frame.origin.y -= 10 var activityMessageLabel = UILabel(frame: CGRectMake(activityView.bounds.origin.x, (activityIndicatorView.frame.origin.y + activityIndicatorView.frame.size.height + 10), activityView.bounds.size.width, 20)) activityMessageLabel.textColor = UIColor.whiteColor() activityMessageLabel.font = (count(msg)<=10) ? UIFont(name:activityMessageLabel.font.fontName, size: 16) : UIFont(name:activityMessageLabel.font.fontName, size: 13) activityMessageLabel.textAlignment = .Center activityMessageLabel.text = msg activityView.addSubview(activityMessageLabel) } self.addSubview(activityView) // associate activity view with self objc_setAssociatedObject(self, &HRToastActivityView, activityView, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { activityView.alpha = 1.0 }, completion: nil) } func hideToastActivity() { var existingActivityView = objc_getAssociatedObject(self, &HRToastActivityView) as! UIView? if existingActivityView == nil { return } UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { existingActivityView!.alpha = 0.0 }, completion: { (finished: Bool) in existingActivityView!.removeFromSuperview() objc_setAssociatedObject(self, &HRToastActivityView, nil, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) }) } /* * private methods (helper) */ func hideToast(#toast: UIView) { self.hideToast(toast: toast, force: false); } func hideToast(#toast: UIView, force: Bool) { var completeClosure = { (finish: Bool) -> () in toast.removeFromSuperview() objc_setAssociatedObject(self, &HRToastTimer, nil, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } if force { completeClosure(true) } else { UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: (.CurveEaseIn | .BeginFromCurrentState), animations: { toast.alpha = 0.0 }, completion:completeClosure) } } func toastTimerDidFinish(timer: NSTimer) { self.hideToast(toast: timer.userInfo as! UIView) } func handleToastTapped(recognizer: UITapGestureRecognizer) { var timer = objc_getAssociatedObject(self, &HRToastTimer) as! NSTimer timer.invalidate() self.hideToast(toast: recognizer.view!) } func centerPointForPosition(position: AnyObject, toast: UIView) -> CGPoint { if position is String { var toastSize = toast.bounds.size var viewSize = self.bounds.size if position.lowercaseString == HRToastPositionTop { return CGPointMake(viewSize.width/2, toastSize.height/2 + HRToastVerticalMargin) } else if position.lowercaseString == HRToastPositionDefault { return CGPointMake(viewSize.width/2, viewSize.height - toastSize.height/2 - HRToastVerticalMargin) } else if position.lowercaseString == HRToastPositionCenter { return CGPointMake(viewSize.width/2, viewSize.height/2) } } else if position is NSValue { return position.CGPointValue() } println("Warning: Invalid position for toast.") return self.centerPointForPosition(HRToastPositionDefault, toast: toast) } func viewForMessage(msg: String?, title: String?, image: UIImage?) -> UIView? { if msg == nil && title == nil && image == nil { return nil } var msgLabel: UILabel? var titleLabel: UILabel? var imageView: UIImageView? var wrapperView = UIView() wrapperView.autoresizingMask = (.FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleTopMargin | .FlexibleBottomMargin) wrapperView.layer.cornerRadius = HRToastCornerRadius wrapperView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(HRToastOpacity) if HRToastDisplayShadow { wrapperView.layer.shadowColor = UIColor.blackColor().CGColor wrapperView.layer.shadowOpacity = Float(HRToastShadowOpacity) wrapperView.layer.shadowRadius = HRToastShadowRadius wrapperView.layer.shadowOffset = HRToastShadowOffset } if image != nil { imageView = UIImageView(image: image) imageView!.contentMode = .ScaleAspectFit imageView!.frame = CGRectMake(HRToastHorizontalMargin, HRToastVerticalMargin, CGFloat(HRToastImageViewWidth), CGFloat(HRToastImageViewHeight)) } var imageWidth: CGFloat, imageHeight: CGFloat, imageLeft: CGFloat if imageView != nil { imageWidth = imageView!.bounds.size.width imageHeight = imageView!.bounds.size.height imageLeft = HRToastHorizontalMargin } else { imageWidth = 0.0; imageHeight = 0.0; imageLeft = 0.0 } if title != nil { titleLabel = UILabel() titleLabel!.numberOfLines = HRToastMaxTitleLines titleLabel!.font = UIFont.boldSystemFontOfSize(HRToastFontSize) titleLabel!.textAlignment = .Center titleLabel!.lineBreakMode = .ByWordWrapping titleLabel!.textColor = UIColor.whiteColor() titleLabel!.backgroundColor = UIColor.clearColor() titleLabel!.alpha = 1.0 titleLabel!.text = title // size the title label according to the length of the text var maxSizeTitle = CGSizeMake((self.bounds.size.width * HRToastMaxWidth) - imageWidth, self.bounds.size.height * HRToastMaxHeight); var expectedHeight = title!.stringHeightWithFontSize(HRToastFontSize, width: maxSizeTitle.width) titleLabel!.frame = CGRectMake(0.0, 0.0, maxSizeTitle.width, expectedHeight) } if msg != nil { msgLabel = UILabel(); msgLabel!.numberOfLines = HRToastMaxMessageLines msgLabel!.font = UIFont.systemFontOfSize(HRToastFontSize) msgLabel!.lineBreakMode = .ByWordWrapping msgLabel!.textAlignment = .Center msgLabel!.textColor = UIColor.whiteColor() msgLabel!.backgroundColor = UIColor.clearColor() msgLabel!.alpha = 1.0 msgLabel!.text = msg var maxSizeMessage = CGSizeMake((self.bounds.size.width * HRToastMaxWidth) - imageWidth, self.bounds.size.height * HRToastMaxHeight) var expectedHeight = msg!.stringHeightWithFontSize(HRToastFontSize, width: maxSizeMessage.width) msgLabel!.frame = CGRectMake(0.0, 0.0, maxSizeMessage.width, expectedHeight) } var titleWidth: CGFloat, titleHeight: CGFloat, titleTop: CGFloat, titleLeft: CGFloat if titleLabel != nil { titleWidth = titleLabel!.bounds.size.width titleHeight = titleLabel!.bounds.size.height titleTop = HRToastVerticalMargin titleLeft = imageLeft + imageWidth + HRToastHorizontalMargin } else { titleWidth = 0.0; titleHeight = 0.0; titleTop = 0.0; titleLeft = 0.0 } var msgWidth: CGFloat, msgHeight: CGFloat, msgTop: CGFloat, msgLeft: CGFloat if msgLabel != nil { msgWidth = msgLabel!.bounds.size.width msgHeight = msgLabel!.bounds.size.height msgTop = titleTop + titleHeight + HRToastVerticalMargin msgLeft = imageLeft + imageWidth + HRToastHorizontalMargin } else { msgWidth = 0.0; msgHeight = 0.0; msgTop = 0.0; msgLeft = 0.0 } var largerWidth = max(titleWidth, msgWidth) var largerLeft = max(titleLeft, msgLeft) // set wrapper view's frame var wrapperWidth = max(imageWidth + HRToastHorizontalMargin * 2, largerLeft + largerWidth + HRToastHorizontalMargin) var wrapperHeight = max(msgTop + msgHeight + HRToastVerticalMargin, imageHeight + HRToastVerticalMargin * 2) wrapperView.frame = CGRectMake(0.0, 0.0, wrapperWidth, wrapperHeight) // add subviews if titleLabel != nil { titleLabel!.frame = CGRectMake(titleLeft, titleTop, titleWidth, titleHeight) wrapperView.addSubview(titleLabel!) } if msgLabel != nil { msgLabel!.frame = CGRectMake(msgLeft, msgTop, msgWidth, msgHeight) wrapperView.addSubview(msgLabel!) } if imageView != nil { wrapperView.addSubview(imageView!) } return wrapperView } } extension String { func stringHeightWithFontSize(fontSize: CGFloat,width: CGFloat) -> CGFloat { var font = UIFont.systemFontOfSize(fontSize) var size = CGSizeMake(width, CGFloat.max) var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .ByWordWrapping; var attributes = [NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy()] var text = self as NSString var rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context:nil) return rect.size.height } }
mit
4f4a227a9c3f5d2aeefdfac89a08825d
41.043814
218
0.646662
4.928399
false
false
false
false
XSega/Words
Pods/RSLoadingView/RSLoadingView/Classes/RSLoadingView.swift
1
7336
import UIKit import QuartzCore import SceneKit protocol RSLoadingViewEffect { func setup(main: RSLoadingView) func prepareForResize(main: RSLoadingView) func update(at time: TimeInterval) } public class RSLoadingView: UIView, SCNSceneRendererDelegate { public enum Effect: String { case spinAlone, twins } @IBInspectable public var speedFactor: CGFloat = 1.0 @IBInspectable public var mainColor: UIColor = UIColor.white @IBInspectable public var colorVariation: CGFloat = 0.0 @IBInspectable public var sizeFactor: CGFloat = 1.0 @IBInspectable public var spreadingFactor: CGFloat = 1.0 @IBInspectable public var lifeSpanFactor: CGFloat = 1.0 @IBInspectable public var variantKey: String = "" fileprivate var effect: RSLoadingViewEffect = RSLoadingSpinAlone() let logger = RSLogger(tag: "RSLoadingView") var scnView: SCNView! let scene = SCNScene() let cameraNode = SCNNode() var bundleResourcePath: String = "" var pixelPerUnit: Float = 0 var widthInUnit: Float = 0 var heightInUnit: Float = 0 var topLeftPoint: SCNVector3 = SCNVector3Zero var topRightPoint: SCNVector3 = SCNVector3Zero var bottomLeftPoint: SCNVector3 = SCNVector3Zero var bottomRightPoint: SCNVector3 = SCNVector3Zero var isResized = true var containerView: RSLoadingContainerView? public var shouldDimBackground = true public var dimBackgroundColor = UIColor.black.withAlphaComponent(0.6) public var isBlocking = true public var shouldTapToDismiss = false public var sizeInContainer: CGSize = CGSize(width: 180, height: 180) deinit { logger.logDebug("deinit") } public init(effectType: Effect? = nil) { if let effectType = effectType { switch effectType { case .spinAlone: effect = RSLoadingSpinAlone() break case .twins: effect = RSLoadingTwins() break } } super.init(frame: CGRect.zero) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } override open func awakeFromNib() { super.awakeFromNib() setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open func setup() { logger.logDebug("setup") scnView = SCNView(frame: CGRect.zero, options: [SCNView.Option.preferredRenderingAPI.rawValue: NSNumber(value: 1)]) scnView.delegate = self addSubview(scnView) scnView.scene = scene scnView.allowsCameraControl = false scnView.backgroundColor = backgroundColor cameraNode.camera = SCNCamera() scene.rootNode.addChildNode(cameraNode) cameraNode.position = SCNVector3(x: 0, y: 0, z: 15) bundleResourcePath = "/Frameworks/RSLoadingView.framework/RSLoadingView.bundle/" effect.setup(main: self) } public override func layoutSubviews() { super.layoutSubviews() scnView.frame = bounds isResized = true } open func prepareForResize() { logger.logDebug("prepareForResize Size: \(bounds.size)") let pointZero = scnView.projectPoint(SCNVector3Zero) let pointOne = scnView.projectPoint(SCNVector3Make(1, 0, 0)) pixelPerUnit = pointOne.x - pointZero.x topLeftPoint = scnView.unprojectPoint(SCNVector3Make(0, 0, pointZero.z)) topRightPoint = scnView.unprojectPoint(SCNVector3Make(bounds.size.width.asFloat, 0, pointZero.z)) bottomLeftPoint = scnView.unprojectPoint(SCNVector3Make(0, bounds.size.height.asFloat, pointZero.z)) bottomRightPoint = scnView.unprojectPoint(SCNVector3Make(bounds.size.width.asFloat, bounds.size.height.asFloat, pointZero.z)) widthInUnit = topRightPoint.x * 2 heightInUnit = topRightPoint.y * 2 logger.logDebug("pixelPerUnit \(pixelPerUnit)") logger.logDebug("topLeftPoint \(topLeftPoint)") logger.logDebug("topRightPoint \(topRightPoint)") logger.logDebug("bottomLeftPoint \(bottomLeftPoint)") logger.logDebug("bottomRightPoint \(bottomRightPoint)") logger.logDebug("sizeInUnit \(widthInUnit) x \(heightInUnit)") effect.prepareForResize(main: self) } public func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { //logger.logDebug("updateAtTime \(time)") if isResized { prepareForResize() isResized = false } else { effect.update(at: time) } } func loadParticleSystem(name: String) -> SCNParticleSystem? { if let particleSystem = SCNParticleSystem(named: name, inDirectory: bundleResourcePath) { return particleSystem } else { logger.logDebug("Can't load particleSystem \(name) at \(bundleResourcePath)") return nil } } func loadParticleImage(name: String) -> UIImage? { let frameworkBundle = Bundle(for: RSLoadingView.self) let bundleURL = frameworkBundle.url(forResource: "RSLoadingView", withExtension: "bundle")! let resourceBundle = Bundle(url: bundleURL)! if let image = UIImage(named: name, in: resourceBundle, compatibleWith: nil) { return image } else { logger.logDebug("Can't load particleImage \(name) at \(resourceBundle.bundlePath)") return nil } } public func showOnKeyWindow() { show(on: UIApplication.shared.keyWindow!) } public func show(on view: UIView) { // Remove existing container views let containerViews = view.subviews.filter { (view) -> Bool in return view is RSLoadingContainerView } containerViews.forEach { (view) in view.removeFromSuperview() } backgroundColor = UIColor.clear scnView.backgroundColor = backgroundColor containerView = RSLoadingContainerView(loadingView: self) if let containerView = containerView { view.addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true containerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true containerView.isHidden = true if shouldTapToDismiss { containerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hide))) } showContainerView() } } static public func hideFromKeyWindow() { hide(from: UIApplication.shared.keyWindow!) } static public func hide(from view: UIView) { let containerViews = view.subviews.filter { (view) -> Bool in return view is RSLoadingContainerView } containerViews.forEach { (view) in if let containerView = view as? RSLoadingContainerView { containerView.loadingView.hide() } } } open func hide() { hideContainerView() } fileprivate func showContainerView() { if let containerView = containerView { containerView.isHidden = false containerView.alpha = 0.0 UIView.animate(withDuration: 0.3) { containerView.alpha = 1.0 } } } fileprivate func hideContainerView() { if let containerView = containerView { UIView.animate(withDuration: 0.3, animations: { containerView.alpha = 0.0 }, completion: { _ in containerView.free() }) } } }
mit
43e265e378311678dfea9a8d039d1bf4
31.896861
129
0.705153
4.514462
false
false
false
false
cikelengfeng/Jude
Jude/Antlr4/CommonToken.swift
2
8028
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. public class CommonToken: WritableToken { /// An empty {@link org.antlr.v4.runtime.misc.Pair} which is used as the default value of /// {@link #source} for tokens that do not have a source. internal static let EMPTY_SOURCE: (TokenSource?, CharStream?) = (nil, nil) /// This is the backing field for {@link #getType} and {@link #setType}. internal var type: Int /// This is the backing field for {@link #getLine} and {@link #setLine}. internal var line: Int = 0 /// This is the backing field for {@link #getCharPositionInLine} and /// {@link #setCharPositionInLine}. internal var charPositionInLine: Int = -1 // set to invalid position /// This is the backing field for {@link #getChannel} and /// {@link #setChannel}. internal var channel: Int = DEFAULT_CHANNEL /// This is the backing field for {@link #getTokenSource} and /// {@link #getInputStream}. /// /// <p> /// These properties share a field to reduce the memory footprint of /// {@link org.antlr.v4.runtime.CommonToken}. Tokens created by a {@link org.antlr.v4.runtime.CommonTokenFactory} from /// the same source and input stream share a reference to the same /// {@link org.antlr.v4.runtime.misc.Pair} containing these values.</p> internal var source: (TokenSource?, CharStream?) /// This is the backing field for {@link #getText} when the token text is /// explicitly set in the constructor or via {@link #setText}. /// /// - seealso: #getText() internal var text: String? /// This is the backing field for {@link #getTokenIndex} and /// {@link #setTokenIndex}. internal var index: Int = -1 /// This is the backing field for {@link #getStartIndex} and /// {@link #setStartIndex}. internal var start: Int = 0 /// This is the backing field for {@link #getStopIndex} and /// {@link #setStopIndex}. internal var stop: Int = 0 /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type. /// /// - parameter type: The token type. private var _visited: Bool = false public init(_ type: Int) { self.type = type self.source = CommonToken.EMPTY_SOURCE } public init(_ source: (TokenSource?, CharStream?), _ type: Int, _ channel: Int, _ start: Int, _ stop: Int) { self.source = source self.type = type self.channel = channel self.start = start self.stop = stop if let tsource = source.0 { self.line = tsource.getLine() self.charPositionInLine = tsource.getCharPositionInLine() } } /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type and /// text. /// /// - parameter type: The token type. /// - parameter text: The text of the token. public init(_ type: Int, _ text: String?) { self.type = type self.channel = CommonToken.DEFAULT_CHANNEL self.text = text self.source = CommonToken.EMPTY_SOURCE } /// Constructs a new {@link org.antlr.v4.runtime.CommonToken} as a copy of another {@link org.antlr.v4.runtime.Token}. /// /// <p> /// If {@code oldToken} is also a {@link org.antlr.v4.runtime.CommonToken} instance, the newly /// constructed token will share a reference to the {@link #text} field and /// the {@link org.antlr.v4.runtime.misc.Pair} stored in {@link #source}. Otherwise, {@link #text} will /// be assigned the result of calling {@link #getText}, and {@link #source} /// will be constructed from the result of {@link org.antlr.v4.runtime.Token#getTokenSource} and /// {@link org.antlr.v4.runtime.Token#getInputStream}.</p> /// /// - parameter oldToken: The token to copy. public init(_ oldToken: Token) { type = oldToken.getType() line = oldToken.getLine() index = oldToken.getTokenIndex() charPositionInLine = oldToken.getCharPositionInLine() channel = oldToken.getChannel() start = oldToken.getStartIndex() stop = oldToken.getStopIndex() if oldToken is CommonToken { text = (oldToken as! CommonToken).text source = (oldToken as! CommonToken).source } else { text = oldToken.getText() source = (oldToken.getTokenSource(), oldToken.getInputStream()) } } public func getType() -> Int { return type } public func setLine(_ line: Int) { self.line = line } public func getText() -> String? { if text != nil { return text! } if let input = getInputStream() { let n: Int = input.size() if start < n && stop < n { return input.getText(Interval.of(start, stop)) } else { return "<EOF>" } } return nil } /// Explicitly set the text for this token. If {code text} is not /// {@code null}, then {@link #getText} will return this value rather than /// extracting the text from the input. /// /// - parameter text: The explicit text of the token, or {@code null} if the text /// should be obtained from the input along with the start and stop indexes /// of the token. public func setText(_ text: String) { self.text = text } public func getLine() -> Int { return line } public func getCharPositionInLine() -> Int { return charPositionInLine } public func setCharPositionInLine(_ charPositionInLine: Int) { self.charPositionInLine = charPositionInLine } public func getChannel() -> Int { return channel } public func setChannel(_ channel: Int) { self.channel = channel } public func setType(_ type: Int) { self.type = type } public func getStartIndex() -> Int { return start } public func setStartIndex(_ start: Int) { self.start = start } public func getStopIndex() -> Int { return stop } public func setStopIndex(_ stop: Int) { self.stop = stop } public func getTokenIndex() -> Int { return index } public func setTokenIndex(_ index: Int) { self.index = index } public func getTokenSource() -> TokenSource? { return source.0 } public func getInputStream() -> CharStream? { return source.1 } public var description: String { return toString(nil) } public func toString(_ r: Recognizer<ATNSimulator>?) -> String { var channelStr: String = "" if channel > 0 { channelStr = ",channel=\(channel)" } var txt: String if let tokenText = getText() { txt = tokenText.replaceAll("\n", replacement: "\\n") txt = txt.replaceAll("\r", replacement: "\\r") txt = txt.replaceAll("\t", replacement: "\\t") } else { txt = "<no text>" } var typeString = "\(type)" if let r = r { typeString = r.getVocabulary().getDisplayName(type); } return "[@"+getTokenIndex()+","+start+":"+stop+"='"+txt+"',<"+typeString+">"+channelStr+","+line+":"+getCharPositionInLine()+"]" // let desc: StringBuilder = StringBuilder() // desc.append("[@\(getTokenIndex()),") // desc.append("\(start):\(stop)='\(txt)',") // desc.append("<\(typeString)>\(channelStr),") // desc.append("\(line):\(getCharPositionInLine())]") // // return desc.toString() } public var visited: Bool { get { return _visited } set { _visited = newValue } } }
mit
cc55731e214d7624982cf68e9f75d75b
29.067416
135
0.588067
4.227488
false
false
false
false