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
PFei-He/Project-Swift
Project/BaseFramework/ViewModel/BaseViewController.swift
1
8259
// // BaseViewController.swift // Project // // Created by PFei_He on 16/5/10. // Copyright © 2016年 PFei_He. All rights reserved. // // __________ __________ _________ ___________ ___________ __________ ___________ // | _______ \ | _______ \ / _______ \ |______ __|| _________| / _________||____ ____| // | | \ || | \ || / \ | | | | | | / | | // | |_______/ || |_______/ || | | | | | | |_________ | | | | // | ________/ | _____ _/ | | | | _ | | | _________|| | | | // | | | | \ \ | | | || | | | | | | | | | // | | | | \ \ | \_______/ || \____/ | | |_________ | \_________ | | // |_| |_| \_\ \_________/ \______/ |___________| \__________| |_| // // // The framework design by https://github.com/PFei-He/Project-Swift // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ***** 基础视图控制器 ***** // import UIKit import PFKitSwift import SVProgressHUD ///调试模式 private var DEBUG_MODE = false public class BaseViewController: UIViewController { ///请求成功返回的结果 public var successResult: AnyObject? { return _successResult } private var _successResult: AnyObject? ///请求失败返回的结果 public var failureResult: AnyObject? { return _failureResult } private var _failureResult: AnyObject? ///请求返回的附加结果 public var additionalResults: AnyObject? { return _additionalResults } private var _additionalResults: AnyObject? ///请求的发送者 public var sender: AnyObject? { return _sender } private var _sender: AnyObject? ///请求是否成功 public var requestIsSuccess: Bool { return _requestIsSuccess } private var _requestIsSuccess = Bool() ///所有的请求 private var requests = Array<BaseRequest>() //MARK: - Life Cycle deinit { removeAllRequests() } // MARK: - Request Management /** 初始化请求 - Note: 无 - Parameter requests: 所有的请求 - Returns: 无 */ public func addRequests(requests: Array<BaseRequest>) { self.requests = requests for request in requests { request.add(self) } } /** 移除请求 - Note: 无 - Parameter requests: 所有的请求 - Returns: 无 */ // public func removeRequests(requests: Array<BaseRequest>) { // for request in requests { // request.removeRequester(self) // } // } ///移除请求 private func removeAllRequests() { for request in self.requests { request.remove(self) } } // MARK: - Notification Management //请求开始通知 final func requestStartedNotification(notification: NSNotification) { if DEBUG_MODE {//调试模式 print("[ PROJECT ][ DEBUG ] Request started with sender: \(notification.object!).") print("[ PROJECT ][ DEBUG ] Requester: \(String(classForCoder)).") } //请求开始 requestStarted() } //请求结束通知 final func requestEndedNotification(notification: NSNotification) { if DEBUG_MODE {//调试模式 print("[ PROJECT ][ DEBUG ] Request ended with sender: \(notification.object!).") } //请求结束 requestEnded() } //请求成功通知 final func requestSuccessNotification(notification: NSNotification) { if DEBUG_MODE {//调试模式 print("[ PROJECT ][ DEBUG ] Request success with result: \(notification.object!).") } //处理请求结果 _successResult = notification.object if notification.userInfo is Dictionary<String, AnyObject> { var dictionary: Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String, AnyObject> _additionalResults = dictionary.removeValueForKey("sender") } _sender = notification.userInfo?["sender"] _requestIsSuccess = true //请求成功 requestSuccess() } //请求失败通知 final func requestFailureNotification(notification: NSNotification) { if DEBUG_MODE {//调试模式 print("[ PROJECT ][ DEBUG ] Request failure with result: \(notification.object!).") } //处理请求结果 _failureResult = notification.object if notification.userInfo is Dictionary<String, AnyObject> { var dictionary: Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String, AnyObject> _additionalResults = dictionary.removeValueForKey("sender") } _sender = notification.userInfo?["sender"] _requestIsSuccess = false //请求失败 requestFailure() } // MARK: - Public Methods /** 请求开始 - Note: 此方法已实现提示框的处理,如需自定义,请自行重写此方法 - Parameter 无 - Returns: 无 */ public func requestStarted() { //显示提示框 SVProgressHUD.showWithStatus("加载中") } /** 请求结束 - Note: 此方法已实现提示框的处理,如需自定义,请自行重写此方法 - Parameter 无 - Returns: 无 */ public func requestEnded() { if _requestIsSuccess {//请求成功 //移除提示框 SVProgressHUD.dismiss() } else {//请求失败 //显示请求失败的提示框 SVProgressHUD.showErrorWithStatus("请求失败") } } /** 请求成功 - Note: 无 - Parameter 无 - Returns: 无 */ public func requestSuccess() { // Override this method to process the request when request success. } /** 请求失败 - Note: 无 - Parameter 无 - Returns: 无 */ public func requestFailure() { // Override this method to process the request when request failure. } /** 调试模式 - Note: 无 - Parameter openOrNot: 是否打开调试模式 - Returns: 无 */ public class func debugMode(openOrNot: Bool) { DEBUG_MODE = openOrNot } } extension UIViewController { /** 弹出视图控制器 - Note: 无 - Parameter 视图控制器名称 - Returns: 无 */ public func presentViewController(viewControllerToPresent: UIViewController) { presentViewController(viewControllerToPresent, animated: true, completion: nil) } /** 回收视图控制器 - Note: 无 - Parameter 无 - Returns: 无 */ public func dismissViewController() { dismissViewControllerAnimated(true, completion: nil) } }
mit
411b3c613bb556b06d30be40df1f8c1b
27.85283
115
0.541329
4.422209
false
false
false
false
ngocphu2810/XLForm
Examples/Swift/SwiftExample/CustomSelectors/XLFormRowViewController/MapViewController.swift
31
3933
// // MapViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import MapKit class MapAnnotation : NSObject, MKAnnotation { @objc var coordinate : CLLocationCoordinate2D override init() { self.coordinate = CLLocationCoordinate2D(latitude: -33.0, longitude: -56.0) super.init() } } @objc(MapViewController) class MapViewController : UIViewController, XLFormRowDescriptorViewController, MKMapViewDelegate { var rowDescriptor: XLFormRowDescriptor? lazy var mapView : MKMapView = { let mapView = MKMapView(frame: self.view.frame) mapView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth return mapView }() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.addSubview(self.mapView) self.mapView.delegate = self if let rowDesc = self.rowDescriptor { if rowDesc.value != nil { let coordinate = (self.rowDescriptor!.value as! CLLocation).coordinate self.mapView.setCenterCoordinate(coordinate, animated: false) self.title = String(format: "%0.4f, %0.4f", self.mapView.centerCoordinate.latitude, self.mapView.centerCoordinate.longitude) let annotation = MapAnnotation() annotation.coordinate = coordinate self.mapView.addAnnotation(annotation) } } } //MARK - - MKMapViewDelegate func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotation") pinAnnotationView.pinColor = MKPinAnnotationColor.Red pinAnnotationView.draggable = true pinAnnotationView.animatesDrop = true return pinAnnotationView } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { if (newState == MKAnnotationViewDragState.Ending){ self.rowDescriptor!.value = CLLocation(latitude:view.annotation.coordinate.latitude, longitude:view.annotation.coordinate.longitude) self.title = String(format: "%0.4f, %0.4f", view.annotation.coordinate.latitude, view.annotation.coordinate.longitude) } } }
mit
d63375dbc24cfc3fabf0ed72a2ff739a
38.33
185
0.705568
5.022989
false
false
false
false
practicalswift/swift
test/SILGen/objc_enum.swift
25
2172
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s > %t.out // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize %s < %t.out // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.out // REQUIRES: objc_interop import gizmo // CHECK-DAG: sil shared [serializable] [ossa] @$sSo16NSRuncingOptionsV{{[_0-9a-zA-Z]*}}fC // CHECK-DAG: sil shared [serializable] [ossa] @$sSo16NSRuncingOptionsV8rawValueSivg // Non-payload enum ctors don't need to be instantiated at all. // NEGATIVE-NOT: sil shared [transparent] [ossa] @$sSo16NSRuncingOptionsV5MinceAbBmF // NEGATIVE-NOT: sil shared [transparent] [ossa] @$sSo16NSRuncingOptionsV12QuinceSlicedAbBmF // NEGATIVE-NOT: sil shared [transparent] [ossa] @$sSo16NSRuncingOptionsV15QuinceJuliennedAbBmF // NEGATIVE-NOT: sil shared [transparent] [ossa] @$sSo16NSRuncingOptionsV11QuinceDicedAbBmF var runcing: NSRuncingOptions = .mince var raw = runcing.rawValue var eq = runcing == .quinceSliced var hash = runcing.hashValue func testEm<E: Equatable>(_ x: E, _ y: E) {} func hashEm<H: Hashable>(_ x: H) {} func rawEm<R: RawRepresentable>(_ x: R) {} testEm(NSRuncingOptions.mince, .quinceSliced) hashEm(NSRuncingOptions.mince) rawEm(NSRuncingOptions.mince) rawEm(NSFungingMask.asset) protocol Bub {} extension NSRuncingOptions: Bub {} // CHECK-32-DAG: integer_literal $Builtin.IntLiteral, -2147483648 // CHECK-64-DAG: integer_literal $Builtin.IntLiteral, 2147483648 _ = NSFungingMask.toTheMax // CHECK-DAG: sil_witness_table shared [serialized] NSRuncingOptions: RawRepresentable module gizmo // CHECK-DAG: sil_witness_table shared [serialized] NSRuncingOptions: Equatable module gizmo // CHECK-DAG: sil_witness_table shared [serialized] NSRuncingOptions: Hashable module gizmo // CHECK-DAG: sil_witness_table shared [serialized] NSFungingMask: RawRepresentable module gizmo // CHECK-DAG: sil shared [transparent] [serialized] [thunk] [ossa] @$sSo16NSRuncingOptionsVSYSCSY8rawValuexSg03RawD0Qz_tcfCTW // Extension conformances get linkage according to the protocol's accessibility, as normal. // CHECK-DAG: sil_witness_table hidden NSRuncingOptions: Bub module objc_enum
apache-2.0
ecf4d6ba54b3b1b2d0e327b062b6d64f
41.588235
125
0.767956
3.388456
false
false
false
false
nielstj/GLChat
GLChat/Views/Layout/TimestampLayout.swift
1
2321
// // TimestampLayout.swift // GLChat // // Created by Daniel on 21/8/17. // Copyright © 2017 Holmusk. All rights reserved. // import CoreGraphics public struct TimestampLayout<Child: Layout>: Layout where Child.Content == UIView { public typealias Content = Child.Content var child: Child var timestamp: UILabel var alignment: NSTextAlignment var font: UIFont fileprivate init(child: Child, date: Date, alignment: NSTextAlignment = .left, font: UIFont = UIFont.systemFont(ofSize: 12)) { self.child = child self.timestamp = UILabel() self.alignment = alignment self.font = font timestamp.text = date.toShortTimeString() timestamp.textColor = UIColor.lightGray timestamp.font = font timestamp.textAlignment = alignment } mutating public func layout(in rect: CGRect) { let crect = childRect(in: rect) let fontPadding = font.pointSize + 8.0 child.layout(in: crect) timestamp.layout(in: CGRect(x: 8.0, y: rect.size.height - fontPadding, width: rect.width - 16.0, height: fontPadding)) } private func childRect(in rect: CGRect) -> CGRect { var cw: CGFloat = rect.width if let c = child.contents.first as? BubbleLabel { cw = min(cw, c.bounds.width) } var newRect = CGRect(x: 0, y: 0, width: cw, height: rect.height - 20) if alignment == .right { newRect = CGRect(x: rect.width - cw, y: 0, width: cw, height: rect.height - 20) } return newRect } public var contents: [Child.Content] { let contents = child.contents + timestamp.contents return contents.flatMap({$0}) } } public extension Layout where Content == UIView { public func withDate(_ date: Date, alignment: NSTextAlignment = .left, font: UIFont = UIFont.systemFont(ofSize: 12.0)) -> TimestampLayout<Self> { return TimestampLayout(child: self, date: date, alignment: alignment) } }
mit
7096d91cd2341e4caf84e3f827919105
31.676056
84
0.553017
4.54902
false
false
false
false
CM-Studio/NotLonely-iOS
NotLonely-iOS/ViewController/Login/LoginViewController.swift
1
3290
// // LoginViewController.swift // NotLonely-iOS // // Created by plusub on 4/1/16. // Copyright © 2016 cm. All rights reserved. // import UIKit class LoginViewController: BaseViewController { @IBOutlet weak var usernameTextField: InputTextField! { didSet { usernameTextField.setLeftImage("ic_user") usernameTextField.setlineColor(UIColor.whiteColor()) } } @IBOutlet weak var passwordTextField: InputTextField! { didSet { passwordTextField.setLeftImage("ic_passwd") passwordTextField.setlineColor(UIColor.whiteColor()) } } @IBOutlet weak var loginButton: UIButton! { didSet { let gradient = horizontal_gradientLayer() gradient.frame = self.loginButton.bounds loginButton.layer.insertSublayer(gradient, atIndex: 0) } } @IBOutlet weak var registerButton: UIButton! override func viewDidLoad() { super.viewDidLoad() let viewModel = LoginViewModel( input: ( usertextview: usernameTextField.rx_text.asObservable(), pwdtextview: passwordTextField.rx_text.asObservable(), buttonTaps: loginButton.rx_tap.asObservable() ), dependency: ( validation: NLValidationService.sharedValidation, API: VMNetWorkApi.sharedVMNetWorkApi ) ) viewModel.buttonEnable .subscribeNext{ [weak self] valid in self?.loginButton.enabled = valid self?.loginButton.alpha = valid ? 1.0 : 0.5 } .addDisposableTo(disposeBag) viewModel.model.subscribeNext { valid in println(Defaults[.password]) println(Defaults[.username]) println(Defaults[.nickname]) println(Defaults[.introduction]) println(Defaults[.sex]) println(Defaults[.url]) if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.startTabBar() } } .addDisposableTo(disposeBag) let tapBackground = UITapGestureRecognizer() tapBackground.rx_event .subscribeNext { [weak self] _ in self?.view.endEditing(true) } .addDisposableTo(disposeBag) view.addGestureRecognizer(tapBackground) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "RegisterViewController" { let secondViewController = segue.destinationViewController as! UINavigationController let registerVC = secondViewController.topViewController as! RegisterViewController registerVC.delegate = self } } } extension LoginViewController: RegisterDelegate { func updateTextField() { self.usernameTextField.text = Defaults[.username] self.usernameTextField.becomeFirstResponder() } }
mit
a54faabfde20e42dcd7dfce35ed9617d
30.932039
97
0.604439
5.729965
false
false
false
false
CandyTrace/CandyTrace
Always Write/Extensions/UIImage+Additions.swift
1
3684
// // UIImage+Additions.swift // Always Write // // Created by Sam Raudabaugh on 3/11/17. // Copyright © 2017 Cornell Tech. All rights reserved. // import UIKit extension UIImage { /** Resizes the image to a `newSize`. - Parameter newSize: The size to resize the image to. - Returns: A new `UIImage` that has been resized. */ public func resize(_ newSize: CGSize) -> UIImage { // start a context UIGraphicsBeginImageContextWithOptions(newSize, false, 0) // draw the image in the context self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) // get the image from the context let result = UIGraphicsGetImageFromCurrentImageContext() // end the context UIGraphicsEndImageContext() // return the new UIImage return result! } func fillCount(bitmapInfo: UInt32) -> Int { let colors = self.getColors(bitmapInfo: bitmapInfo) return colors.filter({ ($0 as! UIColor).cgColor.components! != [0.0, 0.0, 0.0, 1.0] }) .map{ colors.count(for: $0) } .reduce(0, +) } private func getColors(bitmapInfo: UInt32) -> NSCountedSet { print("\(self.size.width), \(self.size.height)") // get the ratio of width to height let ratio = self.size.width/self.size.height // calculate new r_width and r_height let r_width: CGFloat = 100 let r_height: CGFloat = r_width/ratio // resize the image to the new r_width and r_height let cgImage = self.resize(CGSize(width: r_width, height: r_height)).cgImage // get the width and height of the new image let width = cgImage?.width let height = cgImage?.height // get the colors from the image let bytesPerPixel: Int = 4 let bytesPerRow: Int = width! * bytesPerPixel let bitsPerComponent: Int = 8 // color detection let colorSpace = CGColorSpaceCreateDeviceRGB() let raw = malloc(width! * height! * bytesPerPixel) let ctx = CGContext(data: raw, width: width!, height: height!, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) let rect = CGRect(x: 0, y: 0, width: CGFloat(width!), height: CGFloat(height!)) ctx?.clear(rect) ctx?.draw(cgImage!, in: rect) let data = ctx?.data let imageColors = NSCountedSet(capacity: width! * height!) // color detection for x in 0..<width! { for y in 0..<height! { let pixel = ((width! * y) + x) * bytesPerPixel let color = UIColor( red: round(CGFloat(data!.load(fromByteOffset: pixel + 1, as: UInt8.self)) / 255 * 120) / 120, green: round(CGFloat(data!.load(fromByteOffset: pixel + 2, as: UInt8.self)) / 255 * 120) / 120, blue: round(CGFloat(data!.load(fromByteOffset: pixel + 3, as: UInt8.self)) / 255 * 120) / 120, alpha: 1 ) imageColors.add(color) } } free(raw) return imageColors } } extension UIView { func imageByRenderingView() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0) layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
e2ad1f3c99d1d5fd0965a1a7c2f88b4f
34.757282
175
0.572903
4.575155
false
false
false
false
matsuda/MuddlerKit
MuddlerKit/StringExtensions.swift
1
2540
// // StringExtensions.swift // MuddlerKit // // Created by Kosuke Matsuda on 2015/12/28. // Copyright © 2015年 Kosuke Matsuda. All rights reserved. // import Foundation // MARK: - deviceToken extension String { // http://stackoverflow.com/a/24979960 public init?(deviceToken: Data) { let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count) var tokenString = "" (0..<deviceToken.count).indices.forEach { (i) in tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } self = tokenString } } extension String: ExtensionCompatible {} extension Extension where Base == String { // https://github.com/omaralbeik/SwifterSwift/blob/master/Extensions/StringExtensions.swift // https://gist.github.com/stevenschobert/540dd33e828461916c11 public func camelCased(_ startIsUpper: Bool = false) -> String { let source = base if source.characters.contains(" ") { let first = source.substring(to: source.index(after: source.startIndex)) let camel = source.capitalized.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "") let rest = String(camel.characters.dropFirst()) return "\(startIsUpper ? first.uppercased() : first)\(rest)" } else { let first = source.lowercased().substring(to: source.index(after: source.startIndex)) let rest = String(source.characters.dropFirst()) return "\(startIsUpper ? first.uppercased() : first)\(rest)" } } public func pascalCased() -> String { return camelCased(true) } // http://uyama.coffee/wp/swift3xcode8でランダムな文字列を取得する/ public static func randomAlphanumericString(_ length: Int) -> String { let alphabet = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" let upperBound = UInt32(alphabet.characters.count) return String((0..<length).map { _ -> Character in return alphabet[alphabet.index(alphabet.startIndex, offsetBy: Int(arc4random_uniform(upperBound)))] }) } public static func repeatedString(text: String, length: UInt32, isNotEmpty: Bool = true) -> String { let random = arc4random_uniform(length) + (isNotEmpty ? 1 : 0) return (0..<random).reduce("") { (result, value) in var result = result result += text return result } } }
mit
22d4fa92a7f5d6aadd85f6c56dbb9120
37.6
123
0.642886
4.223906
false
false
false
false
huangboju/GesturePassword
GesturePassword/Classes/Views/LockInfoView.swift
1
1434
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // // 指示图 final class LockInfoView: UIView { private var itemLayers: [LockItemLayer] = [] public var itemDiameter: CGFloat = 10 { didSet { setNeedsLayout() } } convenience init() { self.init(frame: .zero) } override init(frame: CGRect) { super.init(frame: frame) for _ in 0 ..< 9 { let itemView = LockItemLayer() itemLayers.append(itemView) layer.addSublayer(itemView) } } public func showSelectedItems(_ passwordStr: String) { for char in passwordStr { itemLayers[Int("\(char)")!].turnHighlight() } } public func reset() { itemLayers.forEach { $0.reset() } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let margin = (frame.width - itemDiameter * 3) / 2 for (idx, sublayer) in itemLayers.enumerated() { let row = CGFloat(idx % 3) let col = CGFloat(idx / 3) let rectX = (itemDiameter + margin) * row let rectY = (itemDiameter + margin) * col sublayer.index = idx sublayer.side = itemDiameter sublayer.origin = CGPoint(x: rectX, y: rectY) } } }
mit
4a2faa76352a4a80a3b197c99a36b00a
24
59
0.546667
4.318182
false
false
false
false
vector-im/riot-ios
Riot/Modules/Common/Flow/ShapeView.swift
1
2839
// Copyright © 2016-2019 JABT // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: The above copyright // notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import UIKit open class ShapeView: UIView { open var shapeLayer: CAShapeLayer { return (layer as? CAShapeLayer)! } /// A sublayer which can be used to apply a gradient fill to `self`. open var gradientLayer: CAGradientLayer? { set { // Remove old gradient layer if let gradientLayer = gradientLayer { gradientLayer.removeFromSuperlayer() } // Replace old gradient with new one if let newGradientLayer = newValue { layer.addSublayer(newGradientLayer) } } get { return layer.sublayers?.first(where: { $0 is CAGradientLayer }) as? CAGradientLayer } } public func addGradient(type: CAGradientLayerType, startPoint: CGPoint, endPoint: CGPoint, stops: [(color: CGColor, location: NSNumber)]) { let gradientLayer = CAGradientLayer() gradientLayer.frame = shapeLayer.bounds self.gradientLayer = gradientLayer let mask = CAShapeLayer() mask.path = shapeLayer.path mask.fillColor = UIColor.black.cgColor mask.strokeColor = nil gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint gradientLayer.colors = stops.map { $0.color } gradientLayer.locations = stops.map { $0.location } gradientLayer.type = type gradientLayer.frame = shapeLayer.bounds gradientLayer.mask = mask } open var path: CGPath? { get { return shapeLayer.path } set { shapeLayer.path = newValue } } override open class var layerClass: AnyClass { return CAShapeLayer.self } }
apache-2.0
7c32b28b52b4a50e8b1ae1c342e8f2ea
35.857143
143
0.668076
5.076923
false
false
false
false
sigito/material-components-ios
components/ShadowLayer/examples/ShadowDragSquareExampleViewController.swift
3
3287
/* Copyright 2015-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 // This viewcontroller contains a subview that has an MDCShadowLayer. // A gesture recognizer allows the user to adjust the elevation of the // shadowed view by pressing it, and move it by dragging it. class ShadowDragSquareExampleViewController: UIViewController { @IBOutlet weak var blueView: ExampleShadowedView! // A UILongPressGestureRecognizer handles the changing of elevation // and location of the shadowedView. let longPressRecogniser = UILongPressGestureRecognizer() // We store the offset from the initial touch to the center of the // view to properly update its location when dragged. var movingViewOffset = CGPoint.zero override func viewDidLoad() { super.viewDidLoad() // MDCShadowLayer's elevation will implicitly animate when changed, so to disable that behavior // we need to disable Core Animation actions inside of a transaction: CATransaction.begin() CATransaction.setDisableActions(true) self.blueView.shadowLayer.elevation = .cardResting CATransaction.commit() longPressRecogniser.addTarget(self, action: #selector(longPressedInView)) longPressRecogniser.minimumPressDuration = 0.0 self.blueView.addGestureRecognizer(longPressRecogniser) } @objc func longPressedInView(_ sender: UILongPressGestureRecognizer) { // Elevation of the view is changed to indicate that it has been pressed or released. // view.center is changed to follow the touch events. if sender.state == .began { self.blueView.shadowLayer.elevation = .cardPickedUp let selfPoint = sender.location(in: self.view) movingViewOffset.x = selfPoint.x - self.blueView.center.x movingViewOffset.y = selfPoint.y - self.blueView.center.y } else if sender.state == .changed { let selfPoint = sender.location(in: self.view) let newCenterPoint = CGPoint(x: selfPoint.x - movingViewOffset.x, y: selfPoint.y - movingViewOffset.y) self.blueView.center = newCenterPoint } else if sender.state == .ended { self.blueView.shadowLayer.elevation = .cardResting movingViewOffset = CGPoint.zero } } // MARK: - CatalogByConvention @objc class func catalogBreadcrumbs() -> [String] { return [ "Shadow", "Shadow Layer"] } @objc class func catalogStoryboardName() -> String { return "ShadowDragSquareExample" } @objc class func catalogDescription() -> String { return "Shadow Layer implements the Material Design specifications for elevation and shadows." } @objc class func catalogIsPrimaryDemo() -> Bool { return true } @objc class func catalogIsPresentable() -> Bool { return true } }
apache-2.0
10b3ae4faf2fb8efc0a770f9ffdb9d86
33.968085
99
0.742622
4.623066
false
false
false
false
silence0201/Swift-Study
AdvancedSwift/协议/Indices/Indices - Index Invalidation.playgroundpage/Contents.swift
1
2501
/*: ### Index Invalidation Indices may become invalid when the collection is mutated. Invalidation could mean that the index remains valid but now addresses a different element or that the index is no longer a valid index for the collection and using it to access the collection will trap. This should be intuitively clear when you consider arrays. When you append an element, all existing indices remain valid. When you remove the first element, an existing index to the last element becomes invalid. Meanwhile smaller indices remain valid, but the elements they point to have changed. A dictionary index remains stable when new key-value pairs are added *until* the dictionary grows so much that it triggers a reallocation. This is because the element's location in the dictionary's storage buffer doesn't change, as elements are inserted until the buffer has to be resized, forcing all elements to be rehashed. Removing elements from a dictionary [invalidates indices](https://github.com/apple/swift/blob/master/docs/IndexInvalidation.rst). An index should be a dumb value that only stores the minimal amount of information required to describe an element's position. In particular, indices shouldn't keep a reference to their collection, if at all possible. Similarly, a collection usually can't distinguish one of its "own" indices from one that came from another collection of the same type. Again, this is trivially evident for arrays. Of course, you can use an integer index that was derived from one array to index another: */ //#-editable-code let numbers = [1,2,3,4] let squares = numbers.map { $0 * $0 } let numbersIndex = numbers.index(of: 4)! squares[numbersIndex] //#-end-editable-code /*: This also works with opaque index types, such as `String.Index`. In this example, we use one string's `startIndex` to access the first character of another string: */ //#-editable-code let hello = "Hello" let world = "World" let helloIdx = hello.startIndex world[helloIdx] //#-end-editable-code /*: However, the fact that you can do this doesn't mean it's generally a good idea. If we had used the index to subscript into an empty string, the program would've crashed because the index was out of bounds. There are legitimate use cases for sharing indices between collections, though. The biggest one is working with slices. Subsequences usually share the underlying storage with their base collection, so an index of the base collection will address the same element in the slice. */
mit
96316205f6e5023da07d739097d2ba07
40
80
0.784886
4.28988
false
false
false
false
eridbardhaj/Weather
Weather WatchKit Extension/Classes/Controllers/Main/InterfaceController.swift
1
2567
// // InterfaceController.swift // Weather WatchKit Extension // // Created by Erid Bardhaj on 5/4/15. // Copyright (c) 2015 STRV. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { //Outlets @IBOutlet weak var m_currenLocation: WKInterfaceLabel! @IBOutlet weak var m_weatherIcon: WKInterfaceImage! @IBOutlet weak var m_weatherCondition: WKInterfaceLabel! @IBOutlet weak var m_weatherTemp: WKInterfaceLabel! //Holder var wModel: Weather? override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. //Set the controller title self.setTitle("Today") } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() //Load network request to download data if wModel == nil { self.loadData() } } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } //MARK: - Setups func loadData() { //Make the call to API WeatherNetwork.getCurrentWeatherByCoordinates(DataManager.shared.m_city_lat, lng: DataManager.shared.m_city_lng, responseHandler: { (error, object) -> (Void) in //No Error just show content if error == ErrorType.None { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.wModel = object self.bindDataToViews(self.wModel!) }) } else { //Handle Error println("Error") } }) } func bindDataToViews(model: Weather) { let vModel = TodayViewModel(model: model) self.m_currenLocation.setText(vModel.m_currentLocation) self.m_weatherCondition.setText(vModel.m_weatherCondition) self.m_weatherIcon.setImage(UIImage(named: vModel.m_weatherImageName)) self.m_weatherTemp.setText(vModel.m_temp) } //MARK: - Force Touch Actions @IBAction func forceTouchRefreshContent() { //Reload data loadData() } }
mit
50dfacd930c0a3ad04179a92eee4d34a
26.602151
137
0.562914
4.955598
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/Maps/View/UIKit/MapsViewController.swift
1
3055
import UIKit class MapsViewController: UIViewController, MapsScene { // MARK: Properties @IBOutlet private weak var collectionView: UICollectionView! private var mapsController: MapsController? { didSet { collectionView.dataSource = mapsController collectionView.delegate = mapsController } } // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() delegate?.mapsSceneDidLoad() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) collectionView?.collectionViewLayout.invalidateLayout() } // MARK: MapsScene private var delegate: MapsSceneDelegate? func setDelegate(_ delegate: MapsSceneDelegate) { self.delegate = delegate } func setMapsTitle(_ title: String) { super.title = title } func bind(numberOfMaps: Int, using binder: MapsBinder) { mapsController = MapsController(numberOfMaps: numberOfMaps, binder: binder, onDidSelectItemAtIndexPath: didSelectMap) collectionView.reloadData() collectionView.collectionViewLayout.invalidateLayout() } // MARK: Private private func didSelectMap(at indexPath: IndexPath) { delegate?.simulateSceneDidSelectMap(at: indexPath.item) } private class MapsController: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private let numberOfMaps: Int private let binder: MapsBinder private let onDidSelectItemAtIndexPath: (IndexPath) -> Void init(numberOfMaps: Int, binder: MapsBinder, onDidSelectItemAtIndexPath: @escaping (IndexPath) -> Void) { self.numberOfMaps = numberOfMaps self.binder = binder self.onDidSelectItemAtIndexPath = onDidSelectItemAtIndexPath } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfMaps } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let cell = collectionView.dequeue(MapCollectionViewCell.self, for: indexPath) binder.bind(cell, at: indexPath.item) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let collectionViewWidth = collectionView.bounds.width return CGSize(width: collectionViewWidth - 28, height: 196) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { onDidSelectItemAtIndexPath(indexPath) } } }
mit
424996f6a703b9d3aaf9826d7c7a0ab4
32.944444
112
0.655319
6.061508
false
false
false
false
SwifterSwift/SwifterSwift
Examples/Examples.playground/Pages/01-SwiftStdlibExtensions.xcplaygroundpage/Contents.swift
1
2396
//: [Table of Contents](00-ToC) //: [Previous](@previous) import SwifterSwift //: ## SwiftStdlib extensions //: ### Array extensions // Remove duplicates from an array var array = ["h", "e", "l", "l", "o"] array.removeDuplicates() //: ### Dictionary extensions var dict: [String: Any] = ["id": 1, "Product-Name": "SwifterSwift"] // Check if key exists in dictionary. dict.has(key: "id") // Lowercase all keys in dictionary. dict.lowercaseAllKeys() // Create JSON Data and string from a dictionary let json = dict.jsonString(prettify: true) //: ### Int extensions // Return square root of a number √9 // Return square power of a number 5 ** 2 // Return a number plus or minus another number 5 ± 2 // Return roman numeral for a number 134.romanNumeral //: ### Random Access Collection extensions // Return all indices of specified item ["h", "e", "l", "l", "o"].indices(of: "l") //: ### String extensions // Return count of substring in string "hello world".count(of: "", caseSensitive: false) // Return string with no spaces or new lines in beginning and end "\n Hello ".trimmed // Return most common character in string "swifterSwift is making swift more swifty".mostCommonCharacter() // Returns CamelCase of string "Some variable nAme".camelCased // Check if string contains at least one letter and one number "123abc".isAlphaNumeric // Reverse string var str1 = "123abc" str1.reverse() // Return latinized string var str2 = "Hèllö Wórld!" str2.latinize() // Create random string of length String.random(ofLength: 10) // Check if string contains one or more instance of substring "Hello World!".contains("o", caseSensitive: false) // Check if string contains one or more emojis "string👨‍with😍emojis✊🏿".containEmoji // Subscript strings easily "Hello"[safe: 2] // Slice strings let str = "Hello world" str.slicing(from: 6, length: 5) // Convert string to numbers "12.12".double // Encode and decode URLs "it's easy to encode strings".urlEncoded "it's%20easy%20to%20encode%20strings".urlDecoded // Encode and decode base64 "Hello World!".base64Encoded "SGVsbG8gV29ybGQh".base64Decoded // Truncate strings with a trailing "This is a very long sentence".truncated(toLength: 14, trailing: "...") // Repeat a string n times "s" * 5 // NSString has never been easier let boldString = "this is string".bold.colored(with: .red) //: [Next](@next)
mit
fcf44f4006fdefb592ad5bbea92a8240
21.009259
71
0.71056
3.542474
false
false
false
false
eneko/JSONRequest
Playground.playground/Contents.swift
1
1257
import XCPlayground import JSONRequest /** Synchronous API */ let getResult = JSONRequest.get("http://httpbin.org/get?hello=world") if let value = getResult.data?["args"]??["hello"] as? String { print(value) // Outputs "world" } let postResult = JSONRequest.post("http://httpbin.org/post", payload: ["hello": "world"]) if let value = postResult.data?["json"]??["hello"] as? String { print(value) // Outputs "world" } /** Async */ JSONRequest.get("http://httpbin.org/get?hello=world") { result in if let value = result.data?["args"]??["hello"] as? String { print(value) // Outputs "world" } } JSONRequest.post("http://httpbin.org/post", payload: ["hello": "world"]) { result in if let value = result.data?["json"]??["hello"] as? String { print(value) // Outputs "world" } } //let request = JSONRequest() // //// async //request.get("http://httpbin.org/get", params: ["hello": "world async"]) { result in // print(result.data?["args"]??["hello"]) //} // //// sync //let result = try? request.get("http://httpbin.org/get", params: ["hello": "world sync"]) //print(result?.data?["args"]??["hello"]) // Wait for async calls to complete XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
mit
cb69e185a02a55d1772a59a964312847
23.173077
90
0.632458
3.581197
false
false
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/Picture.swift
1
964
// // Picture.swift // ReformCore // // Created by Laszlo Korte on 13.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformExpression public struct PictureIdentifier : Hashable { public let value : Int public init(_ id : Int) { self.value = id } public var hashValue : Int { return value } } public func ==(lhs: PictureIdentifier, rhs: PictureIdentifier) -> Bool { return lhs.value == rhs.value } final public class Picture { public let identifier : PictureIdentifier public var name : String public var size : (Double, Double) public let procedure : Procedure public let data : Sheet public init(identifier : PictureIdentifier, name: String, size: (Double, Double), data: Sheet, procedure : Procedure) { self.identifier = identifier self.name = name self.procedure = procedure self.size = size self.data = data } }
mit
2ecb4474b031101c52eaedcd14600760
21.952381
123
0.64486
4.242291
false
false
false
false
blitzagency/events
Events/Channels/Drivers/LocalChannelDriver.swift
1
754
// // LocalChannelDriver.swift // Events // // Created by Adam Venturella on 7/29/16. // Copyright © 2016 BLITZ. All rights reserved. // import Foundation public class LocalChannelDriver: ChannelDriver{ public var channels = [String: Channel]() public func get<Label: RawRepresentable>(_ key: Label) -> Channel where Label.RawValue == String { return get(key.rawValue) } public func get(_ key: String = "default") -> Channel{ if let channel = channels[key]{ print("Got Existing Key: '\(key)'") return channel } print("Creating new channel: '\(key)'") let channel = Channel(label: key) channels[key] = channel return channel } }
mit
6a9541dad17609d2f0bf7782a80a617f
21.147059
69
0.598938
4.206704
false
false
false
false
bksshetty/iosappium-test
autotest/appiumTest/sampleApps/UICatalogObj_Swift/Swift/UICatalog/AlertControllerViewController.swift
3
12498
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The view controller that demonstrates how to use UIAlertController. */ import UIKit class AlertControllerViewController : UITableViewController { // MARK: Properties weak var secureTextAlertAction: UIAlertAction? // A matrix of closures that should be invoked based on which table view cell is // tapped (index by section, row). var actionMap: [[(selectedIndexPath: NSIndexPath) -> Void]] { return [ // Alert style alerts. [ self.showSimpleAlert, self.showOkayCancelAlert, self.showOtherAlert, self.showTextEntryAlert, self.showSecureTextEntryAlert ], // Action sheet style alerts. [ self.showOkayCancelActionSheet, self.showOtherActionSheet ] ] } // MARK: UIAlertControllerStyleAlert Style Alerts /// Show an alert with an "Okay" button. func showSimpleAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the action. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The simple alert's cancel action occured.") } // Add the action. alertController.addAction(cancelAction) presentViewController(alertController, animated: true, completion: nil) } /// Show an alert with an "Okay" and "Cancel" button. func showOkayCancelAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertCotroller = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Okay/Cancel\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Okay/Cancel\" alert's other action occured.") } // Add the actions. alertCotroller.addAction(cancelAction) alertCotroller.addAction(otherAction) presentViewController(alertCotroller, animated: true, completion: nil) } /// Show an alert with two custom buttons. func showOtherAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitleOne = NSLocalizedString("Choice One", comment: "") let otherButtonTitleTwo = NSLocalizedString("Choice Two", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Other\" alert's cancel action occured.") } let otherButtonOneAction = UIAlertAction(title: otherButtonTitleOne, style: .Default) { action in NSLog("The \"Other\" alert's other button one action occured.") } let otherButtonTwoAction = UIAlertAction(title: otherButtonTitleTwo, style: .Default) { action in NSLog("The \"Other\" alert's other button two action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherButtonOneAction) alertController.addAction(otherButtonTwoAction) presentViewController(alertController, animated: true, completion: nil) } /// Show a text entry alert with two custom buttons. func showTextEntryAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Add the text field for text entry. alertController.addTextFieldWithConfigurationHandler { textField in // If you need to customize the text field, you can do so here. } // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Text Entry\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Text Entry\" alert's other action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) } /// Show a secure text entry alert with two custom buttons. func showSecureTextEntryAlert(_: NSIndexPath) { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Add the text field for the secure text entry. alertController.addTextFieldWithConfigurationHandler { textField in // Listen for changes to the text field's text so that we can toggle the current // action's enabled property based on whether the user has entered a sufficiently // secure entry. NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField) textField.secureTextEntry = true } // Stop listening for text change notifications on the text field. This closure will be called in the two action handlers. let removeTextFieldObserver: Void -> Void = { NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields!.first) } // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Secure Text Entry\" alert's cancel action occured.") removeTextFieldObserver() } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Secure Text Entry\" alert's other action occured.") removeTextFieldObserver() } // The text field initially has no text in the text field, so we'll disable it. otherAction.enabled = false // Hold onto the secure text alert action to toggle the enabled/disabled state when the text changed. secureTextAlertAction = otherAction // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) } // MARK: UIAlertControllerStyleActionSheet Style Alerts /// Show a dialog with an "Okay" and "Cancel" button. func showOkayCancelActionSheet(selectedIndexPath: NSIndexPath) { let cancelButtonTitle = NSLocalizedString("Cancel", comment: "OK") let destructiveButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Okay/Cancel\" alert action sheet's cancel action occured.") } let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { action in NSLog("The \"Okay/Cancel\" alert action sheet's destructive action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(destructiveAction) // Configure the alert controller's popover presentation controller if it has one. if let popoverPresentationController = alertController.popoverPresentationController { // This method expects a valid cell to display from. let selectedCell = tableView.cellForRowAtIndexPath(selectedIndexPath)! popoverPresentationController.sourceRect = selectedCell.frame popoverPresentationController.sourceView = view popoverPresentationController.permittedArrowDirections = .Up } presentViewController(alertController, animated: true, completion: nil) } /// Show a dialog with two custom buttons. func showOtherActionSheet(selectedIndexPath: NSIndexPath) { let destructiveButtonTitle = NSLocalizedString("Destructive Choice", comment: "") let otherButtonTitle = NSLocalizedString("Safe Choice", comment: "") let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) // Create the actions. let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { action in NSLog("The \"Other\" alert action sheet's destructive action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Other\" alert action sheet's other action occured.") } // Add the actions. alertController.addAction(destructiveAction) alertController.addAction(otherAction) // Configure the alert controller's popover presentation controller if it has one. if let popoverPresentationController = alertController.popoverPresentationController { // This method expects a valid cell to display from. let selectedCell = tableView.cellForRowAtIndexPath(selectedIndexPath)! popoverPresentationController.sourceRect = selectedCell.frame popoverPresentationController.sourceView = view popoverPresentationController.permittedArrowDirections = .Up } presentViewController(alertController, animated: true, completion: nil) } // MARK: UITextFieldTextDidChangeNotification func handleTextFieldTextDidChangeNotification(notification: NSNotification) { let textField = notification.object as! UITextField // Enforce a minimum length of >= 5 characters for secure text alerts. secureTextAlertAction!.enabled = count(textField.text) >= 5 } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let action = actionMap[indexPath.section][indexPath.row] action(selectedIndexPath: indexPath) tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
b92925912efdbc7f36022675c20720e3
43.94964
184
0.659171
5.899906
false
false
false
false
alblue/swift
test/Inputs/conditional_conformance_with_assoc.swift
1
17283
public func takes_p1<T: P1>(_: T.Type) {} public protocol P1 { associatedtype AT1 func normal() func generic<T: P3>(_: T) } public protocol P2 { associatedtype AT2: P3 } public protocol P3 { associatedtype AT3 } public struct Nothing {} public struct IsP2: P2 { public typealias AT2 = IsP3 } public struct IsP3: P3 { public typealias AT3 = Nothing } public struct IsAlsoP2: P2 { public typealias AT2 = IsBoth } public struct IsBoth: P2, P3 { public typealias AT2 = HoldsP3 public typealias AT3 = Nothing } public struct HoldsP3: P3 { public typealias AT3 = IsP3 } public struct Double<B: P2, C> {} extension Double: P1 where B.AT2: P2, C: P3, B.AT2.AT2.AT3: P3 { public typealias AT1 = C public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Double.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s34conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlAaEP6normalyyFTW"(%T34conditional_conformance_with_assoc6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[C_P3:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_1.P3" = bitcast i8* [[C_P3]] to i8** // CHECK-NEXT: [[B_AT2_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[B_AT2_P2:%.*]] = load i8*, i8** [[B_AT2_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.AT2.P2" = bitcast i8* [[B_AT2_P2]] to i8** // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -3 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3:%.*]] = load i8*, i8** [[B_AT2_AT2_AT3_P3_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.AT2.AT2.AT3.P3" = bitcast i8* [[B_AT2_AT2_AT3_P3]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_WT_ARRAY:%.*]] = bitcast %swift.type* %Self to i8*** // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[SELF_AS_WT_ARRAY]], i64 4 // CHECK-NEXT: %"\CF\84_0_0.P2" = load i8**, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s34conditional_conformance_with_assoc6DoubleVA2A2P3R_AA2P23AT2RpzAadF_AfaEP3AT3RPzrlE6normalyyF"(%swift.type* %"\CF\84_0_0", %swift.type* %"\CF\84_0_1", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_0_1.P3", i8** %"\CF\84_0_0.AT2.P2", i8** %"\CF\84_0_0.AT2.AT2.AT3.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Double.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s34conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlAaEP7genericyyqd__AaFRd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T34conditional_conformance_with_assoc6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[C_P3:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_1.P3" = bitcast i8* [[C_P3]] to i8** // CHECK-NEXT: [[B_AT2_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2 // CHECK-NEXT: [[B_AT2_P2:%.*]] = load i8*, i8** [[B_AT2_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.AT2.P2" = bitcast i8* [[B_AT2_P2]] to i8** // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -3 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3:%.*]] = load i8*, i8** [[B_AT2_AT2_AT3_P3_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.AT2.AT2.AT3.P3" = bitcast i8* [[B_AT2_AT2_AT3_P3]] to i8** // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2 // CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type** // CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3 // CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8 // CHECK-NEXT: [[SELF_AS_WT_ARRAY:%.*]] = bitcast %swift.type* %Self to i8*** // CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[SELF_AS_WT_ARRAY]], i64 4 // CHECK-NEXT: %"\CF\84_0_0.P2" = load i8**, i8*** [[B_P2_PTR]], align 8 // CHECK-NEXT: call swiftcc void @"$s34conditional_conformance_with_assoc6DoubleVA2A2P3R_AA2P23AT2RpzAadF_AfaEP3AT3RPzrlE7genericyyqd__AaDRd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_0_0", %swift.type* %"\CF\84_0_1", %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_0_1.P3", i8** %"\CF\84_1_0.P3", i8** %"\CF\84_0_0.AT2.P2", i8** %"\CF\84_0_0.AT2.AT2.AT3.P3") // CHECK-NEXT: ret void // CHECK-NEXT: } public func generic_generic<T: P2, U>(_: T.Type, _: U.Type) where T.AT2: P2, U: P3, T.AT2.AT2.AT3: P3 { takes_p1(Double<T, U>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s34conditional_conformance_with_assoc08generic_E0yyxm_q_mtAA2P2RzAA2P3R_AaC3AT2RpzAadE_AeaCP3AT3RPzr0_lF"(%swift.type*, %swift.type*, %swift.type* %T, %swift.type* %U, i8** %T.P2, i8** %U.P3, i8** %T.AT2.P2, i8** %T.AT2.AT2.AT3.P3) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [3 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s34conditional_conformance_with_assoc6DoubleVMa"(i64 0, %swift.type* %T, %swift.type* %U, i8** %T.P2) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [3 x i8**], [3 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %U.P3, i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[B_AT2_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** %T.AT2.P2, i8*** [[B_AT2_P2_PTR]], align 8 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 2 // CHECK-NEXT: store i8** %T.AT2.AT2.AT3.P3, i8*** [[B_AT2_AT2_AT3_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s34conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func generic_concrete<T: P2>(_: T.Type) where T.AT2: P2, T.AT2.AT2.AT3: P3 { takes_p1(Double<T, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s34conditional_conformance_with_assoc16generic_concreteyyxmAA2P2RzAaC3AT2RpzAA2P3AD_AdaCP3AT3RPzlF"(%swift.type*, %swift.type* %T, i8** %T.P2, i8** %T.AT2.P2, i8** %T.AT2.AT2.AT3.P3) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [3 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s34conditional_conformance_with_assoc6DoubleVMa"(i64 0, %swift.type* %T, %swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ {{.*}} }>* }>, <{ {{.*}} }>* @"$s34conditional_conformance_with_assoc4IsP3VMf", i32 0, i32 1) to %swift.type*), i8** %T.P2) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [3 x i8**], [3 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* @"$s34conditional_conformance_with_assoc4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[B_AT2_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** %T.AT2.P2, i8*** [[B_AT2_P2_PTR]], align 8 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 2 // CHECK-NEXT: store i8** %T.AT2.AT2.AT3.P3, i8*** [[B_AT2_AT2_AT3_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s34conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func concrete_generic<U>(_: U.Type) where U: P3 { takes_p1(Double<IsAlsoP2, U>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s34conditional_conformance_with_assoc16concrete_genericyyxmAA2P3RzlF"(%swift.type*, %swift.type* %U, i8** %U.P3) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [3 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s34conditional_conformance_with_assoc6DoubleVMa"(i64 0, %swift.type* bitcast (i64* getelementptr inbounds (<{ {{.*}} }>, <{ {{.*}} }>* @"$s34conditional_conformance_with_assoc8IsAlsoP2VMf", i32 0, i32 1) to %swift.type*), %swift.type* %U, i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @"$s34conditional_conformance_with_assoc8IsAlsoP2VAA0G0AAWP", i32 0, i32 0)) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [3 x i8**], [3 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %U.P3, i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[B_AT2_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @"$s34conditional_conformance_with_assoc6IsBothVAA2P2AAWP", i32 0, i32 0), i8*** [[B_AT2_P2_PTR]], align 8 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 2 // CHECK-NEXT: store i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* @"$s34conditional_conformance_with_assoc4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[B_AT2_AT2_AT3_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s34conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT:} public func concrete_concrete() { takes_p1(Double<IsAlsoP2, IsP3>.self) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s34conditional_conformance_with_assoc09concrete_E0yyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s34conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGMa"(i64 0) // CHECK-NEXT: [[X:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Z:%.*]] = call i8** @"$s34conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGACyxq_GAA2P1A2A0I0R_AA0H03AT2RpzAakM_AmaLP3AT3RPzrlWl"() // CHECK-NEXT: call swiftcc void @"$s34conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF"(%swift.type* [[X]], %swift.type* [[X]], i8** [[Z]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete Double<IsAlsoP2, IsP3> : P1. // CHECK-LABEL: define linkonce_odr hidden i8** @"$s34conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGACyxq_GAA2P1A2A0I0R_AA0H03AT2RpzAakM_AmaLP3AT3RPzrlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [3 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s34conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGACyxq_GAA2P1A2A0I0R_AA0H03AT2RpzAakM_AmaLP3AT3RPzrlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s34conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGMa"(i64 0) // CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [3 x i8**], [3 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* @"$s34conditional_conformance_with_assoc4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8 // CHECK-NEXT: [[B_AT2_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1 // CHECK-NEXT: store i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @"$s34conditional_conformance_with_assoc6IsBothVAA2P2AAWP", i32 0, i32 0), i8*** [[B_AT2_P2_PTR]], align 8 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 2 // CHECK-NEXT: store i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* @"$s34conditional_conformance_with_assoc4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[B_AT2_AT2_AT3_P3_PTR]], align 8 // CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: store atomic i8** [[Double_P1]], i8*** @"$s34conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGACyxq_GAA2P1A2A0I0R_AA0H03AT2RpzAakM_AmaLP3AT3RPzrlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Double_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } // witness table instantiator for Double : P1 // CHECK-LABEL: define internal void @"$s34conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlWI"(i8**, %swift.type* %"Double<B, C>", i8**) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLES:%.*]] = bitcast i8** %1 to i8*** // CHECK-NEXT: [[C_P3_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0 // CHECK-NEXT: [[C_P3_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1 // CHECK-NEXT: [[C_P3:%.*]] = load i8**, i8*** [[C_P3_SRC]], align 8 // CHECK-NEXT: [[CAST_C_P3_DEST:%.*]] = bitcast i8** [[C_P3_DEST]] to i8*** // CHECK-NEXT: store i8** [[C_P3]], i8*** [[CAST_C_P3_DEST]], align 8 // CHECK-NEXT: [[B_AT2_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 1 // CHECK-NEXT: [[B_AT2_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -2 // CHECK-NEXT: [[B_AT2_P2:%.*]] = load i8**, i8*** [[B_AT2_P2_SRC]], align 8 // CHECK-NEXT: [[CAST_B_AT2_P2_DEST:%.*]] = bitcast i8** [[B_AT2_P2_DEST]] to i8*** // CHECK-NEXT: store i8** [[B_AT2_P2]], i8*** [[CAST_B_AT2_P2_DEST]], align 8 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 2 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -3 // CHECK-NEXT: [[B_AT2_AT2_AT3_P3:%.*]] = load i8**, i8*** [[B_AT2_AT2_AT3_P3_SRC]], align 8 // CHECK-NEXT: [[CAST_B_AT2_AT2_AT3_P3_DEST:%.*]] = bitcast i8** [[B_AT2_AT2_AT3_P3_DEST]] to i8*** // CHECK-NEXT: store i8** [[B_AT2_AT2_AT3_P3]], i8*** [[CAST_B_AT2_AT2_AT3_P3_DEST]], align 8 // CHECK-NEXT: ret void // CHECK-NEXT: } protocol Base { } protocol Sub : Base { associatedtype S : Base } struct X<T> { } extension X: Base where T: Base { } extension X: Sub where T: Sub, T.S == T { typealias S = X<T> } // Make sure we can recover the type metadata from X<T>.Type. // CHECK: define internal void @"$s34conditional_conformance_with_assoc1XVyxGAA3SubA2aERz1SQzRszlWI"(i8**, %swift.type* %"X<T>", i8**) // CHECK: entry: // CHECK: [[XT_TYPE:%.*]] = bitcast %swift.type* %"X<T>" to %swift.type** // CHECK: [[ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[XT_TYPE]], i64 2 // CHECK: [[T:%.*]] = load %swift.type*, %swift.type** [[ADDR]] // CHECK: %T.Base = call swiftcc i8** {{.*}}(%swift.type* %T, %swift.type* %T, i8** {{.*}}) // CHECK: ret void // CHECK: }
apache-2.0
1d860337f95d97d4b41a5a304c58f028
62.307692
436
0.636059
2.673318
false
false
false
false
evgenyneu/walk-to-circle-ios
walk to circle/ViewControllers/MapViewController.swift
1
2370
import UIKit import MapKit import QuartzCore class MapViewController: UIViewController, MKMapViewDelegate, iiOutputViewController, YiiButtonsDelegate, YiiMapDelegate, CountdownDelegate { @IBOutlet weak var outputLabel: UILabel! @IBOutlet var yiiButtons: YiiButtons! @IBOutlet var yiiMap: YiiMap! let countdown = Countdown() override func viewDidLoad() { super.viewDidLoad() yiiMap.viewDidLoad() yiiMap.delegate = self yiiButtons.viewDidLoad() yiiButtons.delegate = self countdown.delegate = self showPreviousPin() // Preload pin drop sounds to make it play without delay and in sync with animation iiSounds.shared.prepareToPlay(iiSoundType.fall) iiSounds.shared.prepareToPlay(iiSoundType.pin_drop) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.Default } private func showPreviousPin() { if let previousCoordinate = WalkCoordinate.previous { yiiMap.showPreviousPin(previousCoordinate) } } } // ButtonsDelgate // ------------------------------ typealias YiiButtonsDelegateImplementation = MapViewController extension YiiButtonsDelegateImplementation { func yiiButtonsDelegate_start() { countdown.start() let newCoordinate = yiiMap.dropNewPin() iiQ.main { // Defer saving new coordinate because it can slow down UI WalkCoordinate.current = newCoordinate WalkCircleMonitor.start() } } } // MapDelgate // ------------------------------ typealias YiiMapDelegateImplementation = MapViewController extension YiiMapDelegateImplementation { func yiiMapDelegate_mapIsReady() { yiiButtons.showStartButton() } var yiiMapDelegate_startButton: UIView? { return yiiButtons.startButton } } // CountdownDelegate // ------------------------------ typealias CountdownDelegateImplementation = MapViewController extension CountdownDelegateImplementation { func contdownDelegate_tick(value: Int, firstTick: Bool) { yiiButtons.rewindButton.updateText(String(value)) if !firstTick { iiSounds.shared.play(iiSoundType.click_sound, atVolume: 0.2) } } func contdownDelegate_didFinish() { iiSounds.shared.play(iiSoundType.large_door, atVolume: 0.15) iiQ.runAfterDelay(0.01) { // Show zero before view transition WalkViewControllers.Walk.show() } } }
mit
a3d57a3d3d7902fd277c2536f02d95b9
22.465347
87
0.714346
4.429907
false
false
false
false
AimobierCocoaPods/OddityUI
Classes/DetailAndCommitViewController/CommitViewController/Extension/CommExtension.swift
1
2321
// // CommitViewControllerExtension.swift // Journalism // // Created by Mister on 16/6/1. // Copyright © 2016年 aimobier. All rights reserved. // import UIKit import MJRefresh import RealmSwift extension CommitViewController{ // 设置数据源对象 func setResults(){ if let new = new { let realm = try! Realm() hotResults = realm.objects(Comment.self).filter("nid = \(new.nid) AND ishot = 1").sorted(byProperty: "commend", ascending: false) normalResults = realm.objects(Comment.self).filter("nid = \(new.nid) AND ishot = 0").sorted(byProperty: "ctimes", ascending: false) } self.tableView.reloadData() } // 设置表头视图 func setHeaderView(){ if let n = new { self.newTitleLabel.text = n.title self.newTitleLabel.font = UIFont.a_font9 self.newInfoLabel.font = UIFont.a_font8 let comment = n.comment > 0 ? " \(n.comment)评" : "" self.newInfoLabel.text = "\(n.pname) \(n.ptime)\(comment)" tableViewHeaderView.setNeedsLayout() tableViewHeaderView.layoutIfNeeded() let tsize = CGSize(width: self.view.frame.width-18-18, height: 1000) // 获得标题最宽的宽度 let titleHeight = NSString(string:self.newTitleLabel.text!).boundingRect(with: tsize, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:self.newTitleLabel.font], context: nil).height // 获得标题所需高度 let infoHeight = NSString(string:self.newInfoLabel.text!).boundingRect(with: tsize, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:self.newInfoLabel.font], context: nil).height // 获得info所需高度 tableViewHeaderView.frame.size.height = titleHeight+infoHeight+17+33+8 tableView.tableHeaderView = self.tableViewHeaderView } } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { (_) in self.setHeaderView() }, completion: nil ) } }
mit
12824c8783634a44660970ca91604032
35.786885
223
0.611408
4.515091
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Profile/Controller/GameCenterViewController.swift
1
3647
// // GameCenterViewController.swift // MGDYZB // // Created by i-Techsys.com on 17/2/27. // Copyright © 2017年 ming. All rights reserved. // http://capi.douyucdn.cn/api/app_api/get_app_list?devid=EF79C6C6-AB14-4A3C-830B-A55728C89073&sign=d1ca2dcf1a1521515ce4d201db20b12f&time=1488155520&type=ios import UIKit private let KGameCenterCellID = "KGameCenterCellID" class GameCenterViewController: BaseViewController { fileprivate lazy var gameCenterVM = GameCenterViewModel() fileprivate lazy var collectionView: UICollectionView = { [weak self] in let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: MGScreenW, height: 95) flowLayout.minimumLineSpacing = MGGloabalMargin*0.3 flowLayout.minimumInteritemSpacing = MGGloabalMargin flowLayout.sectionInset = UIEdgeInsets(top: MGGloabalMargin, left: MGGloabalMargin*0.8, bottom: 0, right: 0) let cv = UICollectionView(frame: self!.view.bounds, collectionViewLayout: flowLayout) cv.backgroundColor = UIColor(white: 0.95, alpha: 1) cv.autoresizingMask = [.flexibleWidth, .flexibleHeight] cv.dataSource = self cv.delegate = self cv.register(GameCenterCell.self, forCellWithReuseIdentifier: KGameCenterCellID) return cv }() override func viewDidLoad() { super.viewDidLoad() self.title = "游戏中心" loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - UI extension GameCenterViewController { override func setUpMainView() { contentView = collectionView view.addSubview(collectionView) super.setUpMainView() } } // MARK: - 数据 extension GameCenterViewController { fileprivate func loadData() { gameCenterVM.loadGameCenterData { (err) in if err == nil { self.collectionView.reloadData() }else { debugPrint(err) } self.loadDataFinished() } } fileprivate func setUpRefresh() { // MARK: - 下拉 self.collectionView.header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in self!.gameCenterVM.gameCenterMmodels.removeAll() self?.loadData() self!.collectionView.header.endRefreshing() self?.collectionView.footer.endRefreshing() }) self.collectionView.header.isAutoChangeAlpha = true self.collectionView.header.beginRefreshing() } } // MARK: - UICollectionViewDataSource extension GameCenterViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameCenterVM.gameCenterMmodels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KGameCenterCellID, for: indexPath) as! GameCenterCell cell.model = gameCenterVM.gameCenterMmodels[indexPath.item] return cell } } // MARK: - UICollectionViewDelegate extension GameCenterViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let model = gameCenterVM.gameCenterMmodels[indexPath.item] if UIApplication.shared.canOpenURL(URL(string: model.down_ios_url)!) { UIApplication.shared.openURL(URL(string: model.down_ios_url)!) } } }
mit
c3645c811720f0cc55807ee5d1cf2afc
35.646465
159
0.690187
4.705577
false
false
false
false
dbettermann/DBAlertController
Source/DBAlertController.swift
1
1802
// // DBAlertController.swift // DBAlertController // // Created by Dylan Bettermann on 5/11/15. // Copyright (c) 2015 Dylan Bettermann. All rights reserved. // import UIKit public class DBAlertController: UIAlertController { /// The UIWindow that will be at the top of the window hierarchy. The DBAlertController instance is presented on the rootViewController of this window. private lazy var alertWindow: UIWindow = { let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.rootViewController = DBClearViewController() window.backgroundColor = UIColor.clearColor() window.windowLevel = UIWindowLevelAlert return window }() /** Present the DBAlertController on top of the visible UIViewController. - parameter flag: Pass true to animate the presentation; otherwise, pass false. The presentation is animated by default. - parameter completion: The closure to execute after the presentation finishes. */ public func show(animated flag: Bool = true, completion: (() -> Void)? = nil) { if let rootViewController = alertWindow.rootViewController { alertWindow.makeKeyAndVisible() rootViewController.presentViewController(self, animated: flag, completion: completion) } } } // In the case of view controller-based status bar style, make sure we use the same style for our view controller private class DBClearViewController: UIViewController { private override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIApplication.sharedApplication().statusBarStyle } private override func prefersStatusBarHidden() -> Bool { return UIApplication.sharedApplication().statusBarHidden } }
mit
36bc1fd57b82b8cb79843de09df8d5ea
35.77551
155
0.707547
5.460606
false
false
false
false
AlexRamey/mbird-iOS
iOS Client/PodcastsController/PodcastInfoTableViewCell.swift
1
855
// // PodcastInfoTableViewCell.swift // iOS Client // // Created by Jonathan Witten on 8/4/18. // Copyright © 2018 Mockingbird. All rights reserved. // import UIKit class PodcastInfoTableViewCell: UITableViewCell { @IBOutlet weak var podcastName: UILabel! @IBOutlet weak var podcastImage: UIImageView! @IBOutlet weak var titleLabel: UILabel! override func awakeFromNib() { self.titleLabel.font = UIFont(name: "IowanOldStyle-Roman", size: 18) self.podcastName.font = UIFont(name: "IowanOldStyle-Roman", size: 14) self.podcastName.textColor = UIColor.gray self.selectionStyle = .none } func configure(image: UIImage, name: String, description: String) { self.titleLabel.text = description self.podcastImage.image = image self.podcastName.text = name } }
mit
efba561939f95b2d864dedb7f5c10bbb
27.466667
77
0.681499
4.27
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Services/WordPressComSyncService.swift
1
2981
import Foundation import WordPressKit /// WordPressComSyncService encapsulates all of the logic related to Logging into a WordPress.com account, and syncing the /// User's blogs. /// class WordPressComSyncService { /// Syncs account and blog information for the authenticated wpcom user. /// /// - Parameters: /// - authToken: The authentication token. /// - isJetpackLogin: Indicates if this is a Jetpack Site. /// - onSuccess: Closure to be executed upon success. /// - onFailure: Closure to be executed upon failure. /// func syncWPCom(authToken: String, isJetpackLogin: Bool, onSuccess: @escaping (WPAccount) -> Void, onFailure: @escaping (Error) -> Void) { let context = ContextManager.sharedInstance().mainContext let accountService = AccountService(managedObjectContext: context) accountService.createOrUpdateAccount(withAuthToken: authToken, success: { account in self.syncOrAssociateBlogs(account: account, isJetpackLogin: isJetpackLogin, onSuccess: onSuccess, onFailure: onFailure) }, failure: { error in onFailure(error) }) } /// Syncs or associates blogs for the specified account. /// /// - Parameters: /// - account: The WPAccount for which to sync/associate blogs. /// - isJetpackLogin: Whether a Jetpack connected account is being logged into. /// - onSuccess: Success block /// - onFailure: Failure block /// func syncOrAssociateBlogs(account: WPAccount, isJetpackLogin: Bool, onSuccess: @escaping (WPAccount) -> Void, onFailure: @escaping (Error) -> Void) { let context = ContextManager.sharedInstance().mainContext let accountService = AccountService(managedObjectContext: context) let onFailureInternal = { (error: Error) in /// At this point the user is authed and there is a valid account in core data. Make a note of the error and just dismiss /// the vc. There might be some wonkiness due to missing data (blogs, account info) but this will eventually resync. /// DDLogError("Error while syncing wpcom account and/or blog details after authenticating. \(String(describing: error))") onFailure(error) } let onSuccessInternal = { onSuccess(account) } if isJetpackLogin && !account.isDefaultWordPressComAccount { let blogService = BlogService(managedObjectContext: context) blogService.associateSyncedBlogs(toJetpackAccount: account, success: onSuccessInternal, failure: onFailureInternal) } else { if !account.isDefaultWordPressComAccount { accountService.removeDefaultWordPressComAccount() } accountService.setDefaultWordPressComAccount(account) BlogSyncFacade().syncBlogs(for: account, success: onSuccessInternal, failure: onFailureInternal) } } }
gpl-2.0
18a89fc989b2c6be992d36cf75a157fa
44.861538
153
0.674941
5.130809
false
false
false
false
Hovo-Infinity/radio
Radio/LocationManagerHandler.swift
1
2144
// // LocationManagerHandler.swift // Radio // // Created by Hovhannes Stepanyan on 8/1/17. // Copyright © 2017 Hovhannes Stepanyan. All rights reserved. // import UIKit import CoreLocation class LocationManagerHandler: NSObject, CLLocationManagerDelegate { let manager:CLLocationManager; let geocoder:CLGeocoder; var countryCode:String; private override init() { manager = CLLocationManager(); geocoder = CLGeocoder(); countryCode = Locale.current.regionCode ?? "am"; super.init(); manager.requestWhenInUseAuthorization(); if CLLocationManager.locationServicesEnabled() { manager.delegate = self; manager.startMonitoringSignificantLocationChanges(); manager.startUpdatingLocation(); } } private static let _sharedManager = LocationManagerHandler(); class func sharedManager() -> LocationManagerHandler { return _sharedManager; } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { [unowned self](action) in self.countryCode = Locale.current.regionCode!; }; let alert = UIAlertController(title: "", message: "Can Not Take Location, region will be change to (Locale.current.countryCode!)", preferredStyle: UIAlertControllerStyle.alert); alert.addAction(ok); UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil); } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first else { return; }; geocoder.reverseGeocodeLocation(location) { [unowned self](placemarks, error) in guard let currentLocPlacemark = placemarks?.first else { return }; self.countryCode = currentLocPlacemark.isoCountryCode ?? Locale.current.regionCode!; } } func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) { } }
gpl-3.0
781a277dfdad30b09666a0ce1a1003d2
39.433962
185
0.685954
5.3575
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Home/Home.swift
2
5679
// // Home.swift // Neocom // // Created by Artem Shimanski on 19.11.2019. // Copyright © 2019 Artem Shimanski. All rights reserved. // import SwiftUI import EVEAPI import Alamofire struct Home: View { private enum HeaderFrame {} @Environment(\.managedObjectContext) private var managedObjectContext @Environment(\.self) private var environment @EnvironmentObject private var sharedState: SharedState @State private var isAccountsPresented = false @State private var navigationAvatarItemVisible = false // @UserDefault(key: .activeAccountID) private var accountID: String? = nil private let headerContent = HomeHeader() private let serverStatus = ServerStatus() private let characterSheet = CharacterSheetItem() private let jumpClones = JumpClonesItem() private let skills = SkillsItem() private let wealth = WealthMenuItem() private var header: some View { Button(action: { self.isAccountsPresented = true }) { VStack(alignment: .leading, spacing: 0) { headerContent serverStatus.padding(4) }.contentShape(Rectangle()) }.buttonStyle(PlainButtonStyle()) } private var navigationAvatarItem: some View { Group { if navigationAvatarItemVisible { Button(action: { self.isAccountsPresented = true }) { if sharedState.account != nil { Avatar(characterID: sharedState.account!.characterID, size: .size256).frame(width: 36, height: 36) .animation(.linear) } else { Avatar(image: nil) .frame(width: 36, height: 36) .overlay(Image(systemName: "person").resizable().padding(10)) .foregroundColor(.secondary) .animation(.linear) } }.buttonStyle(PlainButtonStyle()) } } } var body: some View { // GeometryReader { geometry in List { self.header.framePreference(in: .global, HeaderFrame.self) if sharedState.account != nil { Section(header: Text("CHARACTER")) { self.characterSheet self.jumpClones self.skills MailItem() CalendarItem() self.wealth LoyaltyPointsItem() } } Section(header: Text("DATABASE")) { DatabaseItem() CertificatesItem() MarketItem() NPCItem() WormholesItem() IncursionsItem() } if sharedState.account != nil { Section(header: Text("BUSINESS")) { AssetsItem() MarketOrdersItem() ContractsItem() WalletTransactionsItem() WalletJournalItem() IndustryJobsItem() PlanetariesItem() } } Section(header: Text("KILLBOARD")) { RecentKillsItem() ZKillboardItem() } Section(header: Text("FITTING")) { FittingItem() } Section { SettingsItem() AboutItem() #if !targetEnvironment(macCatalyst) RemoveAdsItem() #endif } }.listStyle(GroupedListStyle()) // } .sheet(isPresented: $isAccountsPresented) { NavigationView { Accounts { account in if self.sharedState.account != account { self.sharedState.account = account } // if self.accountID != account.uuid { // self.accountID = account.uuid // } self.isAccountsPresented = false } .navigationBarItems(leading: BarButtonItems.close { self.isAccountsPresented = false }, trailing: EditButton()) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } // .navigationBarTitle(Text("Neocom")) // .navigationBarHidden(true) .navigationBarTitle(sharedState.account?.characterName ?? "Neocom") .navigationBarItems(leading: navigationAvatarItem, trailing: sharedState.account != nil ? Button(NSLocalizedString("Logout", comment: "")) {self.sharedState.account = nil} : nil) .onFrameChange(HeaderFrame.self) { frame in self.navigationAvatarItemVisible = (frame.first?.minY ?? -100) < -35 } } } #if DEBUG struct Home_Previews: PreviewProvider { static var previews: some View { NavigationView { Home() } .modifier(ServicesViewModifier.testModifier()) // x§.environment(\.locale, Locale(identifier: "ru_RU")) } } #endif
lgpl-2.1
f3d08926df170aaa39bf4627e7e84aaf
34.93038
190
0.491809
5.792857
false
false
false
false
somedev/animations-in-ios
Animations-in-iOS/Animations-in-iOS/Classes/EmitterLayerViewController.swift
1
1828
// // EmitterLayerViewController.swift // Animations-in-iOS // // Created by Eduard Panasiuk on 1/2/15. // Copyright (c) 2015 Eduard Panasiuk. All rights reserved. // import UIKit import QuartzCore class EmitterLayerViewController: UIViewController { private lazy var emitterLayer:CAEmitterLayer = { let emitterLayer = CAEmitterLayer() emitterLayer.frame = self.view.bounds emitterLayer.emitterPosition = CGPointMake(emitterLayer.bounds.size.width / 2, emitterLayer.frame.origin.y) emitterLayer.emitterZPosition = 10 emitterLayer.emitterSize = CGSizeMake(emitterLayer.bounds.size.width, 0) emitterLayer.emitterShape = kCAEmitterLayerLine emitterLayer.emitterCells = self.emitterCells() return emitterLayer }() override func viewDidLoad() { super.viewDidLoad() view.layer.addSublayer(emitterLayer) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) emitterLayer.removeFromSuperlayer() } //MARK: - Utils func emitterCellFromImageName(name:String) -> CAEmitterCell { let emitterCell = CAEmitterCell() emitterCell.scale = 0.1 emitterCell.scaleRange = 0.2 emitterCell.emissionRange = 1.2 emitterCell.lifetime = 5.0 emitterCell.birthRate = 100 emitterCell.velocity = 200 emitterCell.velocityRange = 50 emitterCell.yAcceleration = 120 emitterCell.spinRange = 4; emitterCell.contents = UIImage(named: name)?.CGImage return emitterCell } func emitterCells() -> [CAEmitterCell] { return [emitterCellFromImageName("snow"), emitterCellFromImageName("snow1"), emitterCellFromImageName("snow2")] } }
mit
16165206e313615ab84a0fedc2d53caf
31.642857
115
0.669584
5.008219
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift
5
17451
// // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension KingfisherWrapper where Base: UIButton { // MARK: Setting Image /// Sets an image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setImage(placeholder, for: state) setTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) if !options.keepCurrentImageWhileLoading { base.setImage(placeholder, for: state) } var mutatingSelf = self let issuedIdentifier = Source.Identifier.next() setTaskIdentifier(issuedIdentifier, for: state) if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } if let provider = ImageProgressiveProvider(options, refresh: { image in self.base.setImage(image, for: state) }) { options.onDataReceived = (options.onDataReceived ?? []) + [provider] } options.onDataReceived?.forEach { $0.onShouldApply = { issuedIdentifier == self.taskIdentifier(for: state) } } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.taskIdentifier(for: state) else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil mutatingSelf.setTaskIdentifier(nil, for: state) switch result { case .success(let value): self.base.setImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setImage(image, for: state) } completionHandler?(result) } } } ) mutatingSelf.imageTask = task return task } /// Sets an image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: resource.map { Source.network($0) }, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Downloading Task /// Cancels the image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelImageDownloadTask() { imageTask?.cancel() } // MARK: Setting Background Image /// Sets a background image to the button for a specified state with a source. /// /// - Parameters: /// - source: The `Source` object contains information about the image. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested source /// Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with source: Source?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { guard let source = source else { base.setBackgroundImage(placeholder, for: state) setBackgroundTaskIdentifier(nil, for: state) completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) if !options.keepCurrentImageWhileLoading { base.setBackgroundImage(placeholder, for: state) } var mutatingSelf = self let issuedIdentifier = Source.Identifier.next() setBackgroundTaskIdentifier(issuedIdentifier, for: state) if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } if let provider = ImageProgressiveProvider(options, refresh: { image in self.base.setBackgroundImage(image, for: state) }) { options.onDataReceived = (options.onDataReceived ?? []) + [provider] } options.onDataReceived?.forEach { $0.onShouldApply = { issuedIdentifier == self.backgroundTaskIdentifier(for: state) } } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.backgroundImageTask = nil mutatingSelf.setBackgroundTaskIdentifier(nil, for: state) switch result { case .success(let value): self.base.setBackgroundImage(value.image, for: state) completionHandler?(result) case .failure: if let image = options.onFailureImage { self.base.setBackgroundImage(image, for: state) } completionHandler?(result) } } } ) mutatingSelf.backgroundImageTask = task return task } /// Sets a background image to the button for a specified state with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - state: The button state to which the image should be set. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setBackgroundImage( with resource: Resource?, for state: UIControl.State, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setBackgroundImage( with: resource.map { .network($0) }, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Background Downloading Task /// Cancels the background image download task of the button if it is running. /// Nothing will happen if the downloading has already finished. public func cancelBackgroundImageDownloadTask() { backgroundImageTask?.cancel() } } // MARK: - Associated Object private var taskIdentifierKey: Void? private var imageTaskKey: Void? // MARK: Properties extension KingfisherWrapper where Base: UIButton { private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]> public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return taskIdentifierInfo.value[state.rawValue] } private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { taskIdentifierInfo.value[state.rawValue] = identifier } private var taskIdentifierInfo: TaskIdentifier { return getAssociatedObject(base, &taskIdentifierKey) ?? { setRetainedAssociatedObject(base, &taskIdentifierKey, $0) return $0 } (TaskIdentifier([:])) } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } } private var backgroundTaskIdentifierKey: Void? private var backgroundImageTaskKey: Void? // MARK: Background Properties extension KingfisherWrapper where Base: UIButton { public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { return backgroundTaskIdentifierInfo.value[state.rawValue] } private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { backgroundTaskIdentifierInfo.value[state.rawValue] = identifier } private var backgroundTaskIdentifierInfo: TaskIdentifier { return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? { setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0) return $0 } (TaskIdentifier([:])) } private var backgroundImageTask: DownloadTask? { get { return getAssociatedObject(base, &backgroundImageTaskKey) } mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) } } } extension KingfisherWrapper where Base: UIButton { /// Gets the image URL of this button for a specified state. /// /// - Parameter state: The state that uses the specified image. /// - Returns: Current URL for image. @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.") public func webURL(for state: UIControl.State) -> URL? { return nil } /// Gets the background image URL of this button for a specified state. /// /// - Parameter state: The state that uses the specified background image. /// - Returns: Current URL for image. @available(*, deprecated, message: "Use `backgroundTaskIdentifier` instead to identify a setting task.") public func backgroundWebURL(for state: UIControl.State) -> URL? { return nil } }
mit
65d0691280660403b3414a661e3c8a19
43.746154
119
0.62707
5.463682
false
false
false
false
martinschilliger/SwissGrid
Pods/Alamofire/Source/Response.swift
1
17871
// // Response.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics _: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DataResponse { /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result /// value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's /// result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics _: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DownloadResponse { /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this /// instance's result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif }
mit
a95817c0c5b346b9acb77b8d3516d0e4
37.765727
119
0.656315
4.826087
false
false
false
false
Lomotif/lomotif-ios-httprequest
HttpRequest/FileFetcher.swift
1
5498
// // FileFetcher.swift // HttpRequest // // Created by Kok Chung Law on 24/4/16. // Copyright © 2016 Lomotif Private Limited. All rights reserved. // import Foundation import Haneke import Alamofire typealias FileCache = Haneke.Cache // MARK: - FileFetcher class /** Custom fetcher class */ open class FileFetcher: Fetcher<Data> { public typealias SuccessHandler = (Data) -> () public typealias FailureHandler = (Error?) -> () public typealias ProgressHandler = (Progress) -> () // MARK: - Properties open var url: URLConvertible? open var URLRequest: URLRequestConvertible? open var headers: HTTPHeaders? open var body: Parameters? open var request: DataRequest? open var formatName: String! open var successHandler: SuccessHandler? open var failureHandler: FailureHandler? open var progressHandler: ProgressHandler? open var cache: Cache<Data> = Shared.fileCache // MARK: - Initializer public init?(key: String? = nil, url: URLConvertible, headers: HTTPHeaders? = nil, body: Parameters? = nil, formatName: String = HanekeGlobals.Cache.OriginalFormatName) { var urlString: String! do { urlString = try url.asURL().absoluteString } catch { return nil } super.init(key: key == nil ? urlString : key!) self.url = url self.headers = headers self.body = body self.formatName = formatName } public init?(key: String? = nil, request: URLRequestConvertible, formatName: String = HanekeGlobals.Cache.OriginalFormatName) { guard let url = request.urlRequest?.url else { return nil } super.init(key: key == nil ? url.absoluteString : key!) self.URLRequest = request self.formatName = formatName } // MARK: - Functions /** Fetching file with alamofire request - parameter failure: Failure handler block - parameter success: Success handler block */ open override func fetch(failure: FailureHandler?, success: SuccessHandler?) { if url == nil { failure?(nil) } if url != nil { request = HttpRequest.GET(url!, headers: headers, body: body) } else if URLRequest != nil { request = HttpRequest.request(URLRequest!) } successHandler = success failureHandler = failure request?.response(completionHandler: { [weak self] (response) in if let strongSelf = self { guard let data = response.data else { strongSelf.failureHandler?(response.error) strongSelf.request = nil strongSelf.successHandler = nil strongSelf.failureHandler = nil strongSelf.progressHandler = nil return } strongSelf.cache.set(value: data, key: strongSelf.key, formatName: strongSelf.formatName, success: { (data) in strongSelf.successHandler?(data) strongSelf.request = nil strongSelf.successHandler = nil strongSelf.failureHandler = nil strongSelf.progressHandler = nil }) } }).downloadProgress(closure: { [weak self] (progress) in self?.progressHandler?(progress) }) } /** Cancel fetching */ open override func cancelFetch() { request?.cancel() successHandler = nil failureHandler = nil progressHandler = nil } } // MARK: Haneke Cache extension public extension Cache { /** Fetch file from url - parameter URL: URL to fetch the file from - parameter headers: Optional request headers - parameter body: Optional request body - paramater failure: Failure handler block - paramater success: Success handler block - returns: FileFetcher instance */ public func fetchFile(_ url: URLConvertible, headers: HTTPHeaders? = nil, body: Parameters? = nil, formatName: String, failure: @escaping FileFetcher.FailureHandler, success: @escaping FileFetcher.SuccessHandler) -> FileFetcher? { guard let fetcher = FileFetcher(url: url, headers: headers, body: body, formatName: formatName) else { return nil } return fetcher } /** Fetch file with url request - parameter request: URL request to fetch the file from - paramater failure: Failure handler block - paramater success: Success handler block - returns: FileFetcher instance */ public func fetchFile(_ request: URLRequestConvertible, formatName: String, failure: @escaping FileFetcher.FailureHandler, success: @escaping FileFetcher.SuccessHandler) -> FileFetcher? { guard let fetcher = FileFetcher(request: request, formatName: formatName) else { return nil } _ = Shared.fileCache.fetch(fetcher: fetcher).onFailure(failure).onSuccess(success) return fetcher } } // MARK: Haneke Shared extension public extension Shared { // MARK: Shared file cache instance public static var fileCache : Cache<Data> { struct Static { static let name = "shared-file" static let cache = Cache<Data>(name: name) } return Static.cache } }
mit
5d367ce8bd0444719f45544560a2fd00
32.518293
234
0.613971
5.071033
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIKitExtensions/String+QMUI.swift
1
14679
// // String+QMUI.swift // QMUI.swift // // Created by 伯驹 黄 on 2017/4/13. // Copyright © 2017年 伯驹 黄. All rights reserved. // extension String { /// 判断是否包含某个子字符串 func qmui_includesString(string: String) -> Bool { guard string.length > 0 else { return false } return contains(string) } /// 去掉头尾的空白字符 var qmui_trim: String { return trimmingCharacters(in: .whitespacesAndNewlines) } /// 去掉整段文字内的所有空白字符(包括换行符) func qmui_trimAllWhiteSpace() -> String { return replacingOccurrences(of: "\\s", with: "", options: .regularExpression) } /// 将文字中的换行符替换为空格 func qmui_trimLineBreakCharacter() -> String { return replacingOccurrences(of: "[\r\n]", with: " ", options: .regularExpression) } /// 把该字符串转换为对应的 md5 var qmui_md5: String { let length = Int(CC_MD5_DIGEST_LENGTH) let messageData = data(using:.utf8)! var digestData = Data(count: length) _ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in messageData.withUnsafeBytes { messageBytes -> UInt8 in if let messageBytesBaseAddress = messageBytes.baseAddress, let digestBytesBlindMemory = digestBytes.bindMemory(to: UInt8.self).baseAddress { let messageLength = CC_LONG(messageData.count) CC_MD5(messageBytesBaseAddress, messageLength, digestBytesBlindMemory) } return 0 } } return digestData.map { String(format: "%02hhx", $0) }.joined() } /// 把某个十进制数字转换成十六进制的数字的字符串,例如“10”->“A” static func qmui_hexString(with int: Int) -> String { var hexString = "" var integer = int var remainder = 0 for _ in 0 ..< 9 { remainder = integer % 16 integer = integer / 16 let letter = hexLetterString(with: remainder) hexString = letter + hexString if integer == 0 { break } } return hexString } /// 把参数列表拼接成一个字符串并返回,相当于用另一种语法来代替 [NSString stringWithFormat:] static func qmui_stringByConcat(_ argvs: Any...) -> String { var result = "" for argv in argvs { result += String(describing: argv) } return result } /** * 将秒数转换为同时包含分钟和秒数的格式的字符串,例如 100->"01:40" */ static func qmui_timeStringWithMinsAndSecs(from seconds: Double) -> String { let min = floor(seconds / 60) let sec = floor(seconds - min * 60) return String(format: "%02ld:%02ld", min, sec) } /** * 用正则表达式匹配的方式去除字符串里一些特殊字符,避免UI上的展示问题 * @link http://www.croton.su/en/uniblock/Diacriticals.html */ func qmui_removeMagicalChar() -> String { if length == 0 { return self } if let regex = try? NSRegularExpression(pattern: "[\u{0300}-\u{036F}]", options: .caseInsensitive) { let modifiedString = regex.stringByReplacingMatches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, length), withTemplate: "") return modifiedString } else { return self } } /** * 按照中文 2 个字符、英文 1 个字符的方式来计算文本长度 */ var qmui_lengthWhenCountingNonASCIICharacterAsTwo: Int { func isChinese(_ char: Character) -> Bool { return "\u{4E00}" <= char && char <= "\u{9FA5}" } var characterLength = 0 for char in self { if isChinese(char) { characterLength += 2 } else { characterLength += 1 } } return characterLength } private func transformIndexToDefaultModeWithIndex(_ index: Int) -> Int { var stringLength = 0 for (index, i) in enumerated() { if i.unicodeScalars.first?.isASCII ?? false { stringLength += 1 } else { stringLength += 2 } if stringLength > index { return index } } return 0 } private func transformRangeToDefaultModeWithRange(_ range: Range<String.Index>) -> Range<String.Index> { var stringLength = 0 var resultRange: Range<String.Index> = startIndex ..< startIndex for (index, i) in enumerated() { if i.unicodeScalars.first?.isASCII ?? false { stringLength += 1 } else { stringLength += 2 } if stringLength >= self.index(after: range.lowerBound).utf16Offset(in: self) { let currentIndex = self.index(startIndex, offsetBy: index) if resultRange.lowerBound == startIndex { resultRange = currentIndex ..< resultRange.upperBound } if !resultRange.isEmpty && stringLength >= resultRange.upperBound.utf16Offset(in: self) { let upperBound = stringLength == resultRange.upperBound.utf16Offset(in: self) ? self.index(after: currentIndex) : currentIndex resultRange = resultRange.lowerBound ..< upperBound return resultRange } } } return resultRange } /** * 将字符串从指定的 index 开始裁剪到结尾,裁剪时会避免将 emoji 等 "character sequences" 拆散(一个 emoji 表情占用1-4个长度的字符)。 * * 例如对于字符串“😊😞”,它的长度为4,若调用 [string qmui_substringAvoidBreakingUpCharacterSequencesFromIndex:1],将返回“😊😞”。 * 若调用系统的 [string substringFromIndex:1],将返回“?😞”。(?表示乱码,因为第一个 emoji 表情被从中间裁开了)。 * * @param index 要从哪个 index 开始裁剪文字 * @param lessValue 要按小的长度取,还是按大的长度取 * @param countingNonASCIICharacterAsTwo 是否按照 英文 1 个字符长度、中文 2 个字符长度的方式来裁剪 * @return 裁剪完的字符 */ func qmui_substringAvoidBreakingUpCharacterSequencesFromIndex(index: Int, lessValue: Bool, countingNonASCIICharacterAsTwoindex: Bool) -> String { let index = countingNonASCIICharacterAsTwoindex ? transformIndexToDefaultModeWithIndex(index) : index let range = rangeOfComposedCharacterSequence(at: self.index(startIndex, offsetBy: index)) return String(describing: [(lessValue ? range.upperBound : range.lowerBound)...]) } /** * 相当于 `qmui_substringAvoidBreakingUpCharacterSequencesFromIndex: lessValue:YES` countingNonASCIICharacterAsTwo:NO * @see qmui_substringAvoidBreakingUpCharacterSequencesFromIndex:lessValue:countingNonASCIICharacterAsTwo: */ func qmui_substringAvoidBreakingUpCharacterSequencesFromIndex(index: Int) -> String { return qmui_substringAvoidBreakingUpCharacterSequencesFromIndex(index: index, lessValue: true, countingNonASCIICharacterAsTwoindex: false) } /** * 将字符串从开头裁剪到指定的 index,裁剪时会避免将 emoji 等 "character sequences" 拆散(一个 emoji 表情占用1-4个长度的字符)。 * * 例如对于字符串“😊😞”,它的长度为4,若调用 [string qmui_substringAvoidBreakingUpCharacterSequencesToIndex:1],将返回“😊”。 * 若调用系统的 [string substringToIndex:1],将返回“?”。(?表示乱码,因为第一个 emoji 表情被从中间裁开了)。 * * @param index 要裁剪到哪个 index * @return 裁剪完的字符 * @param countingNonASCIICharacterAsTwo 是否按照 英文 1 个字符长度、中文 2 个字符长度的方式来裁剪 */ func qmui_substringAvoidBreakingUpCharacterSequencesToIndex(index: Int, lessValue: Bool, countingNonASCIICharacterAsTwo: Bool) -> String { let index = countingNonASCIICharacterAsTwo ? transformIndexToDefaultModeWithIndex(index) : index let range = rangeOfComposedCharacterSequence(at: self.index(startIndex, offsetBy: index)) return String(describing: [...(lessValue ? range.lowerBound : range.upperBound)]) } /** * 相当于 `qmui_substringAvoidBreakingUpCharacterSequencesToIndex:lessValue:YES` countingNonASCIICharacterAsTwo:NO * @see qmui_substringAvoidBreakingUpCharacterSequencesToIndex:lessValue:countingNonASCIICharacterAsTwo: */ func qmui_substringAvoidBreakingUpCharacterSequencesToIndex(index: Int) -> String { return qmui_substringAvoidBreakingUpCharacterSequencesToIndex(index: index, lessValue: true, countingNonASCIICharacterAsTwo: false) } /** * 将字符串里指定 range 的子字符串裁剪出来,会避免将 emoji 等 "character sequences" 拆散(一个 emoji 表情占用1-4个长度的字符)。 * * 例如对于字符串“😊😞”,它的长度为4,在 lessValue 模式下,裁剪 (0, 1) 得到的是空字符串,裁剪 (0, 2) 得到的是“😊”。 * 在非 lessValue 模式下,裁剪 (0, 1) 或 (0, 2),得到的都是“😊”。 * * @param range 要裁剪的文字位置 * @param lessValue 裁剪时若遇到“character sequences”,是向下取整还是向上取整。 * @param countingNonASCIICharacterAsTwo 是否按照 英文 1 个字符长度、中文 2 个字符长度的方式来裁剪 * @return 裁剪完的字符 */ func qmui_substringAvoidBreakingUpCharacterSequencesWithRange(range: Range<String.Index>, lessValue: Bool, countingNonASCIICharacterAsTwo: Bool) -> String { let range = countingNonASCIICharacterAsTwo ? transformRangeToDefaultModeWithRange(range) : range let characterSequencesRange = lessValue ? downRoundRangeOfComposedCharacterSequencesForRange(range) : rangeOfComposedCharacterSequences(for: range) return String(describing: [characterSequencesRange]) } /** * 相当于 `qmui_substringAvoidBreakingUpCharacterSequencesWithRange:lessValue:YES` countingNonASCIICharacterAsTwo:NO * @see qmui_substringAvoidBreakingUpCharacterSequencesWithRange:lessValue:countingNonASCIICharacterAsTwo: */ func qmui_substringAvoidBreakingUpCharacterSequencesWithRange(range: Range<String.Index>) -> String { return qmui_substringAvoidBreakingUpCharacterSequencesWithRange(range: range, lessValue: true, countingNonASCIICharacterAsTwo: false) } /** * 移除指定位置的字符,可兼容emoji表情的情况(一个emoji表情占1-4个length) * @param index 要删除的位置 */ func qmui_stringByRemoveCharacter(at index: Int) -> String { guard let stringIndex = self.index(startIndex, offsetBy: index, limitedBy: endIndex) else { return self } let rangeForMove = rangeOfComposedCharacterSequence(at: stringIndex) let resultString = replacingCharacters(in: rangeForMove, with: "") return resultString } /** * 移除最后一个字符,可兼容emoji表情的情况(一个emoji表情占1-4个length) * @see `qmui_stringByRemoveCharacterAtIndex:` */ func qmui_stringByRemoveLastCharacter() -> String { return qmui_stringByRemoveCharacter(at: length - 1) } private func downRoundRangeOfComposedCharacterSequencesForRange(_ range: Range<String.Index>) -> Range<String.Index> { if range.isEmpty { return range } let resultRange = rangeOfComposedCharacterSequences(for: range) if resultRange.upperBound > range.upperBound { return downRoundRangeOfComposedCharacterSequencesForRange(range.lowerBound ..< index(before: range.upperBound)) } return resultRange } private static func hexLetterString(with int: Int) -> String { assert(int < 16, "要转换的数必须是16进制里的个位数,也即小于16,但你传给我是\(int)") var letter = "" switch int { case 10: letter = "A" case 11: letter = "B" case 12: letter = "C" case 13: letter = "D" case 14: letter = "E" case 15: letter = "F" default: letter = "\(int)" } return letter } var encoding: String { // let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" // let unreservedCharset = CharacterSet(charactersIn: unreservedChars) // return addingPercentEncoding(withAllowedCharacters: unreservedCharset) ?? self return addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? self } init(seconds: Double) { let min = floor(seconds / 60) let sec = floor(seconds - min * 60) self.init(format: "%02ld:%02ld", min, sec) } var decoding: String { return removingPercentEncoding ?? self } func index(from: Int) -> Index { return index(startIndex, offsetBy: from) } // https://stackoverflow.com/questions/45562662/how-can-i-use-string-slicing-subscripts-in-swift-4 func substring(from: Int) -> String { return String(describing: [from...]) } func substring(to: Int) -> String { return String(describing: [..<index(from: to)]) } func substring(with nsrange: NSRange) -> String { guard let range = Range(nsrange, in: self) else { return "" } return String(self[range]) } var length: Int { return count } subscript(i: Int) -> String { return self[i ..< i + 1] } subscript(r: Range<Int>) -> String { let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound)))) let start = index(startIndex, offsetBy: range.lowerBound) let end = index(start, offsetBy: range.upperBound - range.lowerBound) return String(self[start ..< end]) } }
mit
6061945eae5baeb9f16f3bd016e26299
35.360111
183
0.628676
4.132872
false
false
false
false
bluquar/emoji_keyboard
DecisiveEmojiKeyboard/DEKeyboard/EmojiSelectionOption.swift
1
1702
// // EmojiSelectionOption.swift // DecisiveEmojiKeyboard // // Created by Chris Barker on 11/28/14. // Copyright (c) 2014 Chris Barker. All rights reserved. // import UIKit class EmojiSelectionOption: SelectionOption { var emoji: String init(controller: EmojiSelectionController, emoji: String) { self.emoji = emoji super.init(controller: controller) } override func selected() -> Void { self.controller.finalSelect(self) } override func addContent(contentView: UIView) { let label = UILabel() label.text = self.emoji label.font = UIFont.systemFontOfSize(75) label.textAlignment = NSTextAlignment.Center label.adjustsFontSizeToFitWidth = true label.sizeToFit() label.setTranslatesAutoresizingMaskIntoConstraints(false) contentView.addSubview(label) let constraints = [ NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: self.parentView!, attribute: .CenterX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self.parentView!, attribute: .CenterY, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: self.parentView!, attribute: .Width, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: self.parentView!, attribute: .Width, multiplier: 1.0, constant: 0.0), ] self.parentView.addConstraints(constraints) } }
gpl-2.0
b43b16471f56c2c10afdcbe0ef8f2bf1
36.822222
109
0.648061
4.587601
false
false
false
false
elegion/ios-Flamingo
Framework/FlamingoTests/OfflineCacheManagerTests.swift
1
4413
// // OfflineCacheManagerTests.swift // FlamingoTests // // Created by Nikolay Ischuk on 04.03.2018. // Copyright © 2018 ELN. All rights reserved. // import XCTest @testable import Flamingo private final class MockCache: OfflineCacheProtocol { var wasCalledCache = false var wasCalledResponse = false var storage: [URLRequest: CachedURLResponse] = [:] func storeCachedResponse(_ cachedResponse: CachedURLResponse, for request: URLRequest) { storage[request] = cachedResponse wasCalledCache = true } func cachedResponse(for request: URLRequest) -> CachedURLResponse? { let result = storage[request] if result != nil { wasCalledResponse = true } return result } } private final class MockUsers: NetworkClientMutater { var wasCalledResponse = false func response<Request>(for request: Request) -> NetworkClientMutater.RawResponseTuple? where Request: NetworkRequest { let dataAsString = """ [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ] """ let response = HTTPURLResponse(url: URL(fileURLWithPath: ""), statusCode: 200, httpVersion: nil, headerFields: nil) wasCalledResponse = true return (dataAsString.data(using: .utf8), response, nil) } } class OfflineCacheManagerTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } var networkClient: NetworkDefaultClient { let configuration = NetworkDefaultConfiguration(baseURL: "http://jsonplaceholder.typicode.com/", parallel: false) let client = NetworkDefaultClient(configuration: configuration, session: .shared) return client } func test_cachedResponse() { let urlCache = MockCache() let request = UsersRequest() do { let client = networkClient let cacheManager = OfflineCacheManager(cache: urlCache, storagePolicy: .allowed, networkClient: client, reachability: { return true }) client.addOfflineCacheManager(cacheManager) let mockUsers = MockUsers() client.addMutater(mockUsers) client.sendRequest(request) { result, _ in do { let value = try result.get() XCTAssertEqual(value.count, 1) } catch { XCTAssertNil(error, error.localizedDescription) } } XCTAssertTrue(mockUsers.wasCalledResponse) XCTAssertTrue(urlCache.wasCalledCache) XCTAssertFalse(urlCache.wasCalledResponse) } do { let client = networkClient let cacheManager = OfflineCacheManager(cache: urlCache, storagePolicy: .allowed, networkClient: client, reachability: { return true }) client.addOfflineCacheManager(cacheManager) let mockUsers = MockUsers() client.addMutater(mockUsers) client.sendRequest(request) { result, _ in do { let value = try result.get() XCTAssertEqual(value.count, 1) } catch { XCTAssertNil(error, error.localizedDescription) } } XCTAssertFalse(mockUsers.wasCalledResponse) XCTAssertTrue(urlCache.wasCalledResponse) } } }
mit
09078a62888f6f9bf28f7ce097fec310
29.427586
122
0.537625
5.21513
false
false
false
false
uxmstudio/UXMPDFKit
Pod/Classes/Renderer/PDFPageContentView.swift
1
9136
// // PDFPageContentView.swift // Pods // // Created by Chris Anderson on 3/5/16. // // import UIKit public protocol PDFPageContentViewDelegate { func contentView(_ contentView: PDFPageContentView, didSelect action: PDFAction) func contentView(_ contentView: PDFPageContentView, didSelect annotation: PDFAnnotationView) func contentView(_ contentView: PDFPageContentView, tapped recognizer: UITapGestureRecognizer) func contentView(_ contentView: PDFPageContentView, doubleTapped recognizer: UITapGestureRecognizer) } open class PDFPageContentView: UIScrollView, UIScrollViewDelegate { public let contentView: PDFPageContent let containerView: UIView open var page: Int open var contentDelegate: PDFPageContentViewDelegate? open var viewDidZoom: ((CGFloat) -> Void)? fileprivate var PDFPageContentViewContext = 0 fileprivate var previousScale: CGFloat = 1.0 let bottomKeyboardPadding: CGFloat = 20.0 init(frame: CGRect, document: PDFDocument, page: Int) { self.page = page contentView = PDFPageContent(document: document, page: page) containerView = UIView(frame: contentView.bounds) containerView.isUserInteractionEnabled = true containerView.contentMode = .redraw containerView.backgroundColor = UIColor.white containerView.autoresizesSubviews = true containerView.autoresizingMask = [.flexibleHeight, .flexibleWidth] super.init(frame: frame) scrollsToTop = false delaysContentTouches = false showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false contentMode = .redraw backgroundColor = UIColor.clear isUserInteractionEnabled = true autoresizesSubviews = false isPagingEnabled = false bouncesZoom = true delegate = self isScrollEnabled = true clipsToBounds = true autoresizingMask = [.flexibleHeight, .flexibleWidth] contentView.translatesAutoresizingMaskIntoConstraints = false contentSize = contentView.bounds.size containerView.addSubview(contentView) addSubview(containerView) updateMinimumMaximumZoom() zoomScale = minimumZoomScale tag = page self.addObserver(self, forKeyPath: "frame", options: [.new, .old], context: &PDFPageContentViewContext) NotificationCenter.default.addObserver( self, selector: #selector(PDFPageContentView.keyboardWillShowNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(PDFPageContentView.keyboardWillHideNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil ) let singleTapRecognizer = UITapGestureRecognizer( target: self, action: #selector(PDFPageContentView.processSingleTap(_:)) ) singleTapRecognizer.numberOfTouchesRequired = 1 singleTapRecognizer.numberOfTapsRequired = 1 singleTapRecognizer.cancelsTouchesInView = false self.addGestureRecognizer(singleTapRecognizer) let doubleTapRecognizer = UITapGestureRecognizer( target: self, action: #selector(PDFPageContentView.processDoubleTap(_:)) ) doubleTapRecognizer.numberOfTouchesRequired = 1 doubleTapRecognizer.numberOfTapsRequired = 2 doubleTapRecognizer.cancelsTouchesInView = false singleTapRecognizer.require(toFail: doubleTapRecognizer) self.addGestureRecognizer(doubleTapRecognizer) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) self.removeObserver(self, forKeyPath: "frame") } override open func layoutSubviews() { super.layoutSubviews() let boundsSize = bounds.size var viewFrame = containerView.frame if viewFrame.size.width < boundsSize.width { viewFrame.origin.x = (boundsSize.width - viewFrame.size.width) / 2.0 + contentOffset.x } else { viewFrame.origin.x = 0.0 } if viewFrame.size.height < boundsSize.height { viewFrame.origin.y = (boundsSize.height - viewFrame.size.height) / 2.0 + contentOffset.y } else { viewFrame.origin.y = 0.0 } containerView.frame = viewFrame contentView.frame = containerView.bounds } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &PDFPageContentViewContext, let keyPath = keyPath, keyPath == "frame", self == (object as? PDFPageContentView) else { return } updateMinimumMaximumZoom() self.zoomReset() } @objc open func processSingleTap(_ recognizer: UITapGestureRecognizer) { if let action = contentView.processSingleTap(recognizer) as? PDFAction { contentDelegate?.contentView(self, didSelect: action) } else if let annotation = contentView.processSingleTap(recognizer) as? PDFAnnotationView { contentDelegate?.contentView(self, didSelect: annotation) } else { contentDelegate?.contentView(self, tapped: recognizer) } } @objc open func processDoubleTap(_ recognizer: UITapGestureRecognizer) { contentDelegate?.contentView(self, doubleTapped: recognizer) } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let result = super.hitTest(point, with: event) self.isScrollEnabled = !(result is ResizableBorderView) return result } //MARK: - Zoom methods open func zoomIncrement() { var zoomScale = self.zoomScale if zoomScale < minimumZoomScale { zoomScale /= 2.0 if zoomScale > minimumZoomScale { zoomScale = maximumZoomScale } setZoomScale(zoomScale, animated: true) } } open func zoomDecrement() { var zoomScale = self.zoomScale if zoomScale < minimumZoomScale { zoomScale *= 2.0 if zoomScale > minimumZoomScale { zoomScale = maximumZoomScale } setZoomScale(zoomScale, animated: true) } } open func zoomReset() { zoomScale = minimumZoomScale let offsetX = max((self.bounds.size.width - self.contentSize.width) * 0.5, 0.0) let offsetY = max((self.bounds.size.height - self.contentSize.height) * 0.5, 0.0) containerView.center = CGPoint(x: self.contentSize.width * 0.5 + offsetX, y: self.contentSize.height * 0.5 + offsetY) } //MARK: - UIScrollViewDelegate methods open func viewForZooming(in scrollView: UIScrollView) -> UIView? { return containerView } open func scrollViewDidZoom(_ scrollView: UIScrollView) { viewDidZoom?(scrollView.zoomScale) } @objc func keyboardWillShowNotification(_ notification: Notification) { updateBottomLayoutConstraintWithNotification(notification, show: true) } @objc func keyboardWillHideNotification(_ notification: Notification) { updateBottomLayoutConstraintWithNotification(notification, show: false) } func updateBottomLayoutConstraintWithNotification(_ notification: Notification, show:Bool) { let userInfo = (notification as NSNotification).userInfo! let keyboardEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let convertedKeyboardEndFrame = self.convert(keyboardEndFrame, from: self.window) let height: CGFloat if convertedKeyboardEndFrame.height > 0 && show { height = convertedKeyboardEndFrame.height + bottomKeyboardPadding } else { height = 0 } contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: height, right: 0) } //MARK: - Helper methods static func zoomScaleThatFits(_ target: CGSize, source: CGSize) -> CGFloat { let widthScale = target.width / source.width let heightScale = target.height / source.height return (widthScale < heightScale) ? widthScale : heightScale } func updateMinimumMaximumZoom() { previousScale = self.zoomScale let targetRect = bounds.insetBy(dx: 0, dy: 0) let zoomScale = PDFPageContentView.zoomScaleThatFits(targetRect.size, source: contentView.bounds.size) minimumZoomScale = zoomScale maximumZoomScale = zoomScale * 16.0 } }
mit
d2b375cd56089b6b9937ccba12600959
34.003831
156
0.669111
5.563946
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Extensions/Tests/SwiftExtensionsTests/ReferenceTests.swift
1
721
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftExtensions import XCTest final class ReferenceTests: XCTestCase { func test_reference() throws { func mutate(_ a: inout Struct, by value: String) { a.string = value } struct Struct { var string = "" } var a = Struct() let reference = Reference(&a) mutate(&reference.value, by: "Mutant") XCTAssertEqual(reference.value.string, "Mutant") } func test_weak() throws { class Object {} var value: Object? = Object() let weak = Weak(value) XCTAssertNotNil(weak.value) value = nil XCTAssertNil(weak.value) } }
lgpl-3.0
150128566bf7b549e95172c262328dfe
20.176471
62
0.588889
4.390244
false
true
false
false
esttorhe/Watch_BotLauncher
Carthage/Checkouts/XcodeServerSDK/XcodeServerSDKTests/BotConfigurationTests.swift
1
3606
// // BotConfigurationTests.swift // XcodeServerSDK // // Created by Mateusz Zając on 24.06.2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import XCTest import XcodeServerSDK class BotConfigurationTests: 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() } // MARK: Cleaning policy tests func testCleaningPolicyToString() { var policy: BotConfiguration.CleaningPolicy policy = .Never XCTAssertEqual(policy.toString(), "Never") policy = .Always XCTAssertEqual(policy.toString(), "Always") policy = .Once_a_Day XCTAssertEqual(policy.toString(), "Once a day (first build)") policy = .Once_a_Week XCTAssertEqual(policy.toString(), "Once a week (first build)") } // MARK: Testing destination tests func testTestingDestinationToString() { var destination: BotConfiguration.TestingDestinationIdentifier destination = .iOS_AllDevicesAndSimulators XCTAssertEqual(destination.toString(), "iOS: All Devices and Simulators") destination = .iOS_AllDevices XCTAssertEqual(destination.toString(), "iOS: All Devices") destination = .iOS_AllSimulators XCTAssertEqual(destination.toString(), "iOS: All Simulators") destination = .iOS_SelectedDevicesAndSimulators XCTAssertEqual(destination.toString(), "iOS: Selected Devices and Simulators") destination = .Mac XCTAssertEqual(destination.toString(), "Mac") destination = .AllCompatible XCTAssertEqual(destination.toString(), "All Compatible (Mac + iOS)") } func testAllowedDevicesTypes() { let allCompatible = BotConfiguration.TestingDestinationIdentifier.AllCompatible let selected = BotConfiguration.TestingDestinationIdentifier.iOS_SelectedDevicesAndSimulators let allDevicesAndSimulators = BotConfiguration.TestingDestinationIdentifier.iOS_AllDevicesAndSimulators let allDevices = BotConfiguration.TestingDestinationIdentifier.iOS_AllDevices let allSimulators = BotConfiguration.TestingDestinationIdentifier.iOS_AllSimulators let mac = BotConfiguration.TestingDestinationIdentifier.Mac let allCompatibleExpected: [BotConfiguration.DeviceType] = [.iPhone, .Simulator, .Mac] let selectedExpected: [BotConfiguration.DeviceType] = [.iPhone, .Simulator] let allDevicesAndSimulatorsExpected: [BotConfiguration.DeviceType] = [.iPhone, .Simulator] let allDevicesExpected: [BotConfiguration.DeviceType] = [.iPhone] let allSimulatorsExpected: [BotConfiguration.DeviceType] = [.Simulator] let macExpected: [BotConfiguration.DeviceType] = [.Mac] XCTAssertEqual(allCompatible.allowedDeviceTypes(), allCompatibleExpected) XCTAssertEqual(selected.allowedDeviceTypes(), selectedExpected) XCTAssertEqual(allDevices.allowedDeviceTypes(), allDevicesExpected) XCTAssertEqual(allSimulators.allowedDeviceTypes(), allSimulatorsExpected) XCTAssertEqual(allDevicesAndSimulators.allowedDeviceTypes(), allDevicesAndSimulatorsExpected) XCTAssertEqual(mac.allowedDeviceTypes(), macExpected) } }
mit
3a9eac13556b15064d28a07f0316fcd0
40.425287
111
0.698391
5.200577
false
true
false
false
leoMehlig/Charts
Charts/Classes/Renderers/LineChartRenderer.swift
2
27452
// // LineChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class LineChartRenderer: LineRadarChartRenderer { public weak var dataProvider: LineChartDataProvider? public init(dataProvider: LineChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let lineData = dataProvider?.lineData else { return } for (var i = 0; i < lineData.dataSetCount; i++) { guard let set = lineData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is ILineChartDataSet) { fatalError("Datasets for LineChartRenderer must conform to ILineChartDataSet") } drawDataSet(context: context, dataSet: set as! ILineChartDataSet) } } } public func drawDataSet(context context: CGContext, dataSet: ILineChartDataSet) { let entryCount = dataSet.entryCount if (entryCount < 1) { return } CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.lineWidth) if (dataSet.lineDashLengths != nil) { CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths!, dataSet.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } // if drawing cubic lines is enabled if (dataSet.isDrawCubicEnabled) { drawCubic(context: context, dataSet: dataSet) } else { // draw normal (straight) lines drawLinear(context: context, dataSet: dataSet) } CGContextRestoreGState(context) } public func drawCubic(context context: CGContext, dataSet: ILineChartDataSet) { guard let trans = dataProvider?.getTransformer(dataSet.axisDependency), animator = animator else { return } let entryCount = dataSet.entryCount guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { return } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff - 1, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) let phaseX = animator.phaseX let phaseY = animator.phaseY // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! let intensity = dataSet.cubicIntensity // the path for the cubic-spline let cubicPath = CGPathCreateMutable() var valueToPixelMatrix = trans.valueToPixelMatrix let size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) if (size - minx >= 2) { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 var prevPrev: ChartDataEntry! = dataSet.entryForIndex(minx) var prev: ChartDataEntry! = prevPrev var cur: ChartDataEntry! = prev var next: ChartDataEntry! = dataSet.entryForIndex(minx + 1) if cur == nil || next == nil { return } // let the spline start CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity prevDy = CGFloat(cur.value - prev.value) * intensity curDx = CGFloat(next.xIndex - cur.xIndex) * intensity curDy = CGFloat(next.value - cur.value) * intensity // the first cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) for (var j = minx + 1, count = min(size, entryCount - 1); j < count; j++) { prevPrev = prev prev = cur cur = next next = dataSet.entryForIndex(j + 1) if next == nil { break } prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } if (size > entryCount - 1) { prevPrev = dataSet.entryForIndex(entryCount - (entryCount >= 3 ? 3 : 2)) prev = dataSet.entryForIndex(entryCount - 2) cur = dataSet.entryForIndex(entryCount - 1) next = cur if prevPrev == nil || prev == nil || cur == nil { return } prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity // the last cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } } CGContextSaveGState(context) if (dataSet.isDrawFilledEnabled) { // Copy this path because we make changes to it let fillPath = CGPathCreateMutableCopy(cubicPath) drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, from: minx, to: size) } CGContextBeginPath(context) CGContextAddPath(context, cubicPath) CGContextSetStrokeColorWithColor(context, drawingColor.CGColor) CGContextStrokePath(context) CGContextRestoreGState(context) } public func drawCubicFill(context context: CGContext, dataSet: ILineChartDataSet, spline: CGMutablePath, matrix: CGAffineTransform, from: Int, to: Int) { guard let dataProvider = dataProvider else { return } if to - from <= 1 { return } let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0 // Take the from/to xIndex from the entries themselves, // so missing entries won't screw up the filling. // What we need to draw is line from points of the xIndexes - not arbitrary entry indexes! let xTo = dataSet.entryForIndex(to - 1)?.xIndex ?? 0 let xFrom = dataSet.entryForIndex(from)?.xIndex ?? 0 var pt1 = CGPoint(x: CGFloat(xTo), y: fillMin) var pt2 = CGPoint(x: CGFloat(xFrom), y: fillMin) pt1 = CGPointApplyAffineTransform(pt1, matrix) pt2 = CGPointApplyAffineTransform(pt2, matrix) CGPathAddLineToPoint(spline, nil, pt1.x, pt1.y) CGPathAddLineToPoint(spline, nil, pt2.x, pt2.y) CGPathCloseSubpath(spline) if dataSet.fill != nil { drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) public func drawLinear(context context: CGContext, dataSet: ILineChartDataSet) { guard let trans = dataProvider?.getTransformer(dataSet.axisDependency), animator = animator else { return } let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let isDrawSteppedEnabled = dataSet.isDrawSteppedEnabled let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2 let phaseX = animator.phaseX let phaseY = animator.phaseY guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { return } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) CGContextSaveGState(context) // more than 1 color if (dataSet.colors.count > 1) { if (_lineSegments.count != pointsPerEntryPair) { _lineSegments = [CGPoint](count: pointsPerEntryPair, repeatedValue: CGPoint()) } for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { if (count > 1 && j == count - 1) { // Last point, we have already drawn a line to this point break } var e: ChartDataEntry! = dataSet.entryForIndex(j) if e == nil { continue } _lineSegments[0].x = CGFloat(e.xIndex) _lineSegments[0].y = CGFloat(e.value) * phaseY if (j + 1 < count) { e = dataSet.entryForIndex(j + 1) if e == nil { break } if isDrawSteppedEnabled { _lineSegments[1] = CGPoint(x: CGFloat(e.xIndex), y: _lineSegments[0].y) _lineSegments[2] = _lineSegments[1] _lineSegments[3] = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY) } else { _lineSegments[1] = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY) } } else { _lineSegments[1] = _lineSegments[0] } for i in 0..<_lineSegments.count { _lineSegments[i] = CGPointApplyAffineTransform(_lineSegments[i], valueToPixelMatrix) } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // make sure the lines don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))) { continue } // get the color that is set for this line-segment CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextStrokeLineSegments(context, _lineSegments, pointsPerEntryPair) } } else { // only one color per dataset var e1: ChartDataEntry! var e2: ChartDataEntry! if (_lineSegments.count != max((entryCount - 1) * pointsPerEntryPair, pointsPerEntryPair)) { _lineSegments = [CGPoint](count: max((entryCount - 1) * pointsPerEntryPair, pointsPerEntryPair), repeatedValue: CGPoint()) } e1 = dataSet.entryForIndex(minx) if e1 != nil { let count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++) { e1 = dataSet.entryForIndex(x == 0 ? 0 : (x - 1)) e2 = dataSet.entryForIndex(x) if e1 == nil || e2 == nil { continue } _lineSegments[j++] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY ), valueToPixelMatrix) if isDrawSteppedEnabled { _lineSegments[j++] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e2.xIndex), y: CGFloat(e1.value) * phaseY ), valueToPixelMatrix) _lineSegments[j++] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e2.xIndex), y: CGFloat(e1.value) * phaseY ), valueToPixelMatrix) } _lineSegments[j++] = CGPointApplyAffineTransform( CGPoint( x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY ), valueToPixelMatrix) } let size = max((count - minx - 1) * pointsPerEntryPair, pointsPerEntryPair) CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextStrokeLineSegments(context, _lineSegments, size) } } CGContextRestoreGState(context) // if drawing filled is enabled if (dataSet.isDrawFilledEnabled && entryCount > 0) { drawLinearFill(context: context, dataSet: dataSet, minx: minx, maxx: maxx, trans: trans) } } public func drawLinearFill(context context: CGContext, dataSet: ILineChartDataSet, minx: Int, maxx: Int, trans: ChartTransformer) { guard let dataProvider = dataProvider else { return } let filled = generateFilledPath( dataSet: dataSet, fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0, from: minx, to: maxx, matrix: trans.valueToPixelMatrix) if dataSet.fill != nil { drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } /// Generates the path that is used for filled drawing. private func generateFilledPath(dataSet dataSet: ILineChartDataSet, fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath { let phaseX = animator?.phaseX ?? 1.0 let phaseY = animator?.phaseY ?? 1.0 let isDrawSteppedEnabled = dataSet.isDrawSteppedEnabled var e: ChartDataEntry! let filled = CGPathCreateMutable() e = dataSet.entryForIndex(from) if e != nil { CGPathMoveToPoint(filled, &matrix, CGFloat(e.xIndex), fillMin) CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY) } // create a new path for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++) { guard let e = dataSet.entryForIndex(x) else { continue } if isDrawSteppedEnabled { guard let ePrev = dataSet.entryForIndex(x-1) else { continue } CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(ePrev.value) * phaseY) } CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY) } // close up e = dataSet.entryForIndex(max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, dataSet.entryCount - 1), 0)) if e != nil { CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), fillMin) } CGPathCloseSubpath(filled) return filled } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, lineData = dataProvider.lineData, animator = animator else { return } if (CGFloat(lineData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX) { var dataSets = lineData.dataSets let phaseX = animator.phaseX let phaseY = animator.phaseY var pt = CGPoint() for (var i = 0; i < dataSets.count; i++) { guard let dataSet = dataSets[i] as? ILineChartDataSet else { continue } if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if (!dataSet.isDrawCirclesEnabled) { valOffset = valOffset / 2 } let entryCount = dataSet.entryCount guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { continue } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } ChartUtils.drawText(context: context, text: formatter.stringFromNumber(e.value)!, point: CGPoint( x: pt.x, y: pt.y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]) } } } } public override func drawExtras(context context: CGContext) { drawCircles(context: context) } private func drawCircles(context context: CGContext) { guard let dataProvider = dataProvider, lineData = dataProvider.lineData, animator = animator else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY let dataSets = lineData.dataSets var pt = CGPoint() var rect = CGRect() CGContextSaveGState(context) for (var i = 0, count = dataSets.count; i < count; i++) { guard let dataSet = lineData.getDataSetByIndex(i) as? ILineChartDataSet else { continue } if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0 { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let circleRadius = dataSet.circleRadius let circleDiameter = circleRadius * 2.0 let circleHoleDiameter = circleRadius let circleHoleRadius = circleHoleDiameter / 2.0 let isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled guard let entryFrom = dataSet.entryForXIndex(self.minX < 0 ? self.minX : 0, rounding: .Down), entryTo = dataSet.entryForXIndex(self.maxX, rounding: .Up) else { continue } let diff = (entryFrom == entryTo) ? 1 : 0 let minx = max(dataSet.entryIndex(entry: entryFrom) - diff, 0) let maxx = min(max(minx + 2, dataSet.entryIndex(entry: entryTo) + 1), entryCount) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter CGContextFillEllipseInRect(context, rect) if (isDrawCircleHoleEnabled) { CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor) rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter CGContextFillEllipseInRect(context, rect) } } } CGContextRestoreGState(context) } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let lineData = dataProvider?.lineData, chartXMax = dataProvider?.chartXMax, animator = animator else { return } CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { guard let set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as? ILineChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX) { continue } let yValue = set.yValForXIndex(xIndex) if (yValue.isNaN) { continue } let y = CGFloat(yValue) * animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = dataProvider?.getTransformer(set.axisDependency) trans?.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
apache-2.0
6f5173fb790b3d11b5ba464f1f112cdf
37.885269
155
0.521346
5.617352
false
false
false
false
cburrows/swift-protobuf
Sources/SwiftProtobuf/JSONEncoder.swift
1
13707
// Sources/SwiftProtobuf/JSONEncoder.swift - JSON Encoding support // // Copyright (c) 2014 - 2019 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// JSON serialization engine. /// // ----------------------------------------------------------------------------- import Foundation private let asciiZero = UInt8(ascii: "0") private let asciiOne = UInt8(ascii: "1") private let asciiTwo = UInt8(ascii: "2") private let asciiThree = UInt8(ascii: "3") private let asciiFour = UInt8(ascii: "4") private let asciiFive = UInt8(ascii: "5") private let asciiSix = UInt8(ascii: "6") private let asciiSeven = UInt8(ascii: "7") private let asciiEight = UInt8(ascii: "8") private let asciiNine = UInt8(ascii: "9") private let asciiMinus = UInt8(ascii: "-") private let asciiPlus = UInt8(ascii: "+") private let asciiEquals = UInt8(ascii: "=") private let asciiColon = UInt8(ascii: ":") private let asciiComma = UInt8(ascii: ",") private let asciiDoubleQuote = UInt8(ascii: "\"") private let asciiBackslash = UInt8(ascii: "\\") private let asciiForwardSlash = UInt8(ascii: "/") private let asciiOpenSquareBracket = UInt8(ascii: "[") private let asciiCloseSquareBracket = UInt8(ascii: "]") private let asciiOpenCurlyBracket = UInt8(ascii: "{") private let asciiCloseCurlyBracket = UInt8(ascii: "}") private let asciiUpperA = UInt8(ascii: "A") private let asciiUpperB = UInt8(ascii: "B") private let asciiUpperC = UInt8(ascii: "C") private let asciiUpperD = UInt8(ascii: "D") private let asciiUpperE = UInt8(ascii: "E") private let asciiUpperF = UInt8(ascii: "F") private let asciiUpperZ = UInt8(ascii: "Z") private let asciiLowerA = UInt8(ascii: "a") private let asciiLowerZ = UInt8(ascii: "z") private let base64Digits: [UInt8] = { var digits = [UInt8]() digits.append(contentsOf: asciiUpperA...asciiUpperZ) digits.append(contentsOf: asciiLowerA...asciiLowerZ) digits.append(contentsOf: asciiZero...asciiNine) digits.append(asciiPlus) digits.append(asciiForwardSlash) return digits }() private let hexDigits: [UInt8] = { var digits = [UInt8]() digits.append(contentsOf: asciiZero...asciiNine) digits.append(contentsOf: asciiUpperA...asciiUpperF) return digits }() internal struct JSONEncoder { private var data = [UInt8]() private var separator: UInt8? internal init() {} internal var dataResult: Data { return Data(data) } internal var stringResult: String { get { return String(bytes: data, encoding: String.Encoding.utf8)! } } /// Append a `StaticString` to the JSON text. Because /// `StaticString` is already UTF8 internally, this is faster /// than appending a regular `String`. internal mutating func append(staticText: StaticString) { let buff = UnsafeBufferPointer(start: staticText.utf8Start, count: staticText.utf8CodeUnitCount) data.append(contentsOf: buff) } /// Append a `_NameMap.Name` to the JSON text surrounded by quotes. /// As with StaticString above, a `_NameMap.Name` provides pre-converted /// UTF8 bytes, so this is much faster than appending a regular /// `String`. internal mutating func appendQuoted(name: _NameMap.Name) { data.append(asciiDoubleQuote) data.append(contentsOf: name.utf8Buffer) data.append(asciiDoubleQuote) } /// Append a `String` to the JSON text. internal mutating func append(text: String) { data.append(contentsOf: text.utf8) } /// Append a raw utf8 in a `Data` to the JSON text. internal mutating func append(utf8Data: Data) { data.append(contentsOf: utf8Data) } /// Begin a new field whose name is given as a `_NameMap.Name` internal mutating func startField(name: _NameMap.Name) { if let s = separator { data.append(s) } appendQuoted(name: name) data.append(asciiColon) separator = asciiComma } /// Begin a new field whose name is given as a `String`. internal mutating func startField(name: String) { if let s = separator { data.append(s) } data.append(asciiDoubleQuote) // Can avoid overhead of putStringValue, since // the JSON field names are always clean ASCII. data.append(contentsOf: name.utf8) append(staticText: "\":") separator = asciiComma } /// Begin a new extension field internal mutating func startExtensionField(name: String) { if let s = separator { data.append(s) } append(staticText: "\"[") data.append(contentsOf: name.utf8) append(staticText: "]\":") separator = asciiComma } /// Append an open square bracket `[` to the JSON. internal mutating func startArray() { data.append(asciiOpenSquareBracket) separator = nil } /// Append a close square bracket `]` to the JSON. internal mutating func endArray() { data.append(asciiCloseSquareBracket) separator = asciiComma } /// Append a comma `,` to the JSON. internal mutating func comma() { data.append(asciiComma) } /// Append an open curly brace `{` to the JSON. /// Assumes this object is part of an array of objects. internal mutating func startArrayObject() { if let s = separator { data.append(s) } data.append(asciiOpenCurlyBracket) separator = nil } /// Append an open curly brace `{` to the JSON. internal mutating func startObject() { data.append(asciiOpenCurlyBracket) separator = nil } /// Append a close curly brace `}` to the JSON. internal mutating func endObject() { data.append(asciiCloseCurlyBracket) separator = asciiComma } /// Write a JSON `null` token to the output. internal mutating func putNullValue() { append(staticText: "null") } /// Append a float value to the output. /// This handles Nan and infinite values by /// writing well-known string values. internal mutating func putFloatValue(value: Float) { if value.isNaN { append(staticText: "\"NaN\"") } else if !value.isFinite { if value < 0 { append(staticText: "\"-Infinity\"") } else { append(staticText: "\"Infinity\"") } } else { data.append(contentsOf: value.debugDescription.utf8) } } /// Append a double value to the output. /// This handles Nan and infinite values by /// writing well-known string values. internal mutating func putDoubleValue(value: Double) { if value.isNaN { append(staticText: "\"NaN\"") } else if !value.isFinite { if value < 0 { append(staticText: "\"-Infinity\"") } else { append(staticText: "\"Infinity\"") } } else { data.append(contentsOf: value.debugDescription.utf8) } } /// Append a UInt64 to the output (without quoting). private mutating func appendUInt(value: UInt64) { if value >= 10 { appendUInt(value: value / 10) } data.append(asciiZero + UInt8(value % 10)) } /// Append an Int64 to the output (without quoting). private mutating func appendInt(value: Int64) { if value < 0 { data.append(asciiMinus) // This is the twos-complement negation of value, // computed in a way that won't overflow a 64-bit // signed integer. appendUInt(value: 1 + ~UInt64(bitPattern: value)) } else { appendUInt(value: UInt64(bitPattern: value)) } } /// Write an Enum as an int. internal mutating func putEnumInt(value: Int) { appendInt(value: Int64(value)) } /// Write an `Int64` using protobuf JSON quoting conventions. internal mutating func putInt64(value: Int64) { data.append(asciiDoubleQuote) appendInt(value: value) data.append(asciiDoubleQuote) } /// Write an `Int32` with quoting suitable for /// using the value as a map key. internal mutating func putQuotedInt32(value: Int32) { data.append(asciiDoubleQuote) appendInt(value: Int64(value)) data.append(asciiDoubleQuote) } /// Write an `Int32` in the default format. internal mutating func putInt32(value: Int32) { appendInt(value: Int64(value)) } /// Write a `UInt64` using protobuf JSON quoting conventions. internal mutating func putUInt64(value: UInt64) { data.append(asciiDoubleQuote) appendUInt(value: value) data.append(asciiDoubleQuote) } /// Write a `UInt32` with quoting suitable for /// using the value as a map key. internal mutating func putQuotedUInt32(value: UInt32) { data.append(asciiDoubleQuote) appendUInt(value: UInt64(value)) data.append(asciiDoubleQuote) } /// Write a `UInt32` in the default format. internal mutating func putUInt32(value: UInt32) { appendUInt(value: UInt64(value)) } /// Write a `Bool` with quoting suitable for /// using the value as a map key. internal mutating func putQuotedBoolValue(value: Bool) { data.append(asciiDoubleQuote) putBoolValue(value: value) data.append(asciiDoubleQuote) } /// Write a `Bool` in the default format. internal mutating func putBoolValue(value: Bool) { if value { append(staticText: "true") } else { append(staticText: "false") } } /// Append a string value escaping special characters as needed. internal mutating func putStringValue(value: String) { data.append(asciiDoubleQuote) for c in value.unicodeScalars { switch c.value { // Special two-byte escapes case 8: append(staticText: "\\b") case 9: append(staticText: "\\t") case 10: append(staticText: "\\n") case 12: append(staticText: "\\f") case 13: append(staticText: "\\r") case 34: append(staticText: "\\\"") case 92: append(staticText: "\\\\") case 0...31, 127...159: // Hex form for C0 control chars append(staticText: "\\u00") data.append(hexDigits[Int(c.value / 16)]) data.append(hexDigits[Int(c.value & 15)]) case 23...126: data.append(UInt8(truncatingIfNeeded: c.value)) case 0x80...0x7ff: data.append(0xc0 + UInt8(truncatingIfNeeded: c.value >> 6)) data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f)) case 0x800...0xffff: data.append(0xe0 + UInt8(truncatingIfNeeded: c.value >> 12)) data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 6) & 0x3f)) data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f)) default: data.append(0xf0 + UInt8(truncatingIfNeeded: c.value >> 18)) data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 12) & 0x3f)) data.append(0x80 + UInt8(truncatingIfNeeded: (c.value >> 6) & 0x3f)) data.append(0x80 + UInt8(truncatingIfNeeded: c.value & 0x3f)) } } data.append(asciiDoubleQuote) } /// Append a bytes value using protobuf JSON Base-64 encoding. internal mutating func putBytesValue(value: Data) { data.append(asciiDoubleQuote) if value.count > 0 { value.withUnsafeBytes { (body: UnsafeRawBufferPointer) in if let p = body.baseAddress, body.count > 0 { var t: Int = 0 var bytesInGroup: Int = 0 for i in 0..<body.count { if bytesInGroup == 3 { data.append(base64Digits[(t >> 18) & 63]) data.append(base64Digits[(t >> 12) & 63]) data.append(base64Digits[(t >> 6) & 63]) data.append(base64Digits[t & 63]) t = 0 bytesInGroup = 0 } t = (t << 8) + Int(p[i]) bytesInGroup += 1 } switch bytesInGroup { case 3: data.append(base64Digits[(t >> 18) & 63]) data.append(base64Digits[(t >> 12) & 63]) data.append(base64Digits[(t >> 6) & 63]) data.append(base64Digits[t & 63]) case 2: t <<= 8 data.append(base64Digits[(t >> 18) & 63]) data.append(base64Digits[(t >> 12) & 63]) data.append(base64Digits[(t >> 6) & 63]) data.append(asciiEquals) case 1: t <<= 16 data.append(base64Digits[(t >> 18) & 63]) data.append(base64Digits[(t >> 12) & 63]) data.append(asciiEquals) data.append(asciiEquals) default: break } } } } data.append(asciiDoubleQuote) } }
apache-2.0
1723e5d3122bbda7a4b806a50ba08d67
34.510363
104
0.582184
4.389049
false
false
false
false
ttilley/docopt.swift
Sources/String.swift
1
3564
// // String.swift // docopt // // Created by Pavel S. Mazurin on 2/28/15. // Copyright (c) 2015 kovpas. All rights reserved. // import Foundation internal extension String { func partition(_ separator: String) -> (String, String, String) { let components = self.components(separatedBy: separator) if components.count > 1 { return (components[0], separator, components[1..<components.count].joined(separator: separator)) } return (self, "", "") } func strip() -> String { return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } func findAll(_ regex: String, flags: NSRegularExpression.Options) -> [String] { let re = try! NSRegularExpression(pattern: regex, options: flags) let all = NSMakeRange(0, self.characters.count) let matches = re.matches(in: self, options: [], range: all) return matches.map {self[$0.rangeAt(1)].strip()} } func split() -> [String] { return self.characters.split(whereSeparator: {$0 == " " || $0 == "\n"}).map(String.init) } func split(_ regex: String) -> [String] { let re = try! NSRegularExpression(pattern: regex, options: .dotMatchesLineSeparators) let all = NSMakeRange(0, self.characters.count) var result = [String]() let matches = re.matches(in: self, options: [], range: all) if matches.count > 0 { var lastEnd = 0 for match in matches { let range = match.rangeAt(1) if range.location != NSNotFound { if (lastEnd != 0) { result.append(self[lastEnd..<match.range.location]) } else if range.location == 0 { // from python docs: If there are capturing groups in the separator and it matches at the start of the string, // the result will start with an empty string. The same holds for the end of the string: result.append("") } result.append(self[range]) lastEnd = range.location + range.length if lastEnd == self.characters.count { // from python docs: If there are capturing groups in the separator and it matches at the start of the string, // the result will start with an empty string. The same holds for the end of the string: result.append("") } } else { result.append(self[lastEnd..<match.range.location]) lastEnd = match.range.location + match.range.length } } if lastEnd != self.characters.count { result.append(self[lastEnd..<self.characters.count]) } return result } return [self] } func isupper() -> Bool { let charset = CharacterSet.uppercaseLetters.inverted return self.rangeOfCharacter(from: charset) == nil } subscript(i: Int) -> Character { return self[characters.index(startIndex, offsetBy: i)] } subscript(range: Range<Int>) -> String { return self[characters.index(startIndex, offsetBy: range.lowerBound)..<characters.index(startIndex, offsetBy: range.upperBound)] } subscript(range: NSRange) -> String { return self[range.location..<range.location + range.length] } }
mit
7d637a2aa38cfbcef85b7c4d2c7c4fd9
38.6
136
0.561167
4.714286
false
false
false
false
rnapier/SwiftCheck
SwiftCheck/Modifiers.swift
1
10943
// // Modifiers.swift // SwiftCheck // // Created by Robert Widmann on 1/29/15. // Copyright (c) 2015 CodaFi. All rights reserved. // /// For types that either do not have a Printable instance or that wish to have no description to /// print, Blind will create a default description for them. public struct Blind<A : Arbitrary> : Arbitrary, Printable { public let getBlind : A public init(_ blind : A) { self.getBlind = blind } public var description : String { return "(*)" } private static func create(blind : A) -> Blind<A> { return Blind(blind) } public static func arbitrary() -> Gen<Blind<A>> { return A.arbitrary().fmap(Blind.create) } public static func shrink(bl : Blind<A>) -> [Blind<A>] { return A.shrink(bl.getBlind).map(Blind.create) } } extension Blind : CoArbitrary { // Take the lazy way out. public static func coarbitrary<C>(x : Blind) -> (Gen<C> -> Gen<C>) { return coarbitraryPrintable(x) } } /// Guarantees test cases for its underlying type will not be shrunk. public struct Static<A : Arbitrary> : Arbitrary, Printable { public let getStatic : A public init(_ fixed : A) { self.getStatic = fixed } public var description : String { return "Static( \(self.getStatic) )" } private static func create(blind : A) -> Static<A> { return Static(blind) } public static func arbitrary() -> Gen<Static<A>> { return A.arbitrary().fmap(Static.create) } public static func shrink(bl : Static<A>) -> [Static<A>] { return [] } } extension Static : CoArbitrary { // Take the lazy way out. public static func coarbitrary<C>(x : Static) -> (Gen<C> -> Gen<C>) { return coarbitraryPrintable(x) } } /// Generates an array of arbitrary values of type A. public struct ArrayOf<A : Arbitrary> : Arbitrary, Printable { public let getArray : [A] public var getContiguousArray : ContiguousArray<A> { return ContiguousArray(self.getArray) } public init(_ array : [A]) { self.getArray = array } public var description : String { return "\(self.getArray)" } private static func create(array : [A]) -> ArrayOf<A> { return ArrayOf(array) } public static func arbitrary() -> Gen<ArrayOf<A>> { return Gen.sized { n in return Gen<Int>.choose((0, n)).bind { k in if k == 0 { return Gen.pure(ArrayOf([])) } return sequence(Array((0...k)).map { _ in A.arbitrary() }).fmap(ArrayOf.create) } } } public static func shrink(bl : ArrayOf<A>) -> [ArrayOf<A>] { let n = bl.getArray.count let xs = Int.shrink(n).reverse().flatMap({ k in removes(k + 1, n, bl.getArray) }) + shrinkOne(bl.getArray) return xs.map({ ArrayOf($0) }) } } extension ArrayOf : CoArbitrary { public static func coarbitrary<C>(x : ArrayOf) -> (Gen<C> -> Gen<C>) { let a = x.getArray if a.isEmpty { return { $0.variant(0) } } return { $0.variant(1) } • ArrayOf.coarbitrary(ArrayOf([A](a[1..<a.endIndex]))) } } private func removes<A : Arbitrary>(k : Int, n : Int, xs : [A]) -> [[A]] { let xs1 = take(k, xs) let xs2 = drop(k, xs) if k > n { return [] } else if xs2.isEmpty { return [[]] } else { return [xs2] + removes(k, n - k, xs2).map({ xs1 + $0 }) } } private func shrinkOne<A : Arbitrary>(xs : [A]) -> [[A]] { if xs.isEmpty { return [] } else if let x = xs.first { let xss = [A](xs[1..<xs.endIndex]) let a = A.shrink(x).map({ [$0] + xss }) let b = shrinkOne(xss).map({ [x] + $0 }) return a + b } fatalError("Array could not produce a first element") } func take<T>(num : Int, xs : [T]) -> [T] { let n = (num < xs.count) ? num : xs.count return [T](xs[0..<n]) } func drop<T>(num : Int, xs : [T]) -> [T] { let n = (num < xs.count) ? num : xs.count return [T](xs[n..<xs.endIndex]) } /// Generates an dictionary of arbitrary keys and values. public struct DictionaryOf<K : protocol<Hashable, Arbitrary>, V : Arbitrary> : Arbitrary, Printable { public let getDictionary : Dictionary<K, V> public init(_ dict : Dictionary<K, V>) { self.getDictionary = dict } public var description : String { return "\(self.getDictionary)" } private static func create(dict : Dictionary<K, V>) -> DictionaryOf<K, V> { return DictionaryOf(dict) } public static func arbitrary() -> Gen<DictionaryOf<K, V>> { return ArrayOf<K>.arbitrary().bind { k in return ArrayOf<V>.arbitrary().bind { v in return Gen.pure(DictionaryOf(Dictionary<K, V>(Zip2(k.getArray, v.getArray)))) } } } public static func shrink(d : DictionaryOf<K, V>) -> [DictionaryOf<K, V>] { var xs = [DictionaryOf<K, V>]() for (k, v) in d.getDictionary { xs.append(DictionaryOf(Dictionary(Zip2(K.shrink(k), V.shrink(v))))) } return xs } } extension DictionaryOf : CoArbitrary { public static func coarbitrary<C>(x : DictionaryOf) -> (Gen<C> -> Gen<C>) { if x.getDictionary.isEmpty { return { $0.variant(0) } } return { $0.variant(1) } } } extension Dictionary { init<S : SequenceType where S.Generator.Element == Element>(_ pairs : S) { self.init() var g = pairs.generate() while let (k : Key, v : Value) = g.next() { self[k] = v } } } /// Generates an Optional of arbitrary values of type A. public struct OptionalOf<A : Arbitrary> : Arbitrary, Printable { public let getOptional : A? public init(_ opt : A?) { self.getOptional = opt } public var description : String { return "\(self.getOptional)" } private static func create(opt : A?) -> OptionalOf<A> { return OptionalOf(opt) } public static func arbitrary() -> Gen<OptionalOf<A>> { return Gen.frequency([ (1, Gen.pure(OptionalOf(Optional<A>.None))), (3, liftM({ OptionalOf(Optional<A>.Some($0)) })(m1: A.arbitrary())) ]) } public static func shrink(bl : OptionalOf<A>) -> [OptionalOf<A>] { if let x = bl.getOptional { return [OptionalOf(Optional<A>.None)] + A.shrink(x).map({ OptionalOf(Optional<A>.Some($0)) }) } return [] } } extension OptionalOf : CoArbitrary { public static func coarbitrary<C>(x : OptionalOf) -> (Gen<C> -> Gen<C>) { if let _ = x.getOptional { return { $0.variant(0) } } return { $0.variant(1) } } } /// Generates a set of arbitrary values of type A. public struct SetOf<A : protocol<Hashable, Arbitrary>> : Arbitrary, Printable { public let getSet : Set<A> public init(_ set : Set<A>) { self.getSet = set } public var description : String { return "\(self.getSet)" } private static func create(set : Set<A>) -> SetOf<A>{ return SetOf(set) } public static func arbitrary() -> Gen<SetOf<A>> { return Gen.sized { n in return Gen<Int>.choose((0, n)).bind { k in if k == 0 { return Gen.pure(SetOf(Set([]))) } return sequence(Array((0...k)).map { _ in A.arbitrary() }).fmap({ SetOf.create(Set($0)) }) } } } public static func shrink(s : SetOf<A>) -> [SetOf<A>] { return ArrayOf.shrink(ArrayOf([A](s.getSet))).map({ SetOf(Set($0.getArray)) }) } } extension SetOf : CoArbitrary { public static func coarbitrary<C>(x : SetOf) -> (Gen<C> -> Gen<C>) { if x.getSet.isEmpty { return { $0.variant(0) } } return { $0.variant(1) } } } /// Generates a Swift function from T to U. public struct ArrowOf<T : protocol<Hashable, CoArbitrary>, U : Arbitrary> : Arbitrary, Printable { private var table : Dictionary<T, U> private var arr : T -> U public var getArrow : T -> U { return self.arr } private init (_ table : Dictionary<T, U>, _ arr : (T -> U)) { self.table = table self.arr = arr } public init(_ arr : (T -> U)) { self.init(Dictionary(), { (_ : T) -> U in return undefined() }) self.arr = { x in if let v = self.table[x] { return v } let y = arr(x) self.table[x] = y return y } } public var description : String { return "\(T.self) -> \(U.self)" } private static func create(arr : (T -> U)) -> ArrowOf<T, U> { return ArrowOf(arr) } public static func arbitrary() -> Gen<ArrowOf<T, U>> { return promote({ a in return T.coarbitrary(a)(U.arbitrary()) }).fmap({ ArrowOf($0) }) } public static func shrink(f : ArrowOf<T, U>) -> [ArrowOf<T, U>] { var xxs : [ArrowOf<T, U>] = [] for (x, y) in f.table { xxs += U.shrink(y).map({ (y2 : U) -> ArrowOf<T, U> in return ArrowOf<T, U>({ (z : T) -> U in if x == z { return y2 } return f.arr(z) }) }) } return xxs } } private func undefined<A>() -> A { fatalError("") } /// Guarantees that every generated integer is greater than 0. public struct Positive<A : protocol<Arbitrary, SignedNumberType>> : Arbitrary, Printable { public let getPositive : A public init(_ pos : A) { self.getPositive = pos } public var description : String { return "Positive( \(self.getPositive) )" } private static func create(blind : A) -> Positive<A> { return Positive(blind) } public static func arbitrary() -> Gen<Positive<A>> { return A.arbitrary().fmap({ Positive.create(abs($0)) }).suchThat({ $0.getPositive > 0 }) } public static func shrink(bl : Positive<A>) -> [Positive<A>] { return A.shrink(bl.getPositive).filter({ $0 > 0 }).map({ Positive($0) }) } } extension Positive : CoArbitrary { // Take the lazy way out. public static func coarbitrary<C>(x : Positive) -> (Gen<C> -> Gen<C>) { return coarbitraryPrintable(x) } } /// Guarantees that every generated integer is never 0. public struct NonZero<A : protocol<Arbitrary, IntegerType>> : Arbitrary, Printable { public let getNonZero : A public init(_ non : A) { self.getNonZero = non } public var description : String { return "NonZero( \(self.getNonZero) )" } private static func create(blind : A) -> NonZero<A> { return NonZero(blind) } public static func arbitrary() -> Gen<NonZero<A>> { return A.arbitrary().suchThat({ $0 != 0 }).fmap(NonZero.create) } public static func shrink(bl : NonZero<A>) -> [NonZero<A>] { return A.shrink(bl.getNonZero).filter({ $0 != 0 }).map({ NonZero($0) }) } } extension NonZero : CoArbitrary { public static func coarbitrary<C>(x : NonZero) -> (Gen<C> -> Gen<C>) { return coarbitraryIntegral(x.getNonZero) } } /// Guarantees that every generated integer is greater than or equal to 0. public struct NonNegative<A : protocol<Arbitrary, IntegerType>> : Arbitrary, Printable { public let getNonNegative : A public init(_ non : A) { self.getNonNegative = non } public var description : String { return "NonNegative( \(self.getNonNegative) )" } private static func create(blind : A) -> NonNegative<A> { return NonNegative(blind) } public static func arbitrary() -> Gen<NonNegative<A>> { return A.arbitrary().suchThat({ $0 >= 0 }).fmap(NonNegative.create) } public static func shrink(bl : NonNegative<A>) -> [NonNegative<A>] { return A.shrink(bl.getNonNegative).filter({ $0 >= 0 }).map({ NonNegative($0) }) } } extension NonNegative : CoArbitrary { public static func coarbitrary<C>(x : NonNegative) -> (Gen<C> -> Gen<C>) { return coarbitraryIntegral(x.getNonNegative) } }
mit
fe4c32a552fceb5dcc5e8b971ebb01fe
23.641892
108
0.632758
2.958626
false
false
false
false
mz2/AmazonS3RequestManager
Source/AmazonS3RequestManager/ACL.swift
1
10915
// // AmazonS3ACL.swift // AmazonS3RequestManager // // Created by Anthony Miller. 2015. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// MARK: - Constants private let AmazonS3PredefinedACLHeaderKey = "x-amz-acl" /** MARK: - AmazonS3ACL Protocol An object conforming to the `AmazonS3ACL` protocol describes an access control list (ACL) that can be used by `AmazonS3RequestManager` to set the ACL Headers for a request. */ public protocol ACL { /** This method should be implemented to set the ACL headers for the object. */ func setACLHeaders(on request: inout URLRequest) } /** MARK: - Predefined (Canned) ACLs. A list of predefined, or canned, ACLs recognized by the Amazon S3 service. :see: For more information on Predefined ACLs, see "http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl" - privateReadWrite: Owner gets full control. No one else has access rights. This is the default ACL for a new bucket/object. Applies to buckets and objects. - publicReadWrite: Owner gets full control. All other users (anonymous or authenticated) get READ and WRITE access. Granting this on a bucket is generally not recommended. Applies to buckets and objects. - publicReadOnly: Owner gets full control. All other users (anonymous or authenticated) get READ access. Applies to buckets and objects. - authenticatedReadOnly: Owner gets full control. All authenticated users get READ access. Applies to buckets and objects. - bucketOwnerReadOnly: Object owner gets full control. Bucket owner gets READ access. Applies to objects only; if you specify this canned ACL when creating a bucket, Amazon S3 ignores it. - bucketOwnerFullControl: Both the object owner and the bucket owner get full control over the object. Applies to objects only; if you specify this canned ACL when creating a bucket, Amazon S3 ignores it. - logDeliveryWrite: The `LogDelivery` group gets WRITE and READ_ACP permissions on the bucket. :see: For more information on logs, see "http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html" */ public enum PredefinedACL: String, ACL { case privateReadWrite = "private", publicReadWrite = "public-read-write", publicReadOnly = "public-read", authenticatedReadOnly = "authenticated-read", bucketOwnerReadOnly = "bucket-owner-read", bucketOwnerFullControl = "bucket-owner-full-control", logDeliveryWrite = "log-delivery-write" public func setACLHeaders(on request: inout URLRequest) { request.addValue(self.rawValue, forHTTPHeaderField: AmazonS3PredefinedACLHeaderKey) } } /** MARK: - ACL Permissions The list of permission types for the Amazon S3 Service :see: For more information on the access allowed by each permission, see "http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#permissions" - read: Allows grantee to list the objects in the bucket or read the object data and its metadata - write: Allows grantee to create, overwrite, and delete any object in the bucket. :note: This permission applies only to buckets. - readACL: Allows grantee to read the ACL for the bucket or object - writeACL: Allows grantee to write the ACL for the bucket or object - fullControl: Allows grantee the `read`, `write`, `readACL`, and `writeACL` permissions on the bucket or object */ public enum ACLPermission { case read, write, readACL, writeACL, fullControl var valueForRequestBody: String { switch (self) { case .read: return "READ" case .write: return "WRITE" case .readACL: return "READ_ACP" case .writeACL: return "WRITE_ACP" case .fullControl: return "FULL_CONTROL" } } var requestHeaderFieldKey: String { switch (self) { case .read: return "x-amz-grant-read" case .write: return "x-amz-grant-write" case .readACL: return "x-amz-grant-read-acp" case .writeACL: return "x-amz-grant-write-acp" case .fullControl: return "x-amz-grant-full-control" } } } /** MARK: - ACL Grantees Defines a grantee to assign to a permission. A grantee can be an AWS account or one of the predefined Amazon S3 groups. You grant permission to an AWS account by the email address or the canonical user ID. :note: If you provide an email in your grant request, Amazon S3 finds the canonical user ID for that account and adds it to the ACL. The resulting ACLs will always contain the canonical user ID for the AWS account, not the AWS account's email address. :see: For more information on Amazon S3 Service grantees, see "http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#specifying-grantee" - authenticatedUsers: This group represents all AWS accounts. Access permission to this group allows any AWS account to access the resource. However, all requests must be signed (authenticated). - allUsers: Access permission to this group allows anyone to access the resource. The requests can be signed (authenticated) or unsigned (anonymous). Unsigned requests omit the Authentication header in the request. - logDeliveryGroup: WRITE permission on a bucket enables this group to write server access logs to the bucket. :see: For more information on the log delivery group, see "http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html" - emailAddress: A grantee for the AWS account with the given email address. - userID: A grantee for the AWS account with the given canonical user ID. */ public enum ACLGrantee: Hashable { case authenticatedUsers, allUsers, logDeliveryGroup, emailAddress(String), userID(String) var requestHeaderFieldValue: String { switch (self) { case .authenticatedUsers: return "uri=\"http://acs.amazonaws.com/groups/global/AuthenticatedUsers\"" case .allUsers: return "uri=\"http://acs.amazonaws.com/groups/global/AllUsers\"" case .logDeliveryGroup: return "uri=\"http://acs.amazonaws.com/groups/s3/LogDelivery\"" case .emailAddress(let email): return "emailAddress=\"\(email)\"" case .userID(let id): return "id=\"\(id)\"" } } public func hash(into hasher: inout Hasher) { hasher.combine(requestHeaderFieldValue) } } public func ==(lhs: ACLGrantee, rhs: ACLGrantee) -> Bool { return lhs.hashValue == rhs.hashValue } /** MARK: - ACL Permission Grants An `AmazonS3PermissionGrant` represents a grant for a single permission to a list of grantees. */ public struct ACLPermissionGrant: ACL, Hashable { /** Creates a grant with the given permission for a `Set` of grantees - parameter permission: The `ACLPermission` to set for the `grantees` - parameter grantees: The `Set` of `ACLGrantees` to set the permission for - returns: An grant for the given permission and grantees */ public init(permission: ACLPermission, grantees: Set<ACLGrantee>) { self.permission = permission self.grantees = grantees } /** Creates a grant with the given permission for a single grantee - parameter permission: The `ACLPermission` to set for the `grantee` - parameter grantees: The single `ACLGrantees` to set the permission for - returns: An grant for the given permission and grantees */ public init(permission: ACLPermission, grantee: ACLGrantee) { self.permission = permission self.grantees = [grantee] } /// The permission for the grant fileprivate(set) public var permission: ACLPermission /// The set of grantees for the grant fileprivate(set) public var grantees: Set<ACLGrantee> public func setACLHeaders(on request: inout URLRequest) { let granteeList = granteeStrings().joined(separator: ", ") request.addValue(granteeList, forHTTPHeaderField: permission.requestHeaderFieldKey) } fileprivate func granteeStrings() -> [String] { var strings: [String] = [] for grantee in grantees { strings.append(grantee.requestHeaderFieldValue) } return strings } public func hash(into hasher: inout Hasher) { hasher.combine(permission) } } public func ==(lhs: ACLPermissionGrant, rhs: ACLPermissionGrant) -> Bool { return lhs.permission == rhs.permission } /** MARK: - Custom ACLs An `CustomACL` contains an array of `ACLPermissionGrant`s and can be used to create a custom access control list (ACL). :note: The Amazon S3 Service accepts a maximum of 100 permission grants per bucket/object. */ public struct CustomACL: ACL { /** The set of `AmazonS3ACLPermissionGrants` to use for the access control list :note: Only one `AmazonS3PermissionGrant` can be added to the set for each `AmazonS3ACLPermission` type. Each permission may map to multiple grantees. */ public var grants: Set<ACLPermissionGrant> /** Initializes an `AmazonS3CustomACL` with a given array of `AmazonS3PermissionGrant`s. - parameter grant: The grants for the custom ACL - returns: An `AmazonS3CustomACL` with the given grants */ public init(grants: Set<ACLPermissionGrant>) { self.grants = grants } public func setACLHeaders(on request: inout URLRequest) { for grant in grants { grant.setACLHeaders(on: &request) } } }
mit
ef778438d7349684da92c7a76632937a
35.875
252
0.68841
4.410101
false
false
false
false
vector-im/vector-ios
Riot/Modules/Spaces/SpaceMembers/SpaceMembersCoordinator.swift
1
9202
// File created from FlowTemplate // $ createRootCoordinator.sh Spaces/SpaceMembers SpaceMemberList ShowSpaceMemberList /* Copyright 2021 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit struct SpaceMembersCoordinatorParameters { let userSessionsService: UserSessionsService let session: MXSession let spaceId: String let navigationRouter: NavigationRouterType init(userSessionsService: UserSessionsService, session: MXSession, spaceId: String, navigationRouter: NavigationRouterType = NavigationRouter(navigationController: RiotNavigationController())) { self.userSessionsService = userSessionsService self.session = session self.spaceId = spaceId self.navigationRouter = navigationRouter } } @objcMembers final class SpaceMembersCoordinator: SpaceMembersCoordinatorType { // MARK: - Properties // MARK: Private private let parameters: SpaceMembersCoordinatorParameters private let navigationRouter: NavigationRouterType private weak var memberDetailCoordinator: SpaceMemberDetailCoordinator? // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: SpaceMembersCoordinatorDelegate? // MARK: - Setup init(parameters: SpaceMembersCoordinatorParameters) { self.parameters = parameters self.navigationRouter = parameters.navigationRouter } // MARK: - Public methods func start() { let rootCoordinator = self.createSpaceMemberListCoordinator() rootCoordinator.start() self.add(childCoordinator: rootCoordinator) if self.navigationRouter.modules.isEmpty { self.navigationRouter.setRootModule(rootCoordinator) } else { self.navigationRouter.push(rootCoordinator, animated: true) { self.remove(childCoordinator: rootCoordinator) } } } func toPresentable() -> UIViewController { return self.navigationRouter.toPresentable() } func presentMemberDetail(with member: MXRoomMember, from sourceView: UIView?) { let coordinator = self.createSpaceMemberDetailCoordinator(with: member) coordinator.start() self.add(childCoordinator: coordinator) self.memberDetailCoordinator = coordinator if UIDevice.current.isPhone { self.navigationRouter.push(coordinator.toPresentable(), animated: true) { if let memberDetailCoordinator = self.memberDetailCoordinator { self.remove(childCoordinator: memberDetailCoordinator) } } } else { let viewController = coordinator.toPresentable() viewController.modalPresentationStyle = .popover if let sourceView = sourceView, let popoverPresentationController = viewController.popoverPresentationController { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceView.bounds } self.navigationRouter.present(viewController, animated: true) } } // MARK: - Private methods private func createSpaceMemberListCoordinator() -> SpaceMemberListCoordinator { let coordinator = SpaceMemberListCoordinator(session: self.parameters.session, spaceId: self.parameters.spaceId) coordinator.delegate = self return coordinator } private func createSpaceMemberDetailCoordinator(with member: MXRoomMember) -> SpaceMemberDetailCoordinator { let parameters = SpaceMemberDetailCoordinatorParameters(userSessionsService: self.parameters.userSessionsService, member: member, session: self.parameters.session, spaceId: self.parameters.spaceId, showCancelMenuItem: false) let coordinator = SpaceMemberDetailCoordinator(parameters: parameters) coordinator.delegate = self return coordinator } private func navigateTo(roomWith roomId: String) { let roomDataSourceManager = MXKRoomDataSourceManager.sharedManager(forMatrixSession: self.parameters.session) roomDataSourceManager?.roomDataSource(forRoom: roomId, create: true, onComplete: { [weak self] roomDataSource in if let room = self?.parameters.session.room(withRoomId: roomId) { Analytics.shared.trackViewRoom(room) } let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) guard let roomViewController = storyboard.instantiateViewController(withIdentifier: "RoomViewControllerStoryboardId") as? RoomViewController else { return } self?.navigationRouter.push(roomViewController, animated: true, popCompletion: nil) roomViewController.displayRoom(roomDataSource) roomViewController.navigationItem.leftItemsSupplementBackButton = true roomViewController.showMissedDiscussionsBadge = false }) } } // MARK: - SpaceMemberListCoordinatorDelegate extension SpaceMembersCoordinator: SpaceMemberListCoordinatorDelegate { func spaceMemberListCoordinator(_ coordinator: SpaceMemberListCoordinatorType, didSelect member: MXRoomMember, from sourceView: UIView?) { self.presentMemberDetail(with: member, from: sourceView) } func spaceMemberListCoordinatorDidCancel(_ coordinator: SpaceMemberListCoordinatorType) { self.delegate?.spaceMembersCoordinatorDidCancel(self) } func spaceMemberListCoordinatorShowInvite(_ coordinator: SpaceMemberListCoordinatorType) { guard let space = parameters.session.spaceService.getSpace(withId: parameters.spaceId), let spaceRoom = space.room else { MXLog.error("[SpaceMembersCoordinator] spaceMemberListCoordinatorShowInvite: failed to find space with id \(parameters.spaceId)") return } spaceRoom.state { [weak self] roomState in guard let self = self else { return } guard let powerLevels = roomState?.powerLevels, let userId = self.parameters.session.myUserId else { MXLog.error("[SpaceMembersCoordinator] spaceMemberListCoordinatorShowInvite: failed to find powerLevels for room") return } let userPowerLevel = powerLevels.powerLevelOfUser(withUserID: userId) guard userPowerLevel >= powerLevels.invite else { let alert = UIAlertController(title: VectorL10n.spacesInvitePeople, message: VectorL10n.spaceInviteNotEnoughPermission, preferredStyle: .alert) alert.addAction(UIAlertAction(title: VectorL10n.ok, style: .default, handler: nil)) self.navigationRouter.present(alert, animated: true) return } let coordinator = ContactsPickerCoordinator(session: self.parameters.session, room: spaceRoom, initialSearchText: nil, actualParticipants: nil, invitedParticipants: nil, userParticipant: nil) coordinator.delegate = self coordinator.start() self.childCoordinators.append(coordinator) self.navigationRouter.present(coordinator.toPresentable(), animated: true) } } } // MARK: - ContactsPickerCoordinatorDelegate extension SpaceMembersCoordinator: ContactsPickerCoordinatorDelegate { func contactsPickerCoordinatorDidStartLoading(_ coordinator: ContactsPickerCoordinatorProtocol) { } func contactsPickerCoordinatorDidEndLoading(_ coordinator: ContactsPickerCoordinatorProtocol) { } func contactsPickerCoordinatorDidClose(_ coordinator: ContactsPickerCoordinatorProtocol) { remove(childCoordinator: coordinator) } } // MARK: - SpaceMemberDetailCoordinatorDelegate extension SpaceMembersCoordinator: SpaceMemberDetailCoordinatorDelegate { func spaceMemberDetailCoordinator(_ coordinator: SpaceMemberDetailCoordinatorType, showRoomWithId roomId: String) { if !UIDevice.current.isPhone, let memberDetailCoordinator = self.memberDetailCoordinator { memberDetailCoordinator.toPresentable().dismiss(animated: true, completion: { self.memberDetailCoordinator = nil self.navigateTo(roomWith: roomId) }) } else { self.navigateTo(roomWith: roomId) } } func spaceMemberDetailCoordinatorDidCancel(_ coordinator: SpaceMemberDetailCoordinatorType) { self.delegate?.spaceMembersCoordinatorDidCancel(self) } }
apache-2.0
5f0f84a1f221cc2e35040fc980711372
41.40553
232
0.706586
5.776522
false
false
false
false
sundeepgupta/chord
chord/RadarFactory.swift
1
1883
import CoreBluetooth import CoreLocation struct RadarFactory { static func radar(uuid: String) -> Radar? { guard let region = self.regionWithUuid(uuid) else { return nil } let locationManager = self.locationManager() let responder = RadarResponder() let proximityReaction = { (beaconId: BeaconId, proximity: Proximity) in let userInfo: [String: AnyObject] = ["beaconId": beaconId, "proximityString": proximity.toString()] NSNotificationCenter.defaultCenter().postNotificationName(NotificationName.proximityDidChange, object: nil, userInfo: userInfo) } let shouldSkipProbation = { (proximity: Proximity) -> Bool in return proximity == .InRange(.Immediate) } let radar = Radar( locationManager: locationManager, region: region, responder: responder, proximityReaction: proximityReaction, shouldSkipProbation: shouldSkipProbation ) locationManager.delegate = responder responder.delegate = radar return radar } // MARK: - Private private static func regionWithUuid(uuid: String) -> CLBeaconRegion? { guard let UUID = NSUUID(UUIDString: uuid) else { return nil } let region = CLBeaconRegion(proximityUUID: UUID, identifier: "Chord App") region.notifyEntryStateOnDisplay = true return region } private static func locationManager() -> CLLocationManager { let locationManager = CLLocationManager() locationManager.allowsBackgroundLocationUpdates = true locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers locationManager.pausesLocationUpdatesAutomatically = false return locationManager } }
apache-2.0
0bcd026e508c399a631a2ea718b7d8dd
34.528302
139
0.645247
6.035256
false
false
false
false
Acidburn0zzz/firefox-ios
StorageTests/TestSQLiteHistory.swift
1
65553
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @testable import Storage @testable import Client import XCTest class BaseHistoricalBrowserSchema: Schema { var name: String { return "BROWSER" } var version: Int { return -1 } func update(_ db: SQLiteDBConnection, from: Int) -> Bool { fatalError("Should never be called.") } func create(_ db: SQLiteDBConnection) -> Bool { return false } func drop(_ db: SQLiteDBConnection) -> Bool { return false } var supportsPartialIndices: Bool { let v = sqlite3_libversion_number() return v >= 3008000 // 3.8.0. } let oldFaviconsSQL = """ CREATE TABLE IF NOT EXISTS favicons ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE, width INTEGER, height INTEGER, type INTEGER NOT NULL, date REAL NOT NULL ) """ func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool { if let sql = sql { do { try db.executeChange(sql, withArgs: args) } catch { return false } } return true } func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool { for sql in queries { if let sql = sql { if !run(db, sql: sql) { return false } } } return true } func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql) { return false } } return true } } // Versions of BrowserSchema that we care about: // v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015. // This is when we first started caring about database versions. // // v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles. // // v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons. // // v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9. // // These tests snapshot the table creation code at each of these points. class BrowserSchemaV6: BaseHistoricalBrowserSchema { override var version: Int { return 6 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = Strings.BookmarksFolderTitleMobile let titleMenu = Strings.BookmarksFolderTitleMenu let titleToolbar = Strings.BookmarksFolderTitleToolbar let titleUnsorted = Strings.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func CreateHistoryTable() -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func CreateDomainsTable() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func CreateQueueTable() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let queries = [ // This used to be done by FaviconsTable. self.oldFaviconsSQL, CreateDomainsTable(), CreateHistoryTable(), visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, CreateQueueTable(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV7: BaseHistoricalBrowserSchema { override var version: Int { return 7 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = Strings.BookmarksFolderTitleMobile let titleMenu = Strings.BookmarksFolderTitleMenu let titleToolbar = Strings.BookmarksFolderTitleToolbar let titleUnsorted = Strings.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func getDomainsTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func getQueueTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let queries = [ // This used to be done by FaviconsTable. self.oldFaviconsSQL, getDomainsTableCreationString(), getHistoryTableCreationString(), visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV8: BaseHistoricalBrowserSchema { override var version: Int { return 8 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = Strings.BookmarksFolderTitleMobile let titleMenu = Strings.BookmarksFolderTitleMenu let titleToolbar = Strings.BookmarksFolderTitleToolbar let titleUnsorted = Strings.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func getDomainsTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func getQueueTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { let favicons = """ CREATE TABLE IF NOT EXISTS favicons ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE, width INTEGER, height INTEGER, type INTEGER NOT NULL, date REAL NOT NULL ) """ // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let queries: [String] = [ getDomainsTableCreationString(), getHistoryTableCreationString(), favicons, visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV10: BaseHistoricalBrowserSchema { override var version: Int { return 10 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = Strings.BookmarksFolderTitleMobile let titleMenu = Strings.BookmarksFolderTitleMenu let titleToolbar = Strings.BookmarksFolderTitleToolbar let titleUnsorted = Strings.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString(forVersion version: Int = BrowserSchema.DefaultVersion) -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func getDomainsTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func getQueueTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } func getBookmarksMirrorTableCreationString() -> String { // The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry. // For now we have the simplest possible schema: everything in one. let sql = """ CREATE TABLE IF NOT EXISTS bookmarksMirror -- Shared fields. ( id INTEGER PRIMARY KEY AUTOINCREMENT , guid TEXT NOT NULL UNIQUE -- Type enum. TODO: BookmarkNodeType needs to be extended. , type TINYINT NOT NULL -- Record/envelope metadata that'll allow us to do merges. -- Milliseconds. , server_modified INTEGER NOT NULL -- Boolean , is_deleted TINYINT NOT NULL DEFAULT 0 -- Boolean, 0 (false) if deleted. , hasDupe TINYINT NOT NULL DEFAULT 0 -- GUID , parentid TEXT , parentName TEXT -- Type-specific fields. These should be NOT NULL in many cases, but we're going -- for a sparse schema, so this'll do for now. Enforce these in the application code. -- LIVEMARKS , feedUri TEXT, siteUri TEXT -- SEPARATORS , pos INT -- FOLDERS, BOOKMARKS, QUERIES , title TEXT, description TEXT -- BOOKMARKS, QUERIES , bmkUri TEXT, tags TEXT, keyword TEXT -- QUERIES , folderName TEXT, queryId TEXT , CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1) , CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1) ) """ return sql } /** * We need to explicitly store what's provided by the server, because we can't rely on * referenced child nodes to exist yet! */ func getBookmarksMirrorStructureTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS bookmarksMirrorStructure ( parent TEXT NOT NULL REFERENCES bookmarksMirror(guid) ON DELETE CASCADE, -- Should be the GUID of a child. child TEXT NOT NULL, -- Should advance from 0. idx INTEGER NOT NULL ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { let favicons = """ CREATE TABLE IF NOT EXISTS favicons ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE, width INTEGER, height INTEGER, type INTEGER NOT NULL, date REAL NOT NULL ) """ // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let bookmarksMirror = getBookmarksMirrorTableCreationString() let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString() let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS idx_bookmarksMirrorStructure_parent_idx ON bookmarksMirrorStructure (parent, idx)" let queries: [String] = [ getDomainsTableCreationString(), getHistoryTableCreationString(), favicons, visits, bookmarks, bookmarksMirror, bookmarksMirrorStructure, indexStructureParentIdx, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class TestSQLiteHistory: XCTestCase { let files = MockFiles() fileprivate func deleteDatabases() { for v in ["6", "7", "8", "10", "6-data"] { do { try files.remove("browser-v\(v).db") } catch {} } do { try files.remove("browser.db") try files.remove("historysynced.db") } catch {} } override func tearDown() { super.tearDown() self.deleteDatabases() } override func setUp() { super.setUp() // Just in case tearDown didn't run or succeed last time! self.deleteDatabases() } // Test that our visit partitioning for frecency is correct. func testHistoryLocalAndRemoteVisits() { let db = BrowserDB(filename: "testHistoryLocalAndRemoteVisits.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let siteL = Site(url: "http://url1/", title: "title local only") let siteR = Site(url: "http://url2/", title: "title remote only") let siteB = Site(url: "http://url3/", title: "title local and remote") siteL.guid = "locallocal12" siteR.guid = "remoteremote" siteB.guid = "bothbothboth" let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link) let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link) let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link) let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link) let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link) let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link) let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link) let deferred = history.clearHistory() >>> { history.addLocalVisit(siteVisitL1) } >>> { history.addLocalVisit(siteVisitL2) } >>> { history.addLocalVisit(siteVisitBL1) } >>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) } >>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) } >>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) } // Do this step twice, so we exercise the dupe-visit handling. >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) } >>> { history.getFrecentHistory().getSites(matchingSearchQuery: nil, limit: 3) >>== { (sites: Cursor) -> Success in XCTAssertEqual(3, sites.count) // Two local visits beat a single later remote visit and one later local visit. // Two local visits beat three remote visits. XCTAssertEqual(siteL.guid!, sites[0]!.guid!) XCTAssertEqual(siteB.guid!, sites[1]!.guid!) XCTAssertEqual(siteR.guid!, sites[2]!.guid!) return succeed() } // This marks everything as modified so we can fetch it. >>> history.onRemovedAccount // Now check that we have no duplicate visits. >>> { history.getModifiedHistoryToUpload() >>== { (places) -> Success in if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) { XCTAssertEqual(3, visits.count) } else { XCTFail("Couldn't find site R.") } return succeed() } } } XCTAssertTrue(deferred.value.isSuccess) } func testUpgrades() { let sources: [(Int, Schema)] = [ (6, BrowserSchemaV6()), (7, BrowserSchemaV7()), (8, BrowserSchemaV8()), (10, BrowserSchemaV10()), ] let destination = BrowserSchema() for (version, schema) in sources { var db = BrowserDB(filename: "browser-v\(version).db", schema: schema, files: files) XCTAssertTrue(db.withConnection({ connection -> Int in connection.version }).value.successValue == schema.version, "Creating BrowserSchema at version \(version)") db.forceClose() db = BrowserDB(filename: "browser-v\(version).db", schema: destination, files: files) XCTAssertTrue(db.withConnection({ connection -> Int in connection.version }).value.successValue == destination.version, "Upgrading BrowserSchema from version \(version) to version \(schema.version)") db.forceClose() } } func testUpgradesWithData() { var db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchemaV6(), files: files) // Insert some data. let queries = [ "INSERT INTO domains (id, domain) VALUES (1, 'example.com')", "INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)", "INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)", "INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)", "INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)", "INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')" ] XCTAssertTrue(db.run(queries).value.isSuccess) // And we can upgrade to the current version. db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let results = history.getSitesByLastVisit(limit: 10, offset: 0).value.successValue XCTAssertNotNil(results) XCTAssertEqual(results![0]?.url, "http://www.example.com") db.forceClose() } func testDomainUpgrade() { let db = BrowserDB(filename: "testDomainUpgrade.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let site = Site(url: "http://www.example.com/test1.4", title: "title one") // Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden. let insertDeferred = db.withConnection { connection -> Void in try connection.executeChange("PRAGMA foreign_keys = OFF") let insert = "INSERT OR REPLACE INTO history (guid, url, title, local_modified, is_deleted, should_upload, domain_id) VALUES (?, ?, ?, ?, ?, ?, ?)" let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1] try connection.executeChange(insert, withArgs: args) } XCTAssertTrue(insertDeferred.value.isSuccess) // Now insert it again. This should update the domain. history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link)).succeeded() // domain_id isn't normally exposed, so we manually query to get it. let resultsDeferred = db.withConnection { connection -> Cursor<Int?> in let sql = "SELECT domain_id FROM history WHERE url = ?" let args: Args = [site.url] return connection.executeQuery(sql, factory: { $0[0] as? Int }, withArgs: args) } let results = resultsDeferred.value.successValue! let domain = results[0]! // Unwrap to get the first item from the cursor. XCTAssertNil(domain) } func testDomains() { let db = BrowserDB(filename: "testDomains.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let initialGuid = Bytes.generateGUID() let site11 = Site(url: "http://www.example.com/test1.1", title: "title one") let site12 = Site(url: "http://www.example.com/test1.2", title: "title two") let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three") let site3 = Site(url: "http://www.example2.com/test1", title: "title three") let expectation = self.expectation(description: "First.") let clearTopSites = "DELETE FROM cached_top_sites" let updateTopSites: [(String, Args?)] = [(clearTopSites, nil), (history.getFrecentHistory().updateTopSitesCacheQuery())] func countTopSites() -> Deferred<Maybe<Cursor<Int>>> { return db.runQuery("SELECT count(*) FROM cached_top_sites", args: nil, factory: { sdrow -> Int in return sdrow[0] as? Int ?? 0 }) } history.clearHistory().bind({ success in return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))]) }).bind({ (results: [Maybe<()>]) in return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds()) }).bind({ guid -> Success in XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct") return db.run(updateTopSites) }).bind({ success in XCTAssertTrue(success.isSuccess, "update was successful") return countTopSites() }).bind({ (count: Maybe<Cursor<Int>>) -> Success in XCTAssert(count.successValue![0] == 2, "2 sites returned") return history.removeSiteFromTopSites(site11) }).bind({ success -> Success in XCTAssertTrue(success.isSuccess, "Remove was successful") return db.run(updateTopSites) }).bind({ success -> Deferred<Maybe<Cursor<Int>>> in XCTAssertTrue(success.isSuccess, "update was successful") return countTopSites() }) .upon({ (count: Maybe<Cursor<Int>>) in XCTAssert(count.successValue![0] == 1, "1 site returned") expectation.fulfill() }) waitForExpectations(timeout: 10.0) { error in return } } func testHistoryIsSynced() { let db = BrowserDB(filename: "historysynced.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let initialGUID = Bytes.generateGUID() let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title") XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true) XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess) XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false) } // This is a very basic test. Adds an entry, retrieves it, updates it, // and then clears the database. func testHistoryTable() { let db = BrowserDB(filename: "testHistoryTable.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let site1 = Site(url: "http://url1/", title: "title one") let site1Changed = Site(url: "http://url1/", title: "title one alt") let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link) let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark) let site2 = Site(url: "http://url2/", title: "title two") let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getFrecentHistory().getSites(matchingSearchQuery: nil, limit: 10) >>== f } } func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getSitesByLastVisit(limit: 10, offset: 0) >>== f } } func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getFrecentHistory().getSites(matchingSearchQuery: filter, limit: 10) >>== f } } func checkDeletedCount(_ expected: Int) -> () -> Success { return { history.getDeletedHistoryToUpload() >>== { guids in XCTAssertEqual(expected, guids.count) return succeed() } } } history.clearHistory() >>> { history.addLocalVisit(siteVisit1) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1.title, sites[0]!.title) XCTAssertEqual(site1.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit2) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site1Changed.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit3) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(2, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site2.title, sites[1]!.title) return succeed() } >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(2, sites.count) // They're in order of date last visited. let first = sites[0]! let second = sites[1]! XCTAssertEqual(site2.title, first.title) XCTAssertEqual(site1Changed.title, second.title) XCTAssertTrue(siteVisit3.date == first.latestVisit!.date) return succeed() } >>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in XCTAssertEqual(1, sites.count) let first = sites[0]! XCTAssertEqual(site2.title, first.title) return succeed() } >>> checkDeletedCount(0) >>> { history.removeHistoryForURL("http://url2/") } >>> checkDeletedCount(1) >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) return succeed() } >>> { history.clearHistory() } >>> checkDeletedCount(0) >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> done waitForExpectations(timeout: 10.0) { error in return } } func testRemoveRecentHistory() { let db = BrowserDB(filename: "testRemoveRecentHistory.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) func delete(date: Date, expectedDeletions: Int) { history.clearHistory().succeeded() let siteL = Site(url: "http://url1/", title: "title local only") let siteR = Site(url: "http://url2/", title: "title remote only") let siteB = Site(url: "http://url3/", title: "title local and remote") siteL.guid = "locallocal12" siteR.guid = "remoteremote" siteB.guid = "bothbothboth" // Site visit uses microsec timestamp let siteVisitL1 = SiteVisit(site: siteL, date: 1_000_000, type: VisitType.link) let siteVisitL2 = SiteVisit(site: siteR, date: 2_000_000, type: VisitType.link) let siteVisitBL1 = SiteVisit(site: siteB, date: 4_000_000, type: VisitType.link) let deferred = history.addLocalVisit(siteVisitL1) >>> { history.addLocalVisit(siteVisitL2) } >>> { history.addLocalVisit(siteVisitBL1) } >>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) } >>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) } >>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) } XCTAssert(deferred.value.isSuccess) history.removeHistoryFromDate(date).succeeded() history.getDeletedHistoryToUpload() >>== { guids in XCTAssertEqual(expectedDeletions, guids.count) } } delete(date: Date(timeIntervalSinceNow: 0), expectedDeletions: 0) delete(date: Date(timeIntervalSince1970: 0), expectedDeletions: 3) delete(date: Date(timeIntervalSince1970: 3), expectedDeletions: 1) } func testRemoveHistoryForUrl() { let db = BrowserDB(filename: "testRemoveHistoryForUrl.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 3 sites that will have 4 local and 4 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 3) history.removeHistoryForURL("http://s0ite0.com/foo").succeeded() history.removeHistoryForURL("http://s1ite1.com/foo").succeeded() let deletedResult = history.getDeletedHistoryToUpload().value XCTAssertTrue(deletedResult.isSuccess) let guids = deletedResult.successValue! XCTAssertEqual(2, guids.count) } func testTopSitesFrecencyOrder() { let db = BrowserDB(filename: "testTopSitesFrecencyOrder.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 100 sites that will have 4 local and 4 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 100) // Create a new site thats for an existing domain but a different URL. let site = Site(url: "http://s\(5)ite\(5).com/foo-different-url", title: "A \(5) different url") site.guid = "abc\(5)defhi" history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded() // Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite! for i in 0...100 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)defhi") return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesFiltersGoogle() { let db = BrowserDB(filename: "testTopSitesFiltersGoogle.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 100) func createTopSite(url: String, guid: String) { let site = Site(url: url, title: "Hi") site.guid = guid history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded() // Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite! for i in 0...100 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } } createTopSite(url: "http://google.com", guid: "abcgoogle") // should not be a topsite createTopSite(url: "http://www.google.com", guid: "abcgoogle1") // should not be a topsite createTopSite(url: "http://google.co.za", guid: "abcgoogleza") // should not be a topsite createTopSite(url: "http://docs.google.com", guid: "docsgoogle") // should be a topsite let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites[0]?.guid, "docsgoogle") // google docs should be the first topsite // make sure all other google guids are not in the topsites array topSites.forEach { let guid: String = $0!.guid! // type checking is hard XCTAssertNil(["abcgoogle", "abcgoogle1", "abcgoogleza"].firstIndex(of: guid)) } XCTAssertEqual(topSites.count, 20) return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesCache() { let db = BrowserDB(filename: "testTopSitesCache.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Make sure that we get back the top sites populateHistoryForFrecencyCalculations(history, siteCount: 100) // Add extra visits to the 5th site to bubble it to the top of the top sites cache let site = Site(url: "http://s\(5)ite\(5).com/foo", title: "A \(5)") site.guid = "abc\(5)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } func invalidateIfNeededDoesntChangeResults() -> Success { return history.repopulate(invalidateTopSites: true) >>> { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } } func addVisitsToZerothSite() -> Success { let site = Site(url: "http://s\(0)ite\(0).com/foo", title: "A \(0)") site.guid = "abc\(0)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } return succeed() } func markInvalidation() -> Success { history.setTopSitesNeedsInvalidation() return succeed() } func checkSitesInvalidate() -> Success { history.repopulate(invalidateTopSites: true).succeeded() return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") XCTAssertEqual(topSites[1]!.guid, "abc\(0)def") return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> invalidateIfNeededDoesntChangeResults >>> markInvalidation >>> addVisitsToZerothSite >>> checkSitesInvalidate >>> done waitForExpectations(timeout: 10.0) { error in return } } func testPinnedTopSites() { let db = BrowserDB(filename: "testPinnedTopSites.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // add 2 sites to pinned topsite // get pinned site and make sure it exists in the right order // remove pinned sites // make sure pinned sites dont exist // create pinned sites. let site1 = Site(url: "http://s\(1)ite\(1).com/foo", title: "A \(1)") site1.id = 1 site1.guid = "abc\(1)def" addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now()) let site2 = Site(url: "http://s\(2)ite\(2).com/foo", title: "A \(2)") site2.id = 2 site2.guid = "abc\(2)def" addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now()) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func addPinnedSites() -> Success { return history.addPinnedTopSite(site1) >>== { sleep(1) // Sleep to prevent intermittent issue with sorting on the timestamp return history.addPinnedTopSite(site2) } } func checkPinnedSites() -> Success { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 2) XCTAssertEqual(pinnedSites[0]!.url, site2.url) XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last") return succeed() } } func removePinnedSites() -> Success { return history.removeFromPinnedTopSites(site2) >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site") XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left") return succeed() } } } func dupePinnedSite() -> Success { return history.addPinnedTopSite(site1) >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "There should not be a dupe") XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left") return succeed() } } } func removeHistory() -> Success { return history.clearHistory() >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "Pinned sites should exist after a history clear") return succeed() } } } addPinnedSites() >>> checkPinnedSites >>> removePinnedSites >>> dupePinnedSite >>> removeHistory >>> done waitForExpectations(timeout: 10.0) { error in return } } } class TestSQLiteHistoryTransactionUpdate: XCTestCase { func testUpdateInTransaction() { let files = MockFiles() let db = BrowserDB(filename: "testUpdateInTransaction.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.clearHistory().succeeded() let site = Site(url: "http://site/foo", title: "AA") site.guid = "abcdefghiabc" history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded() let ts: MicrosecondTimestamp = baseInstantInMicros let local = SiteVisit(site: site, date: ts, type: VisitType.link) XCTAssertTrue(history.addLocalVisit(local).value.isSuccess) // Doing it again is a no-op and will not fail. history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded() } }
mpl-2.0
e19cbfcca372a522090e7c4de357147f
38.729091
198
0.56542
5.122128
false
false
false
false
franklinsch/usagi
iOS/usagi-iOS/usagi-iOS/Project.swift
1
867
// // Project.swift // usagi-iOS // // Created by Franklin Schrans on 30/01/2016. // Copyright © 2016 Franklin Schrans. All rights reserved. // import Foundation class Project { var name: String var description: String var participants: [User] var subtasks: [Project] var dependsOnTasks = [Project]() var progress: Int var timeLeft: String var manager: User? init(name: String, description: String, participants: [User], subtasks: [Project], progress: Int, timeLeft: String, dependsOnTasks: [Project] = [], manager: User? = nil) { self.name = name self.description = description self.participants = participants self.subtasks = subtasks self.progress = progress self.timeLeft = timeLeft self.dependsOnTasks = dependsOnTasks self.manager = manager } }
mit
337eada4d602ea33b6a68218406b1616
26.935484
175
0.65127
4.143541
false
false
false
false
soapyigu/LeetCode_Swift
DFS/WordSearchII.swift
1
3382
/** * Question Link: https://leetcode.com/problems/word-search-ii/ * Primary idea: Classic Depth-first Search, go up, down, left, right four directions * with the help of Trie * * Time Complexity: O(mn^2), m is the longest length fo a word in words * Space Complexity: O(n^2) * */ class WordSearchII { func findWords(_ board: [[Character]], _ words: [String]) -> [String] { var res = [String]() let m = board.count let n = board[0].count let trie = _convertToTrie(words) var visited = [[Bool]](repeating: Array(repeating: false, count: n), count: m) for i in 0 ..< m { for j in 0 ..< n { _dfs(board, m, n, i, j, &visited, &res, trie, "") } } return res } fileprivate func _dfs(_ board: [[Character]], _ m: Int, _ n: Int, _ i: Int, _ j: Int, _ visited: inout [[Bool]], _ res: inout [String], _ trie: Trie, _ str: String) { // beyond matrix guard i >= 0 && i < m && j >= 0 && j < n else { return } // check visited guard !visited[i][j] else { return } // check is word prefix let str = str + "\(board[i][j])" guard trie.isWordPrefix(str) else { return } // check word exist if trie.isWord(str) && !res.contains(str) { res.append(str) } // check four directions visited[i][j] = true _dfs(board, m, n, i + 1, j, &visited, &res, trie, str) _dfs(board, m, n, i - 1, j, &visited, &res, trie, str) _dfs(board, m, n, i, j + 1, &visited, &res, trie, str) _dfs(board, m, n, i, j - 1, &visited, &res, trie, str) visited[i][j] = false } func _convertToTrie(_ words: [String]) -> Trie { let trie = Trie() for str in words { trie.insert(str) } return trie } } class Trie { var root: TrieNode init() { root = TrieNode() } func insert(_ word: String) { var node = root var word = [Character](word.characters) for i in 0 ..< word.count { let c = word[i] if node.children[c] == nil { node.children[c] = TrieNode() } node = node.children[c]! } node.isEnd = true } func isWord(_ word: String) -> Bool { var node = root var word = [Character](word.characters) for i in 0 ..< word.count { let c = word[i] if node.children[c] == nil { return false } node = node.children[c]! } return node.isEnd } func isWordPrefix(_ prefix: String) -> Bool { var node = root var prefix = [Character](prefix.characters) for i in 0 ..< prefix.count { let c = prefix[i] if node.children[c] == nil { return false } node = node.children[c]! } return true } } class TrieNode { var isEnd: Bool var children: [Character:TrieNode] init() { isEnd = false children = [Character:TrieNode]() } }
mit
1b7229d7189cf1ee8376b57f7efe5807
22.992908
171
0.462448
3.851936
false
false
false
false
Hout/SwiftDate
Sources/SwiftDate/Formatters/Formatter+Protocols.swift
1
6395
// // 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 DateToStringTrasformable { static func format(_ date: DateRepresentable, options: Any?) -> String } public protocol StringToDateTransformable { static func parse(_ string: String, region: Region?, options: Any?) -> DateInRegion? } // MARK: - Formatters /// Format to represent a date to string /// /// - iso: standard iso format. The ISO8601 formatted date, time and millisec "yyyy-MM-dd'T'HH:mm:ssZZZZZ" /// - extended: Extended format. "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz" /// - rss: The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200" /// - altRSS: The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200" /// - dotNet: The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/" /// - httpHeader: The http header formatted date "EEE, dd MMM yyyy HH:mm:ss zzz" i.e. "Tue, 15 Nov 1994 12:45:26 GMT" /// - custom: custom string format /// - standard: A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy" /// - date: Date only format (short = "2/27/17", medium = "Feb 27, 2017", long = "February 27, 2017", full = "Monday, February 27, 2017" /// - time: Time only format (short = "2:22 PM", medium = "2:22:06 PM", long = "2:22:06 PM EST", full = "2:22:06 PM Eastern Standard Time" /// - dateTime: Date/Time format (short = "2/27/17, 2:22 PM", medium = "Feb 27, 2017, 2:22:06 PM", long = "February 27, 2017 at 2:22:06 PM EST", full = "Monday, February 27, 2017 at 2:22:06 PM Eastern Standard Time" public enum DateToStringStyles { case iso(_: ISOFormatter.Options) case extended case rss case altRSS case dotNet case httpHeader case sql case date(_: DateFormatter.Style) case time(_: DateFormatter.Style) case dateTime(_: DateFormatter.Style) case dateTimeMixed(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) case custom(_: String) case standard case relative(style: RelativeFormatter.Style?) public func toString(_ date: DateRepresentable) -> String { switch self { case .iso(let opts): return ISOFormatter.format(date, options: opts) case .extended: return date.formatterForRegion(format: DateFormats.extended).string(from: date.date) case .rss: return date.formatterForRegion(format: DateFormats.rss).string(from: date.date) case .altRSS: return date.formatterForRegion(format: DateFormats.altRSS).string(from: date.date) case .sql: return date.formatterForRegion(format: DateFormats.sql).string(from: date.date) case .dotNet: return DOTNETFormatter.format(date, options: nil) case .httpHeader: return date.formatterForRegion(format: DateFormats.httpHeader).string(from: date.date) case .custom(let format): return date.formatterForRegion(format: format).string(from: date.date) case .standard: return date.formatterForRegion(format: DateFormats.standard).string(from: date.date) case .date(let style): return date.formatterForRegion(format: nil, configuration: { $0.dateStyle = style $0.timeStyle = .none }).string(from: date.date) case .time(let style): return date.formatterForRegion(format: nil, configuration: { $0.dateStyle = .none $0.timeStyle = style }).string(from: date.date) case .dateTime(let style): return date.formatterForRegion(format: nil, configuration: { $0.dateStyle = style $0.timeStyle = style }).string(from: date.date) case .dateTimeMixed(let dateStyle, let timeStyle): return date.formatterForRegion(format: nil, configuration: { $0.dateStyle = dateStyle $0.timeStyle = timeStyle }).string(from: date.date) case .relative(let style): return RelativeFormatter.format(date, options: style) } } } // MARK: - Parsers /// String to date transform /// /// - iso: standard automatic iso parser (evaluate the date components automatically) /// - extended: Extended format. "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz" /// - rss: The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200" /// - altRSS: The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200" /// - dotNet: The dotNet formatted date "/Date(%d%d)/" i.e. "/Date(1268123281843)/" /// - httpHeader: The http header formatted date "EEE, dd MMM yyyy HH:mm:ss zzz" i.e. "Tue, 15 Nov 1994 12:45:26 GMT" /// - strict: custom string format with lenient options active /// - custom: custom string format /// - standard: A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy" public enum StringToDateStyles { case iso(_: ISOParser.Options) case extended case rss case altRSS case dotNet case sql case httpHeader case strict(_: String) case custom(_: String) case standard public func toDate(_ string: String, region: Region) -> DateInRegion? { switch self { case .iso(let options): return ISOParser.parse(string, region: region, options: options) case .custom(let format): return DateInRegion(string, format: format, region: region) case .extended: return DateInRegion(string, format: DateFormats.extended, region: region) case .sql: return DateInRegion(string, format: DateFormats.sql, region: region) case .rss: return DateInRegion(string, format: DateFormats.rss, region: Region.ISO)?.convertTo(locale: region.locale) case .altRSS: return DateInRegion(string, format: DateFormats.altRSS, region: Region.ISO)?.convertTo(locale: region.locale) case .dotNet: return DOTNETParser.parse(string, region: region, options: nil) case .httpHeader: return DateInRegion(string, format: DateFormats.httpHeader, region: region) case .standard: return DateInRegion(string, format: DateFormats.standard, region: region) case .strict(let format): let formatter = DateFormatter.sharedFormatter(forRegion: region, format: format) formatter.isLenient = false guard let absDate = formatter.date(from: string) else { return nil } return DateInRegion(absDate, region: region) } } }
mit
adf2638e3af09ec796e574ea28db607d
46.362963
215
0.7066
3.484469
false
true
false
false
itechline/bonodom_new
SlideMenuControllerSwift/DataTableViewCell.swift
1
7262
import UIKit import SwiftyJSON import SDWebImage struct DataTableViewCellData { init(id: Int, imageUrl: String, adress: String, street: String,description: String, size: String, rooms: String, price: String, e_type: Int, fav: Bool, balcony: Int, parking: Int, furniture: Int) { self.id = id self.imageUrl = imageUrl self.adress = adress self.street = street self.description = description self.size = size self.rooms = rooms self.price = price self.e_type = e_type self.fav = fav self.balcony = balcony self.parking = parking self.furniture = furniture } var id: Int var imageUrl: String var adress: String var street: String var description: String var size: String var rooms: String var price: String var e_type: Int var fav: Bool var balcony: Int var parking: Int var furniture: Int } class DataTableViewCell : BaseTableViewCell { var favorite : Bool! var id : Int! @IBOutlet weak var heart_button: UIButton! @IBAction func heart_button_action(sender: AnyObject) { var favToSend = 0 if (self.favorite == true) { favToSend = 0 } else { favToSend = 1 } print ("ID") print (self.id) print ("FAVORITE") print (favToSend) EstateUtil.sharedInstance.setFavorite(self.id, favorit: favToSend, onCompletion: { (json: JSON) in print (json) dispatch_async(dispatch_get_main_queue(),{ if (!json["error"].boolValue) { if (favToSend == 0) { print ("NOT FAV") print (self.id) self.favorite = false self.heart_button.setImage(UIImage(named: "heart_empty")!, forState: UIControlState.Normal) } else { print ("FAV") self.favorite = true print (self.id) self.heart_button.setImage(UIImage(named: "heart_filled")!, forState: UIControlState.Normal) } } else { } }) }) } @IBOutlet weak var dataImage: UIImageView! @IBOutlet weak var dataText: UILabel! @IBOutlet weak var sizeText: UILabel! @IBOutlet weak var descriptionText: UILabel! @IBOutlet weak var roomsText: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var priceText: UILabel! @IBOutlet weak var streetText: UILabel! @IBOutlet weak var furniture_image: UIImageView! @IBOutlet weak var balcony_image: UIImageView! @IBOutlet weak var parking_image: UIImageView! override func awakeFromNib() { self.dataText?.font = UIFont.boldSystemFontOfSize(16) self.dataText?.textColor = UIColor(hex: "000000") } override class func height() -> CGFloat { return 172 } func cropToBounds(image: UIImage, width: Double, height: Double) -> UIImage { let contextImage: UIImage = UIImage(CGImage: image.CGImage!) let contextSize: CGSize = contextImage.size var posX: CGFloat = 0.0 var posY: CGFloat = 0.0 var cgwidth: CGFloat = CGFloat(width) var cgheight: CGFloat = CGFloat(height) // See what size is longer and create the center off of that if contextSize.width > contextSize.height { posX = ((contextSize.width - contextSize.height) / 2) posY = 0 cgwidth = contextSize.height cgheight = contextSize.height } else { posX = 0 posY = ((contextSize.height - contextSize.width) / 2) cgwidth = contextSize.width cgheight = contextSize.width } let rect: CGRect = CGRectMake(posX, posY, cgwidth, cgheight) // Create bitmap image from context using the rect let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)! // Create a new image based on the imageRef and rotate back to the original orientation let image: UIImage = UIImage(CGImage: imageRef, scale: image.scale, orientation: image.imageOrientation) return image } override func setData(data: Any?) { if let data = data as? DataTableViewCellData { //self.dataImage.setRandomDownloadImage(100, height: 170) //self.dataImage.setImageFromURL(data.imageUrl, indicator: activityIndicator) if (data.imageUrl != "") { let url: NSURL = NSURL(string: data.imageUrl)! self.dataImage.sd_setImageWithURL(url) } else { self.dataImage.image = UIImage(named: "noimage") } self.dataImage.sizeThatFits(CGSize.init(width: 116.0, height: 169.0)) self.dataText.text = data.adress self.sizeText.text = data.size self.descriptionText.text = data.description self.roomsText.text = data.rooms self.streetText.text = data.street self.favorite = data.fav self.id = data.id if (data.balcony == 1) { //NINCS self.balcony_image.image = UIImage(named: "list_nobalcony") } else { self.balcony_image.image = UIImage(named: "list_balcony") } if (data.furniture == 2) { //NINCS self.furniture_image.image = UIImage(named: "list_nofurniture") } else { self.furniture_image.image = UIImage(named: "list_furniture") } if (data.parking == 4) { self.parking_image.image = UIImage(named: "list_noparking") } else { self.parking_image.image = UIImage(named: "list_parking") } if (self.favorite == true) { self.heart_button.setImage(UIImage(named: "heart_filled")!, forState: UIControlState.Normal) } else { self.heart_button.setImage(UIImage(named: "heart_empty")!, forState: UIControlState.Normal) } if (data.e_type == 1) { //self.priceText.text = data.price + " Ft" //print(Int(data.price)!.asLocaleCurrency) //self.priceText.text = String(format: "%02d", Int(data.price)!.asLocaleCurrency) + " Ft" self.priceText.text = data.price.asLocaleCurrency + " Ft" } else { self.priceText.text = data.price.asLocaleCurrency + " Ft/hó" } } } } extension String { var asLocaleCurrency:String { let formatter = NSNumberFormatter() formatter.numberStyle = .DecimalStyle //formatter.locale = NSLocale.currentLocale() return formatter.stringFromNumber(Int(self)!)! } }
mit
6529ca330a01252dbb7dac62a7ce18bd
33.089202
201
0.554607
4.59557
false
false
false
false
UncleJerry/Dailylife-with-a-fish
Fishing Days/LeftSegue.swift
1
1548
// // LeftSegue.swift // Fishing Days // // Created by 周建明 on 2017/6/7. // Copyright © 2017年 Uncle Jerry. All rights reserved. // import UIKit class LeftSegue: UIStoryboardSegue { override func perform() { // Assign the source and destination views to local variables. let firstVCView = self.source.view as UIView! let secondVCView = self.destination.view as UIView! // Get the screen width and height. let screenWidth = UIScreen.main.bounds.size.width let screenHeight = UIScreen.main.bounds.size.height // Specify the initial position of the destination view. secondVCView?.frame = CGRect(x: -screenWidth, y: 0.0, width: screenWidth, height: screenHeight) // Access the app's key window and insert the destination view above the current (source) one. let window = UIApplication.shared.keyWindow window?.insertSubview(secondVCView!, aboveSubview: firstVCView!) // Animate the transition. UIView.animate(withDuration: 0.5, animations: { () -> Void in firstVCView?.frame = (firstVCView?.frame.offsetBy(dx: screenWidth, dy: 0.0))! secondVCView?.frame = (secondVCView?.frame.offsetBy(dx: screenWidth, dy: 0.0))! }, completion: { (Finished) -> Void in self.source.present(self.destination as UIViewController, animated: false, completion: nil) }) } }
mit
7a3a921f14118680f56010f1cfd55b36
37.475
103
0.614035
4.580357
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/MergedAvatarsView.swift
1
5644
// // MergedAvatarsView.swift // Telegram // // Created by Mikhail Filimonov on 03/09/2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import SwiftSignalKit import Postbox private enum PeerAvatarReference : Equatable { static func == (lhs: PeerAvatarReference, rhs: PeerAvatarReference) -> Bool { switch lhs { case let .image(lhsPeer, rep): if case .image(let rhsPeer, rep) = rhs { return lhsPeer.isEqual(rhsPeer) } else { return false } } } case image(Peer, TelegramMediaImageRepresentation?) var peerId: PeerId { switch self { case let .image(value, _): return value.id } } } private extension PeerAvatarReference { init(peer: Peer) { self = .image(peer, peer.smallProfileImage) } } final class MergedAvatarsView: Control { init(mergedImageSize: CGFloat = 16.0, mergedImageSpacing: CGFloat = 15.0, avatarFont: NSFont = NSFont.avatar(8.0)) { self.mergedImageSize = mergedImageSize self.mergedImageSpacing = mergedImageSpacing self.avatarFont = avatarFont super.init() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required convenience init(frame frameRect: NSRect) { self.init() } let mergedImageSize: CGFloat let mergedImageSpacing: CGFloat let avatarFont: NSFont private var peers: [PeerAvatarReference] = [] private var images: [PeerId: CGImage] = [:] private var disposables: [PeerId: Disposable] = [:] deinit { for (_, disposable) in self.disposables { disposable.dispose() } } func update(context: AccountContext, peers: [Peer], message: Message?, synchronousLoad: Bool) { let filteredPeers = Array(peers.map(PeerAvatarReference.init).prefix(3)) if filteredPeers != self.peers { self.peers = filteredPeers var validImageIds: [PeerId] = [] for peer in filteredPeers { if case .image = peer { validImageIds.append(peer.peerId) } } var removedImageIds: [PeerId] = [] for (id, _) in self.images { if !validImageIds.contains(id) { removedImageIds.append(id) } } var removedDisposableIds: [PeerId] = [] for (id, disposable) in self.disposables { if !validImageIds.contains(id) { disposable.dispose() removedDisposableIds.append(id) } } for id in removedImageIds { self.images.removeValue(forKey: id) } for id in removedDisposableIds { self.disposables.removeValue(forKey: id) } for peer in filteredPeers { switch peer { case let .image(peer, representation): if self.disposables[peer.id] == nil { let signal = peerAvatarImage(account: context.account, photo: PeerPhoto.peer(peer, representation, peer.displayLetters, message), displayDimensions: NSMakeSize(mergedImageSize, mergedImageSize), scale: backingScaleFactor, font: avatarFont, synchronousLoad: synchronousLoad) let disposable = (signal |> deliverOnMainQueue).start(next: { [weak self] image in guard let strongSelf = self else { return } if let image = image.0 { strongSelf.images[peer.id] = image strongSelf.setNeedsDisplay() } }) self.disposables[peer.id] = disposable } } } self.setNeedsDisplay() } } override func draw(_ layer: CALayer, in context: CGContext) { super.draw(layer, in: context) context.setBlendMode(.copy) context.setFillColor(NSColor.clear.cgColor) context.fill(bounds) context.setBlendMode(.copy) var currentX = mergedImageSize + mergedImageSpacing * CGFloat(self.peers.count - 1) - mergedImageSize for i in (0 ..< self.peers.count).reversed() { context.saveGState() context.translateBy(x: frame.width / 2.0, y: frame.height / 2.0) context.scaleBy(x: 1.0, y: -1.0) context.translateBy(x: -frame.width / 2.0, y: -frame.height / 2.0) let imageRect = CGRect(origin: CGPoint(x: currentX, y: 0.0), size: CGSize(width: mergedImageSize, height: mergedImageSize)) context.setFillColor(NSColor.clear.cgColor) context.fillEllipse(in: imageRect.insetBy(dx: -1.0, dy: -1.0)) if let image = self.images[self.peers[i].peerId] { context.draw(image, in: imageRect) } else { context.setFillColor(NSColor.gray.cgColor) context.fillEllipse(in: imageRect) } currentX -= mergedImageSpacing context.restoreGState() } } }
gpl-2.0
cbc0e8e209448aec25303c69be98073e
32.390533
297
0.533936
4.906957
false
false
false
false
nferocious76/NFImageView
NFImageView/Classes/NFImageViewConfiguration.swift
1
1956
// // NFImageViewConfiguration.swift // Pods // // Created by Neil Francis Hipona on 23/07/2016. // Copyright (c) 2016 Neil Francis Ramirez Hipona. All rights reserved. // import Foundation import UIKit extension NFImageView { // MARK: - UIActivityIndicatorView Configuration /** * Set loading spinner's spinner color */ public func setLoadingSpinnerColor(_ color: UIColor) { loadingIndicator.color = color } /** * Set loading spinner's spinner style */ public func setLoadingSpinnerViewStyle(activityIndicatorViewStyle style: UIActivityIndicatorView.Style) { loadingIndicator.style = style } /** * Set loading spinner's background color */ public func setLoadingSpinnerBackgroundColor(_ color: UIColor) { loadingIndicator.backgroundColor = color } // MARK: - UIProgressView Configuration /** * Set loading progress view style */ public func setLoadingProgressViewStyle(progressViewStyle style: UIProgressView.Style) { loadingProgressView.progressViewStyle = style } /** * Set loading progress tint color */ public func setLoadingProgressViewTintColor(_ progressTintColor: UIColor?, trackTintColor: UIColor?) { loadingProgressView.progressTintColor = progressTintColor loadingProgressView.trackTintColor = trackTintColor } /** * Set loading progress image */ public func setLoadingProgressViewProgressImage(_ progressImage: UIImage?, trackImage: UIImage?) { loadingProgressView.progressImage = progressImage loadingProgressView.trackImage = trackImage } /** * Set loading progress's progress value */ public func setLoadingProgressViewProgress(_ progress: Float, animated: Bool) { loadingProgressView.setProgress(progress, animated: animated) } }
mit
42124238a5b9b677d032f9082b131677
26.166667
109
0.67229
5.418283
false
false
false
false
ffried/FFFoundation
Sources/FFFoundation/Geometry/Angle.swift
1
10648
// // Angle.swift // FFFoundation // // Created by Florian Friedrich on 18.08.17. // Copyright 2017 Florian Friedrich // // 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. // public struct Angle<Value: FloatingPoint>: FloatingPoint, CustomStringConvertible where Value.Stride == Value { public typealias Stride = Angle public typealias IntegerLiteralType = Value.IntegerLiteralType public typealias Exponent = Value.Exponent public typealias Magnitude = Angle private enum Kind { case radians, degrees } private var kind: Kind public private(set) var value: Value public var description: String { switch kind { case .radians: return "\(value) radians" case .degrees: return "\(value) degrees" } } private init(kind: Kind, value: Value) { (self.kind, self.value) = (kind, value) } public init(radians: Value) { self.init(kind: .radians, value: radians) } public init(degrees: Value) { self.init(kind: .degrees, value: degrees) } public var asRadians: Angle<Value> { switch kind { case .radians: return self case .degrees: return converted() } } public var asDegrees: Angle<Value> { switch kind { case .radians: return converted() case .degrees: return self } } private func value(as newKind: Kind) -> Value { kind == newKind ? value : converted().value } // MARK: - Hashable public func hash(into hasher: inout Hasher) { hasher.combine(asRadians.value) } // MARK: - Conversion public mutating func convert() { switch kind { case .radians: kind = .degrees value *= 180 / .pi case .degrees: kind = .radians value *= .pi / 180 } } public func converted() -> Angle<Value> { var newAngle = self newAngle.convert() return newAngle } // MARK: - FloatingPoint public static var radix: Int { Value.radix } public static var nan: Angle<Value> { .init(kind: .radians, value: .nan) } public static var signalingNaN: Angle<Value> { .init(kind: .radians, value: .signalingNaN) } public static var infinity: Angle<Value> { .init(kind: .radians, value: .infinity) } public static var pi: Angle<Value> { .init(kind: .radians, value: .pi) } public static var greatestFiniteMagnitude: Angle<Value> { .init(kind: .radians, value: .greatestFiniteMagnitude) } public static var leastNonzeroMagnitude: Angle<Value> { .init(kind: .radians, value: .leastNonzeroMagnitude) } public static var leastNormalMagnitude: Angle<Value> { .init(kind: .radians, value: .leastNormalMagnitude) } public var exponent: Exponent { value.exponent } public var sign: FloatingPointSign { value.sign } public var isNormal: Bool { value.isNormal } public var isFinite: Bool { value.isFinite } public var isZero: Bool { value.isZero } public var isSubnormal: Bool { value.isSubnormal } public var isInfinite: Bool { value.isInfinite } public var isNaN: Bool { value.isNaN } public var isSignalingNaN: Bool { value.isSignalingNaN } public var isCanonical: Bool { value.isCanonical } public var magnitude: Magnitude { .init(kind: kind, value: value.magnitude) } public var ulp: Angle<Value> { .init(kind: kind, value: value.ulp) } public var significand: Angle<Value> { .init(kind: kind, value: value.significand) } public var nextUp: Angle<Value> { .init(kind: kind, value: value.nextUp) } public var nextDown: Angle<Value> { .init(kind: kind, value: value.nextDown) } // MARK: Initializers public init(integerLiteral value: IntegerLiteralType) { self.init(kind: .radians, value: .init(integerLiteral: value)) } public init?<Source>(exactly source: Source) where Source : BinaryInteger { guard let value = Value(exactly: source) else { return nil } self.init(kind: .radians, value: value) } public init<Source>(_ value: Source) where Source : BinaryInteger { self.init(kind: .radians, value: .init(value)) } public init(signOf: Angle, magnitudeOf: Angle) { self.init(kind: .radians, value: .init(signOf: signOf.asRadians.value, magnitudeOf: magnitudeOf.asRadians.value)) } public init(sign: FloatingPointSign, exponent: Exponent, significand: Angle) { self.init(kind: .radians, value: .init(sign: sign, exponent: exponent, significand: significand.asRadians.value)) } // MARK: Calculation public mutating func formRemainder(dividingBy other: Angle<Value>) { value.formRemainder(dividingBy: other.value(as: kind)) } public mutating func formTruncatingRemainder(dividingBy other: Angle<Value>) { value.formTruncatingRemainder(dividingBy: other.value(as: kind)) } public mutating func addProduct(_ lhs: Angle<Value>, _ rhs: Angle<Value>) { value.addProduct(lhs.value(as: kind), rhs.value(as: kind)) } public mutating func formSquareRoot() { value.formSquareRoot() } public mutating func round(_ rule: FloatingPointRoundingRule) { value.round(rule) } // MARK: Comparison public func isEqual(to other: Angle<Value>) -> Bool { value.isEqual(to: other.value(as: kind)) } public func isLess(than other: Angle<Value>) -> Bool { value.isLess(than: other.value(as: kind)) } public func isLessThanOrEqualTo(_ other: Angle<Value>) -> Bool { value.isLessThanOrEqualTo(other.value(as: kind)) } public func isTotallyOrdered(belowOrEqualTo other: Angle<Value>) -> Bool { value.isTotallyOrdered(belowOrEqualTo: other.value(as: kind)) } // MARK: - Strideable public func distance(to other: Angle<Value>) -> Stride { .init(kind: kind, value: value.distance(to: other.value(as: kind))) } public func advanced(by n: Stride) -> Angle<Value> { .init(kind: kind, value: value.advanced(by: n.value(as: kind))) } // MARK: - Operators public static func +(lhs: Angle<Value>, rhs: Angle<Value>) -> Angle<Value> { .init(kind: lhs.kind, value: lhs.value + rhs.value(as: lhs.kind)) } public static func -(lhs: Angle<Value>, rhs: Angle<Value>) -> Angle<Value> { .init(kind: lhs.kind, value: lhs.value - rhs.value(as: lhs.kind)) } public static func *(lhs: Angle<Value>, rhs: Angle<Value>) -> Angle<Value> { .init(kind: lhs.kind, value: lhs.value * rhs.value(as: lhs.kind)) } public static func /(lhs: Angle<Value>, rhs: Angle<Value>) -> Angle<Value> { .init(kind: lhs.kind, value: lhs.value / rhs.value(as: lhs.kind)) } public static func +=(lhs: inout Angle<Value>, rhs: Angle<Value>) { lhs.value += rhs.value(as: lhs.kind) } public static func -=(lhs: inout Angle<Value>, rhs: Angle<Value>) { lhs.value -= rhs.value(as: lhs.kind) } public static func *=(lhs: inout Angle<Value>, rhs: Angle<Value>) { lhs.value *= rhs.value(as: lhs.kind) } public static func /=(lhs: inout Angle<Value>, rhs: Angle<Value>) { lhs.value /= rhs.value(as: lhs.kind) } } // MARK: - Convenience extension Angle { public static func radians(_ value: Value) -> Angle { .init(kind: .radians, value: value) } public static func degrees(_ value: Value) -> Angle { .init(kind: .degrees, value: value) } } // MARK: - Conditional Conformances fileprivate extension Angle { enum CodingKeys: String, CodingKey { case kind, value } } extension Angle: Sendable where Value: Sendable {} extension Angle: Encodable where Value: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch kind { case .degrees: try container.encode("degrees", forKey: .kind) case .radians: try container.encode("radians", forKey: .kind) } try container.encode(value, forKey: .value) } } extension Angle: Decodable where Value: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) switch try container.decode(String.self, forKey: .kind) { case "degrees": try self.init(kind: .degrees, value: container.decode(Value.self, forKey: .value)) case "radians": try self.init(kind: .radians, value: container.decode(Value.self, forKey: .value)) case let invalidValue: throw DecodingError.dataCorruptedError(forKey: .kind, in: container, debugDescription: "Could not convert '\(invalidValue)' to \(Angle.self)") } } } extension Angle: ExpressibleByFloatLiteral where Value: ExpressibleByFloatLiteral { public typealias FloatLiteralType = Value.FloatLiteralType public init(floatLiteral value: FloatLiteralType) { self.init(radians: Value(floatLiteral: value)) } } extension Angle: BinaryFloatingPoint where Value: BinaryFloatingPoint { public typealias RawSignificand = Value.RawSignificand public typealias RawExponent = Value.RawExponent public static var exponentBitCount: Int { Value.exponentBitCount } public static var significandBitCount: Int { Value.significandBitCount } public var exponentBitPattern: RawExponent { value.exponentBitPattern } public var significandBitPattern: RawSignificand { value.significandBitPattern } public var binade: Angle<Value> { .init(kind: kind, value: value.binade) } public var significandWidth: Int { value.significandWidth } public init(sign: FloatingPointSign, exponentBitPattern: RawExponent, significandBitPattern: RawSignificand) { self.init(kind: .radians, value: .init(sign: sign, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern)) } }
apache-2.0
778e8b21f27d90b063892ac5e036ee6f
35.717241
129
0.652705
4.2592
false
false
false
false
arloistale/iOSThrive
Thrive/Thrive/APIController.swift
1
2817
// // APIController.swift // Thrive // // Created by Jonathan Lu on 3/2/16. // Copyright © 2016 UCSC OpenLab. All rights reserved. // import Foundation let apiURL = "http://Jonathans-MacBook-Pro.local:8081/" let apiCardsPoint = "items" class APIController { typealias APICallback = ((error: NSError?, results: [Card]?) -> Void) func searchCards(pagination: Int, completionHandler: APICallback) { let urlPath = apiURL.stringByAppendingString(apiCardsPoint) let url = NSURL(string: urlPath) let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Accept") let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, err) in if(err != nil) { completionHandler(error: err! as NSError, results: nil) } else { do { let responseObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) let responseDict = responseObject as? [String: AnyObject] guard let responseArray = responseDict?["data"] as? [[String: AnyObject]] else { completionHandler(error: NSError(domain: "Json Error", code: 0, userInfo: nil), results: nil) return } var cards = [Card]() for dataObject : [String: AnyObject] in responseArray { guard let dateString = dataObject["created_at"] as? String, let date = DateUtils.getDateFromString(dateString) else { print("Invalid card received (no date)") continue } //guard let moodIndex = dataObject["moodIndex"] as? let message = dataObject[Card.PropertyKey.messageKey] as? String let moodIndex = 0 let photo = dataObject[Card.PropertyKey.photoKey] as? String if let card = Card(date: date, moodIndex: moodIndex, message: message, photo: photo) { cards.append(card) } } completionHandler(error: nil, results: cards) } catch { completionHandler(error: error as? NSError, results: nil) } } }) task.resume() } }
mit
3c818a7c15b2556d0645fd1d1bc12ec8
39.242857
117
0.498224
5.654618
false
false
false
false
exchangegroup/Dodo
Dodo/UIView+SwiftAlertBar.swift
1
944
import UIKit private var sabAssociationKey: UInt8 = 0 /** UIView extension for showing a notification widget. let view = UIView() view.dodo.show("Hello World!") */ public extension UIView { /** Message bar extension. Call `dodo.show`, `dodo.success`, dodo.error` functions to show a notification widget in the view. let view = UIView() view.dodo.show("Hello World!") */ var dodo: DodoInterface { get { if let value = objc_getAssociatedObject(self, &sabAssociationKey) as? DodoInterface { return value } else { let dodo = Dodo(superview: self) objc_setAssociatedObject(self, &sabAssociationKey, dodo, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) return dodo } } set { objc_setAssociatedObject(self, &sabAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } }
mit
aa3d226d2e9ed2b292c4e84b21f475f8
21.47619
100
0.636653
4.538462
false
false
false
false
abecker3/SeniorDesignGroup7
ProvidenceWayfinding/ProvidenceWayfinding/HistoryViewController.swift
1
3217
// // HistoryViewController.swift // ProvidenceWayfinding // // Created by Derek Becker on 2/9/16. // Copyright © 2016 GU. All rights reserved. // import UIKit class HistoryViewController: UITableViewController{ @IBOutlet var table: UITableView! let defaults = NSUserDefaults.standardUserDefaults() var building = [String()] var floor = [String()] var dateSave = [String()] var timeSave = [String()] var curIndex = Int() var flag = Int() var index = 0 var pathFlag = Int() override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (building.count - 1) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:BasicDirectionsCell = tableView.dequeueReusableCellWithIdentifier("historyCell", forIndexPath: indexPath) as! BasicDirectionsCell cell.subtitleLabel.text = floor[indexPath.item] cell.titleLabel.text = building[indexPath.item] cell.subtitle2Label.text = timeSave[indexPath.item] cell.title2Label.text = dateSave[indexPath.item] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let check = defaults.integerForKey("savedParkingEver") if (check == 1){ let cell = tableView.cellForRowAtIndexPath(indexPath)! as! BasicDirectionsCell parkingHistEntry = Directory(name: cell.titleLabel.text! + " Parking " + cell.subtitleLabel.text!, category: "Parking", floor: cell.subtitleLabel.text!, hours: "NA", ext: "", notes: "") routeFromWhichScreen = 3 flagForPlace = 1 resetToRootView = 1 tabBarController?.selectedIndex = 1 } else{ let alertTitle = "Error!" let alertMessage = "There is no saved parking location to route to!" let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in alertController.dismissViewControllerAnimated(true, completion: nil) })) presentViewController(alertController, animated: false, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() self.tableView.layer.borderWidth = 0.5 self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 80.0 if(flag == 1){ index = curIndex } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) pathFlag = Int(defaults.stringForKey("pathFlag")!)! if (pathFlag == 1) { if let navController = self.navigationController { navController.popViewControllerAnimated(false) } } } }
apache-2.0
babe40d34a6862156b71f9ece19e7d21
37.759036
197
0.654229
5.13738
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDKTests/Mocks/MockRoomSummary.swift
1
3445
// // Copyright 2021 The Matrix.org Foundation C.I.C // // 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 internal class MockRoomSummary: NSObject, MXRoomSummaryProtocol { var roomId: String var roomTypeString: String? var roomType: MXRoomType = .room var avatar: String? var displayname: String? var topic: String? var creatorUserId: String = "@room_creator:some_domain.com" var aliases: [String] = [] var historyVisibility: String? = nil var joinRule: String? = kMXRoomJoinRuleInvite var membership: MXMembership = .join var membershipTransitionState: MXMembershipTransitionState = .joined var membersCount: MXRoomMembersCount = MXRoomMembersCount(members: 2, joined: 2, invited: 0) var isConferenceUserRoom: Bool = false var hiddenFromUser: Bool = false var storedHash: UInt = 0 var lastMessage: MXRoomLastMessage? var isEncrypted: Bool = false var trust: MXUsersTrustLevelSummary? var localUnreadEventCount: UInt = 0 var notificationCount: UInt = 0 var highlightCount: UInt = 0 var hasAnyUnread: Bool { return localUnreadEventCount > 0 } var hasAnyNotification: Bool { return notificationCount > 0 } var hasAnyHighlight: Bool { return highlightCount > 0 } var isDirect: Bool { return isTyped(.direct) } var directUserId: String? var others: [String: NSCoding]? var favoriteTagOrder: String? var dataTypes: MXRoomSummaryDataTypes = [] func isTyped(_ types: MXRoomSummaryDataTypes) -> Bool { return (dataTypes.rawValue & types.rawValue) != 0 } var sentStatus: MXRoomSummarySentStatus = .ok var spaceChildInfo: MXSpaceChildInfo? var parentSpaceIds: Set<String> = [] var userIdsSharingLiveBeacon: Set<String> = [] init(withRoomId roomId: String) { self.roomId = roomId super.init() } static func generate() -> MockRoomSummary { return generate(withTypes: []) } static func generateDirect() -> MockRoomSummary { return generate(withTypes: .direct) } static func generate(withTypes types: MXRoomSummaryDataTypes) -> MockRoomSummary { guard let random = MXTools.generateSecret() else { fatalError("Room id cannot be created") } let result = MockRoomSummary(withRoomId: "!\(random):some_domain.com") result.dataTypes = types if types.contains(.invited) { result.membership = .invite result.membershipTransitionState = .invited } return result } override var description: String { return "<MockRoomSummary: \(roomId) \(String(describing: displayname))>" } }
apache-2.0
31f1c65acda5bd08cf7f038bd2b06224
25.705426
96
0.644702
4.668022
false
false
false
false
peferron/algo
EPI/Linked Lists/Test whether a singly linked list is palindromic/swift/test.swift
1
1316
import Darwin let tests = [ (list: [0], isPalindrome: true), (list: [0, 1], isPalindrome: false), (list: [0, 0], isPalindrome: true), (list: [1, 2, 1], isPalindrome: true), (list: [1, 2, 2], isPalindrome: false), (list: [1, 5, 2, 2, 5, 1], isPalindrome: true), (list: [1, 5, 2, 3, 5, 1], isPalindrome: false), (list: [0, 1, 0, 3, 1, 1, 0], isPalindrome: false), (list: [0, 1, 0, 3, 0, 1, 0], isPalindrome: true), ] func toList(_ values: [Int]) -> Node { let nodes = values.map(Node.init) for i in 0..<values.count - 1 { nodes[i].next = nodes[i + 1] } return nodes[0] } func toArray(_ list: Node) -> [Int] { var curr: Node? = list; var array = [Int]() while let c = curr { array.append(c.value) curr = c.next } return array } for test in tests { let list = toList(test.list) let isPalindrome = list.isPalindrome() guard isPalindrome == test.isPalindrome else { print("For list \(test.list), expected isPalindrome to be \(test.isPalindrome), " + "but was \(isPalindrome)") exit(1) } let values = toArray(list); guard values == test.list else { print("For list \(test.list), expected final list to be unchanged, but was \(values)") exit(1) } }
mit
9319b97996416a1c8aee96e5d15693fd
25.857143
94
0.555471
3.257426
false
true
false
false
OctMon/OMExtension
OMExtensionDemo/OMExtensionDemo/OMViewController/PlaceholderVC.swift
1
4108
// // PlaceholderVC.swift // OMExtensionDemo // // The MIT License (MIT) // // Copyright (c) 2016 OctMon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class PlaceholderVC: BaseVC { @IBOutlet weak var segmentControl: UISegmentedControl! @objc let dataSource = [ "500px", "Airbnb", "AppStore", "Camera", "Dropbox", "Facebook", "Fancy", "Foursquare", "iCloud", "Instagram", "iTunes Connect", "Kickstarter", "Path", "Pinterest", "Photos", "Podcasts", "Remote", "Safari", "Skype", "Slack", "Tumblr", "Twitter", "Videos", "Vesper", "Vine", "WhatsApp", "WWDC" ] @objc var getImage: UIImage? { let app = PopularApp(rawValue: dataSource.omRandom()!.element)! return UIImage(named: "placeholder_" + app.rawValue.lowercased().replacingOccurrences(of: "", with: "_", options: NSString.CompareOptions.caseInsensitive, range: nil)) } @objc var getButtonBackgroundImageName: String { let app = PopularApp(rawValue: dataSource.omRandom()!.element)! return "button_background_" + app.rawValue.lowercased() } @objc var timer: Timer? override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if let timer = timer, timer.isValid { timer.invalidate() } } override func viewDidLoad() { super.viewDidLoad() om.showPlaceholder(image: getImage) timer = Timer.OM.runLoop(seconds: 1) { (timer) in if let image = self.getImage { let title = "empty set button" let backgroundImageName = self.getButtonBackgroundImageName let backgroundImageNormal = UIImage(named: backgroundImageName + "_normal") let backgroundImageHighlight = UIImage(named: backgroundImageName + "_highlight") self.om.showPlaceholder(image: image, shouldTap: true, offset: image.size.width * 0.5, bringSubviews: [self.segmentControl], buttonBackgroundImages: [(backgroundImageNormal, state: UIControlState()), (backgroundImageHighlight, state: UIControlState.highlighted)], buttonTitles: (backgroundImageNormal != nil ? [(title.omGetAttributes(), UIControlState())] : nil), buttonTapHandler: { (button) in print(button.isSelected) }) } else { let title = "No Image" self.om.showPlaceholder(image: nil, titleAttributedString: title.omGetAttributes(color: [(UIColor.gray, title)]), shouldTap: false, offset: 64) } } } }
mit
16f565854a7d25097c01d8248295cf3f
32.672131
411
0.591529
4.973366
false
false
false
false
wireapp/wire-ios-sync-engine
Tests/Source/SessionManager/APIVersionResolverTests.swift
1
12282
// // Wire // Copyright (C) 2022 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 Foundation @testable import WireSyncEngine import XCTest class APIVersionResolverTests: ZMTBaseTest { private var transportSession: MockTransportSession! private var mockDelegate: MockAPIVersionResolverDelegate! override func setUp() { mockDelegate = .init() transportSession = MockTransportSession(dispatchGroup: dispatchGroup) setCurrentAPIVersion(nil) super.setUp() } override func tearDown() { mockDelegate = nil transportSession = nil setCurrentAPIVersion(nil) super.tearDown() } private func createSUT( clientProdVersions: Set<APIVersion>, clientDevVersions: Set<APIVersion>, isDeveloperModeEnabled: Bool = false ) -> APIVersionResolver { let sut = APIVersionResolver( clientProdVersions: clientProdVersions, clientDevVersions: clientDevVersions, transportSession: transportSession, isDeveloperModeEnabled: isDeveloperModeEnabled ) sut.delegate = mockDelegate return sut } private func mockBackendInfo( productionVersions: ClosedRange<Int32>, developmentVersions: ClosedRange<Int32>?, domain: String, isFederationEnabled: Bool ) { transportSession.supportedAPIVersions = productionVersions.map(NSNumber.init(value:)) if let developmentVersions = developmentVersions { transportSession.developmentAPIVersions = developmentVersions.map(NSNumber.init(value:)) } transportSession.domain = domain transportSession.federation = isFederationEnabled } // MARK: - Endpoint unavailable func testThatItDefaultsToVersionZeroIfEndpointIsUnavailable() throws { // Given the client supports API versioning. let sut = createSUT( clientProdVersions: Set(APIVersion.allCases), clientDevVersions: [] ) // Given the backend does not. transportSession.isAPIVersionEndpointAvailable = false // When version is resolved. let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then it resolves to v0. let resolvedVersion = try XCTUnwrap(BackendInfo.apiVersion) XCTAssertEqual(resolvedVersion, .v0) XCTAssertEqual(BackendInfo.domain, "wire.com") XCTAssertEqual(BackendInfo.isFederationEnabled, false) } // MARK: - Highest productino version func testThatItResolvesTheHighestProductionAPIVersion() throws { // Given client has prod and dev versions. let sut = createSUT( clientProdVersions: [.v0, .v1], clientDevVersions: [.v2] ) // Given backend also has prod and dev versions. mockBackendInfo( productionVersions: 0...1, developmentVersions: 2...2, domain: "foo.com", isFederationEnabled: true ) XCTAssertNil(BackendInfo.apiVersion) // When version is resolved. let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then it's the highest common prod version. XCTAssertEqual(BackendInfo.apiVersion, .v1) XCTAssertEqual(BackendInfo.domain, "foo.com") XCTAssertEqual(BackendInfo.isFederationEnabled, true) } func testThatItResolvesTheHighestProductionAPIVersionWhenDevelopmentVersionsAreAbsent() throws { // Given client has prod and dev versions. let sut = createSUT( clientProdVersions: [.v0, .v1], clientDevVersions: [.v2] ) // Given backend only has prod versons. mockBackendInfo( productionVersions: 0...1, developmentVersions: nil, domain: "foo.com", isFederationEnabled: true ) XCTAssertNil(BackendInfo.apiVersion) // When version is resolved. let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then it's the highest common prod version. XCTAssertEqual(BackendInfo.apiVersion, .v1) XCTAssertEqual(BackendInfo.domain, "foo.com") XCTAssertEqual(BackendInfo.isFederationEnabled, true) } // MARK: - Peferred version func testThatItResolvesThePreferredAPIVersion() throws { // Given client has prod and dev versions in dev mode. let sut = createSUT( clientProdVersions: [.v0, .v1], clientDevVersions: [.v2], isDeveloperModeEnabled: true ) // Given backend also has prod and dev versions. mockBackendInfo( productionVersions: 0...1, developmentVersions: 2...2, domain: "foo.com", isFederationEnabled: true ) // Given there is a preferred version. BackendInfo.preferredAPIVersion = .v2 XCTAssertNil(BackendInfo.apiVersion) // When version is resolved. let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then it's the preferred version. XCTAssertEqual(BackendInfo.apiVersion, .v2) XCTAssertEqual(BackendInfo.domain, "foo.com") XCTAssertEqual(BackendInfo.isFederationEnabled, true) } func testThatItDoesNotResolvePreferredAPIVersionIfNotInDevMode() throws { // Given client has prod and dev versions not in dev mode. let sut = createSUT( clientProdVersions: [.v0, .v1], clientDevVersions: [.v2], isDeveloperModeEnabled: false ) // Given backend also has prod and dev versions. mockBackendInfo( productionVersions: 0...1, developmentVersions: 2...2, domain: "foo.com", isFederationEnabled: true ) // Given there is a preferred version. BackendInfo.preferredAPIVersion = .v2 XCTAssertNil(BackendInfo.apiVersion) // When version is resolved. let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then it's the highest common prod version. XCTAssertEqual(BackendInfo.apiVersion, .v1) XCTAssertEqual(BackendInfo.domain, "foo.com") XCTAssertEqual(BackendInfo.isFederationEnabled, true) } func testThatItDoesNotResolvePreferredAPIVersionIfNotSupportedByBackend() throws { // Given client has prod and dev versions in dev mode. let sut = createSUT( clientProdVersions: [.v0, .v1], clientDevVersions: [.v2], isDeveloperModeEnabled: true ) // Given backend also has prod and dev versions. mockBackendInfo( productionVersions: 0...1, developmentVersions: nil, domain: "foo.com", isFederationEnabled: true ) // Given there is a preferred version. BackendInfo.preferredAPIVersion = .v2 XCTAssertNil(BackendInfo.apiVersion) // When version is resolved. let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then it's the highest common prod version. XCTAssertEqual(BackendInfo.apiVersion, .v1) XCTAssertEqual(BackendInfo.domain, "foo.com") XCTAssertEqual(BackendInfo.isFederationEnabled, true) } // MARK: - Blacklist func testThatItReportsBlacklistReasonWhenBackendIsObsolete() throws { // Given version one was selected. setCurrentAPIVersion(.v1) // Given now we only support version 2. let sut = createSUT( clientProdVersions: [.v2], clientDevVersions: [] ) // Given backend doesn't support version 2 mockBackendInfo( productionVersions: 0...1, developmentVersions: nil, domain: "foo.com", isFederationEnabled: true ) // When version is resolved let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then no version could be resolved & blacklist reason is generated. XCTAssertNil(BackendInfo.apiVersion) XCTAssertEqual(BackendInfo.domain, "foo.com") XCTAssertEqual(BackendInfo.isFederationEnabled, true) XCTAssertEqual(mockDelegate.blacklistReason, .backendAPIVersionObsolete) } func testThatItReportsBlacklistReasonWhenClientIsObsolete() throws { // Given version one was selected. setCurrentAPIVersion(.v1) // Given we still only support v1. let sut = createSUT( clientProdVersions: [.v1], clientDevVersions: [] ) // Given backend no longer supports v1. mockBackendInfo( productionVersions: 2...2, developmentVersions: nil, domain: "foo.com", isFederationEnabled: true ) // When version is resolved let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then no version could be resolved & blacklist reason is generated. XCTAssertNil(BackendInfo.apiVersion) XCTAssertEqual(BackendInfo.domain, "foo.com") XCTAssertEqual(BackendInfo.isFederationEnabled, true) XCTAssertEqual(mockDelegate.blacklistReason, .clientAPIVersionObsolete) } // MARK: - Federation func testThatItReportsToDelegate_WhenFederationHasBeenEnabled() throws { // Given client has prod versions. let sut = createSUT( clientProdVersions: Set(APIVersion.allCases), clientDevVersions: [] ) // Given federation is not enabled. BackendInfo.isFederationEnabled = false // Backend now has federation enabled. mockBackendInfo( productionVersions: 0...2, developmentVersions: nil, domain: "foo.com", isFederationEnabled: true ) // When version is resolved. let done = expectation(description: "done") sut.resolveAPIVersion(completion: done.fulfill) XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5)) // Then federation is enabled and forwarded to delegate. XCTAssertTrue(BackendInfo.isFederationEnabled) XCTAssertTrue(mockDelegate.didReportFederationHasBeenEnabled) } } // MARK: - Mocks private class MockAPIVersionResolverDelegate: APIVersionResolverDelegate { var blacklistReason: BlacklistReason? func apiVersionResolverFailedToResolveVersion(reason: BlacklistReason) { blacklistReason = reason } var didReportFederationHasBeenEnabled: Bool = false func apiVersionResolverDetectedFederationHasBeenEnabled() { didReportFederationHasBeenEnabled = true } }
gpl-3.0
1b90e68996a142d847f31b933ae1753f
33.211699
100
0.656815
4.952419
false
false
false
false
squiffy/AlienKit
Example/AlienKit/ViewController.swift
1
1900
// // ViewController.swift // AlienKit // // Created by Squiffy on 03/17/2016. // Copyright (c) 2016 Squiffy. All rights reserved. // import UIKit import AlienKit class ViewController: UIViewController { var client :UserlessClient? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.client = UserlessClient(id: "YwBLaxHJevLYPg") client!.authorize({ self.client!.getPostsFrom("apple", success: { listing in for thing in listing.things { if let link = thing as? Link { print(link.title) } } if let thing = listing.things[0] as? Link { self.client!.getCommentsFor(thing, sort: .Top, success: { listing in if let thing = listing.things[0] as? Comment { print(thing.body!) if let subThing = thing.replies?.things[0] as? Comment { print(subThing.body!) } } }, failure: { }) } }, failure: { print("could not get posts.") }) }, failure: { _ in print("could not auth") }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
907636b7e65e848f7e20e7a874be4d6d
26.142857
88
0.407368
5.828221
false
false
false
false
exponent/exponent
packages/expo-modules-core/ios/Swift/Views/ComponentData.swift
2
3527
// Copyright 2021-present 650 Industries. All rights reserved. /** Custom component data extending `RCTComponentData`. Its main purpose is to handle event-based props (callbacks), but it also simplifies capturing the view config so we can omit some reflections that React Native executes. */ @objc(EXComponentData) public final class ComponentData: EXComponentDataCompatibleWrapper { /** Weak pointer to the holder of a module that the component data was created for. */ weak var moduleHolder: ModuleHolder? /** Initializer that additionally takes the original view module to have access to its definition. */ @objc public init(viewModule: ViewModuleWrapper, managerClass: ViewModuleWrapper.Type, bridge: RCTBridge) { self.moduleHolder = viewModule.wrappedModuleHolder super.init(managerClass: managerClass, bridge: bridge, eventDispatcher: bridge.eventDispatcher()) } // MARK: RCTComponentData /** Creates a setter for the specific prop. For non-event props we just let React Native do its job. Events are handled differently to conveniently use them in Swift. */ public override func createPropBlock(_ propName: String, isShadowView: Bool) -> RCTPropBlockAlias { // Expo Modules Core doesn't support shadow views yet, so fall back to the default implementation. if isShadowView { return super.createPropBlock(propName, isShadowView: isShadowView) } // If the prop is defined as an event, create our own event setter. if moduleHolder?.viewManager?.eventNames.contains(propName) == true { return createEventSetter(eventName: propName, bridge: self.manager?.bridge) } // Otherwise also fall back to the default implementation. return super.createPropBlock(propName, isShadowView: isShadowView) } /** The base `RCTComponentData` class does some Objective-C dynamic calls in this function, but we don't need to do these slow operations since the Sweet API gives us necessary details without reflections. */ public override func viewConfig() -> [String: Any] { var propTypes: [String: Any] = [:] var directEvents: [String] = [] let superClass: AnyClass? = managerClass.superclass() if let eventNames = moduleHolder?.viewManager?.eventNames { for eventName in eventNames { directEvents.append(RCTNormalizeInputEventName(eventName)) propTypes[eventName] = "BOOL" } } return [ "propTypes": propTypes, "directEvents": directEvents, "bubblingEvents": [String](), "baseModuleName": superClass?.moduleName() as Any ] } } /** Creates a setter for the event prop. */ private func createEventSetter(eventName: String, bridge: RCTBridge?) -> RCTPropBlockAlias { return { [weak bridge] (target: RCTComponent, value: Any) in // Find view's property that is named as the prop and is wrapped by `Event`. let child = Mirror(reflecting: target).children.first { $0.label == "_\(eventName)" } guard let event = child?.value as? AnyEventInternal else { return } // For callbacks React Native passes a bool value whether the prop is specified or not. if value as? Bool == true { event.settle { [weak target] (body: Any) in if let target = target { let componentEvent = RCTComponentEvent(name: eventName, viewTag: target.reactTag, body: ["payload": body]) bridge?.eventDispatcher().send(componentEvent) } } } else { event.invalidate() } } }
bsd-3-clause
9117b4018a43639259c2ea0761bd28b2
36.126316
116
0.704281
4.365099
false
false
false
false
joshgoesthedistance/TZStackView
TZStackViewDemo/ExplicitIntrinsicContentSizeView.swift
6
1071
// // Created by Tom van Zummeren on 10/06/15. // Copyright (c) 2015 Tom van Zummeren. All rights reserved. // import UIKit class ExplicitIntrinsicContentSizeView: UIView { let name: String let contentSize: CGSize init(intrinsicContentSize: CGSize, name: String) { self.name = name self.contentSize = intrinsicContentSize super.init(frame: CGRectZero) let gestureRecognizer = UITapGestureRecognizer(target: self, action: "tap") addGestureRecognizer(gestureRecognizer) userInteractionEnabled = true } func tap() { UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .AllowUserInteraction, animations: { self.hidden = true }, completion: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func intrinsicContentSize() -> CGSize { return contentSize } override var description: String { return name } }
mit
fb65ec6da6c69df3144545cc8e162d6e
25.121951
150
0.665733
4.935484
false
false
false
false
ByteriX/BxInputController
BxInputController/Sources/Rows/Variants/BxInputVariantRow.swift
1
2116
/** * @file BxInputVariantRow.swift * @namespace BxInputController * * @details Row for choosing one item from variant from selector with keyboard frame * @date 10.01.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Row for choosing one item from variant from selector with keyboard frame /// - parameter: T - is associated data model for variant rows, should be inherited from BxInputStringObject open class BxInputVariantRow<T : BxInputStringObject> : BxInputValueRow, BxInputVariant { /// Make and return Binder for binding row with cell. open var binder : BxInputRowBinder { return BxInputVariantRowBinder<T, BxInputStandartTextCell>(row: self) } open var resourceId : String { get { return "BxInputStandartTextCell" } } open var estimatedHeight : CGFloat { get { return 60 } } open var title : String? open var subtitle : String? open var placeholder : String? open var isEnabled : Bool = true open var items: [T] = [] open var value: T? /// Return true if value for the row is empty open var hasEmptyValue: Bool { return value == nil } internal var variants: [BxInputStringObject] { get { return items } } internal var selectedVariant: BxInputStringObject? { get { return value } set(value) { if let value = value as? T { self.value = value } else { self.value = nil } } } public init(title: String? = nil, subtitle: String? = nil, placeholder: String? = nil, value: T? = nil) { self.title = title self.subtitle = subtitle self.placeholder = placeholder self.value = value } /// event when value of current row was changed open func didChangeValue(){ // } }
mit
db2072c172ecc0649823cdad8410edc7
26.842105
108
0.617675
4.408333
false
false
false
false
nbkhope/swift
swift2/tour_01.swift
1
2213
/** * Swift Tour 01 * These statements should be used in a playground */ // The print function print("Hello World") // Constants and Variables let PageTotal = 20 var count: Int // You don't need semicolons to end a statement in Swift print("There are \(PageTotal) pages you have to read.") // Parenthesis are optional for count = 0; count < PageTotal; count++ { print ("Reading page \(count+1)...") } // Braces are mandatory even for single-statement if's if count == PageTotal { print("You have read everything. Good!") } else { print("Why didn't you read everything?") } print("") // Explicit declaration & initialization let myVar1: Float = 4 // Values are never implicitly converted to another type let label = "The width is " let width = 94 let widthLabel = label + String(width) let yourName = "Jackson" // String interpolation print("Hello, mr. \(yourName). Here is a fp number: \(3.4 + 7.5)") // Arrays var shoppingList = ["catfish", "water", "tulips", "blue paint"] print("Your second item is \(shoppingList[1])") // Dictionary var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] let firstDude = "Malcolm" let separator = " and " let secondDude = "Kaylee" print("Your dictionary contains the following values: \(occupations[firstDude]! + separator + occupations[secondDude]!)") print("Your dictionary contains the following values: \(occupations[firstDude]) and \(occupations[secondDude])") // Note the Optional("...") thingie let dictValue = "Your dictionary contains the value \(occupations[firstDude])." // This one works out fine. The above only appears if you try doing string interpolation let anotherDictValue = occupations["Kaylee"] print("") // Create empty array and dictionary // (if you use let instead of var, // then you won't be able to assign any values after this) var emptyArray = [Int]() // array of integers var emptyDict = [String: Int]() // dict that maps from String to Int emptyArray = [2, 4, 5, 6, 6] emptyDict = ["James": 24000, "Holly": 36000, "Alicia": 76800] for item in emptyArray { print("Number is \(item)") } print("") // foreach loop for (key, value) in emptyDict { print("Employee \(key) makes U$ \(value) per year.") }
gpl-2.0
2aeee857e0833bf744c4767774564a68
24.147727
121
0.69634
3.518283
false
false
false
false
Pluto-tv/RxSwift
RxSwift/Observables/Implementations/ShareReplay1.swift
1
2070
// // ShareReplay1.swift // Rx // // Created by Krunoslav Zaher on 10/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // optimized version of share replay for most common case class ShareReplay1<Element> : Observable<Element>, ObserverType { private let _source: Observable<Element> private let _lock = NSRecursiveLock() private var _subscription: Disposable? private var _element: Element? private var _stopEvent = nil as Event<Element>? private var _observers = Bag<AnyObserver<Element>>() init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { return _lock.calculateLocked { if let element = self._element { observer.on(.Next(element)) } if let stopEvent = self._stopEvent { observer.on(stopEvent) return NopDisposable.instance } let initialCount = self._observers.count let observerKey = self._observers.insert(AnyObserver(observer)) if initialCount == 0 { self._subscription = self._source.subscribe(self) } return AnonymousDisposable { self._lock.performLocked { self._observers.removeKey(observerKey) if self._observers.count == 0 { self._subscription?.dispose() self._subscription = nil } } } } } func on(event: Event<E>) { _lock.performLocked { if self._stopEvent != nil { return } if case .Next(let element) = event { self._element = element } if event.isStopEvent { self._stopEvent = event } _observers.forEach { o in o.on(event) } } } }
mit
725d4203d9eab3a3e3dec31f6673eeaa
25.883117
89
0.528758
4.997585
false
false
false
false
eaplatanios/jelly-bean-world
api/swift/Sources/JellyBeanWorld/Rendering.swift
1
10142
// Copyright 2019, The Jelly Bean World Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import Foundation import PythonKit fileprivate let np = Python.import("numpy") fileprivate let mpl = Python.import("matplotlib") fileprivate let plt = Python.import("matplotlib.pyplot") fileprivate let collections = Python.import("matplotlib.collections") fileprivate let patches = Python.import("matplotlib.patches") fileprivate let AGENT_RADIUS = 0.5 fileprivate let ITEM_RADIUS = 0.4 fileprivate let MAXIMUM_SCENT = 0.9 fileprivate var FIGURE_COUNTER = 0 /// Returns the agent's position in the figure, given the direction in which it is facing. fileprivate func agentPosition(_ direction: Direction) -> (x: Float, y: Float, angle: Float) { switch direction { case .up: return (x: 0.0, y: -0.1, angle: 0.0) case .down: return (x: 0.0, y: 0.1, angle: Float.pi) case .left: return (x: 0.1, y: 0.0, angle: Float.pi / 2) case .right: return (x: -0.1, y: 0.0, angle: 3 * Float.pi / 2) } } /// Simulation map visualizer. public final class MapVisualizer { private let simulator: Simulator private let figureID: String private let fig: PythonObject private let ax: PythonObject private let axAgent: PythonObject? private var xLim: (Float, Float) private var yLim: (Float, Float) public init( for simulator: Simulator, bottomLeft: Position, topRight: Position, agentPerspective: Bool = true ) { self.simulator = simulator self.figureID = "Jelly Bean World Visualization \(FIGURE_COUNTER)" FIGURE_COUNTER += 1 self.xLim = (Float(bottomLeft.x), Float(topRight.x)) self.yLim = (Float(bottomLeft.y), Float(topRight.y)) plt.ion() if agentPerspective { let figure = plt.subplots(nrows: 1, ncols: 2, num: self.figureID) self.fig = figure[0] self.ax = figure[1][0] self.axAgent = figure[1][1] self.fig.set_size_inches(w: 18, h: 9) } else { let figure = plt.subplots(num: self.figureID) self.fig = figure[0] self.ax = figure[1] self.axAgent = nil self.fig.set_size_inches(w: 9, h: 9) } self.fig.tight_layout() } deinit { plt.close(fig) } private func pause(_ interval: Float) { let backend = plt.rcParams["backend"] if Array(mpl.rcsetup.interactive_bk).contains(backend) { let figManager = mpl._pylab_helpers.Gcf.get_active() if figManager != Python.None { let canvas = figManager.canvas if Bool(canvas.figure.stale)! { canvas.draw() } canvas.start_event_loop(interval) } } } public func draw() throws { if !Bool(plt.fignum_exists(figureID))! { fatalError("The Jelly Bean World rendering window has been closed.") } let bottomLeft = Position(x: Int64(floor(xLim.0)), y: Int64(floor(yLim.0))) let topRight = Position(x: Int64(ceil(xLim.1)), y: Int64(ceil(yLim.1))) let map = try simulator.map(bottomLeft: bottomLeft, topRight: topRight) let n = Int(simulator.configuration.patchSize) ax.clear() ax.set_xlim(xLim.0, xLim.1) ax.set_ylim(yLim.0, yLim.1) // Draw all the map patches. for patch in map.patches { let color = PythonObject( tupleContentsOf: patch.fixed ? [0.0, 0.0, 0.0, 0.3] : [0.0, 0.0, 0.0, 0.1]) let a = Python.slice(Python.None, Python.None, Python.None) let x = Int(patch.position.x) let y = Int(patch.position.y) let verticalLines = np.empty(shape: [n + 1, 2, 2]) verticalLines[a, 0, 0] = np.add(np.arange(n + 1), x * n) - 0.5 verticalLines[a, 0, 1] = np.subtract(y * n, 0.5) verticalLines[a, 1, 0] = np.add(np.arange(n + 1), x * n) - 0.5 verticalLines[a, 1, 1] = np.add(y * n, n) - 0.5 let verticalLineCol = collections.LineCollection( segments: verticalLines, colors: color, linewidths: 0.4, linestyle: "solid") ax.add_collection(verticalLineCol) let horizontalLines = np.empty(shape: [n + 1, 2, 2]) horizontalLines[a, 0, 0] = np.subtract(x * n, 0.5) horizontalLines[a, 0, 1] = np.add(np.arange(n + 1), y * n) - 0.5 horizontalLines[a, 1, 0] = np.add(x * n, n) - 0.5 horizontalLines[a, 1, 1] = np.add(np.arange(n + 1), y * n) - 0.5 let horizontalLinesCol = collections.LineCollection( segments: horizontalLines, colors: color, linewidths: 0.4, linestyle: "solid") ax.add_collection(horizontalLinesCol) var agentItemPatches = [PythonObject]() // Add the agent patches. for agent in patch.agents { let x = Float(agent.position.x) let y = Float(agent.position.y) let position = agentPosition(agent.direction) agentItemPatches.append(patches.RegularPolygon( [x + position.x, y + position.y], numVertices: 3, radius: AGENT_RADIUS, orientation: position.angle, facecolor: simulator.configuration.agentColor.scalars, edgecolor: [0.0, 0.0, 0.0], linestyle: "solid", linewidth: 0.4)) } // Add the item patches. for item in patch.items { let id = item.itemType let x = Float(item.position.x) let y = Float(item.position.y) if simulator.configuration.items[id].blocksMovement { agentItemPatches.append(patches.Rectangle( [x - 0.5, y - 0.5], width: 1.0, height: 1.0, facecolor: simulator.configuration.items[id].color.scalars, edgecolor: [0.0, 0.0, 0.0], linestyle: "solid", linewidth: 0.4)) } else { agentItemPatches.append(patches.Circle( [x, y], radius: ITEM_RADIUS, facecolor: simulator.configuration.items[id].color.scalars, edgecolor: [0.0, 0.0, 0.0], linestyle: "solid", linewidth: 0.4)) } } // Convert 'scent' to a numpy array and transform it into // a subtractive color space (so that zero corresponds to white). var scentImg = patch.scent.makeNumpyArray() scentImg = np.divide(np.log(np.power(scentImg, 0.4) + 1), MAXIMUM_SCENT) scentImg = np.clip(scentImg, 0.0, 1.0) scentImg = 1.0 - 0.5 * np.dot(scentImg, [[0, 1, 1], [1, 0, 1], [1, 1, 0]]) let left = Float(x * n) - 0.5 let right = Float(x * n + n) - 0.5 let bottom = Float(y * n) - 0.5 let top = Float(y * n + n) - 0.5 ax.imshow(np.rot90(scentImg), extent: [left, right, bottom, top]) // Add the agent and item patches to the plots. let agentItemPatchCol = collections.PatchCollection(agentItemPatches, match_original: true) ax.add_collection(agentItemPatchCol) } // Draw the agent's perspective. if simulator.agents.keys.contains(0) { if let axAgent = axAgent { let agentState = simulator.agentStates[0]! let r = Int(simulator.configuration.visionRange) let a = Python.slice(Python.None, Python.None, Python.None) axAgent.clear() axAgent.set_xlim(-Float(r) - 0.5, Float(r) + 0.5) axAgent.set_ylim(-Float(r) - 0.5, Float(r) + 0.5) let verticalLines = np.empty(shape: [2 * r, 2, 2]) verticalLines[a, 0, 0] = np.subtract(np.arange(2 * r), r) + 0.5 verticalLines[a, 0, 1] = np.subtract(-r, 0.5) verticalLines[a, 1, 0] = np.subtract(np.arange(2 * r), r) + 0.5 verticalLines[a, 1, 1] = np.add(r, 0.5) let verticalLineCol = collections.LineCollection( segments: verticalLines, colors: [0.0, 0.0, 0.0, 0.3], linewidths: 0.4, linestyle: "solid") axAgent.add_collection(verticalLineCol) let horizontalLines = np.empty(shape: [2 * r, 2, 2]) horizontalLines[a, 0, 0] = np.subtract(-r, 0.5) horizontalLines[a, 0, 1] = np.subtract(np.arange(2 * r), r) + 0.5 horizontalLines[a, 1, 0] = np.add(r, 0.5) horizontalLines[a, 1, 1] = np.subtract(np.arange(2 * r), r) + 0.5 let horizontalLinesCol = collections.LineCollection( segments: horizontalLines, colors: [0.0, 0.0, 0.0, 0.3], linewidths: 0.4, linestyle: "solid") axAgent.add_collection(horizontalLinesCol) // Add the agent patch to the plot. let position = agentPosition(.up) let agentPatch = patches.RegularPolygon( [position.x, position.y], numVertices: 3, radius: AGENT_RADIUS, orientation: position.angle, facecolor: simulator.configuration.agentColor.scalars, edgecolor: [0.0, 0.0, 0.0], linestyle: "solid", linewidth: 0.4) let agentPatchCol = collections.PatchCollection([agentPatch], match_original: true) axAgent.add_collection(agentPatchCol) // Convert 'vision' to a numpy array and transform it into // a subtractive color space (so that zero corresponds to white). var visionImg = agentState.vision.makeNumpyArray() visionImg = 1.0 - 0.5 * np.dot(visionImg, [[0, 1, 1], [1, 0, 1], [1, 1, 0]]) let left = -Float(r) - 0.5 let right = Float(r) + 0.5 let bottom = -Float(r) - 0.5 let top = Float(r) + 0.5 axAgent.imshow(np.rot90(visionImg), extent: [left, right, bottom, top]) } } pause(1e-16) plt.draw() let pltXLim = ax.get_xlim() let pltYLim = ax.get_ylim() xLim = (Float(pltXLim[0])!, Float(pltXLim[1])!) yLim = (Float(pltYLim[0])!, Float(pltYLim[1])!) } }
apache-2.0
63929c6bc5215fb26b79428cd43e7f6f
36.424354
97
0.609939
3.224801
false
false
false
false
wl879/SwiftyCss
SwiftyCss/SwiftyBox/Weak.swift
1
2713
// Created by Wang Liang on 2017/4/8. // Copyright © 2017年 Wang Liang. All rights reserved. import Foundation public class Weak <Element: AnyObject>: CustomStringConvertible { public weak var value : Element? public init(_ value: Element) { self.value = value } public final var description: String { return "Weak(" + (self.value != nil ? String(describing: self.value!) : "nil") + ")" } } public class WeakArray <Element: AnyObject> { public var list: [Weak<Element>] public init() { list = [Weak<Element>]() } public var count: Int { return list.count } public final var array: [Element] { var arr = [Element]() for i in 0 ..< list.count { if list[i].value != nil { arr.append(list[i].value!) } } return arr } public subscript (index: Int) -> Element? { if index >= 0 && index < list.count { return list[index].value } return nil } public final func refrehs() -> WeakArray { for i in (0 ..< list.count).reversed() { if list[i].value == nil { list.remove(at: i) } } return self } public final func insert(_ element: Element, at: Int) { self.list.insert( Weak( element ), at: at) } public final func append(_ element: Element) { list.append( Weak( element ) ) } public final func remove(_ element: Element){ for i in (0 ..< list.count).reversed() { if list[i].value === element { list.remove(at: i) } } } public final func remove(at: Int) -> Element? { let elm = list.remove(at: at < 0 ? list.count + at : at) return elm.value } } public class WeakDict <Key: Hashable, Element: AnyObject> { public var dict: [Key: Weak<Element>] public init() { dict = [Key: Weak<Element>]() } public var count: Int { return dict.count } public var values: [Element?] { var res = [Element?]() for (_, v) in dict { res.append( v.value ) } return res } public var keys: LazyMapCollection<Dictionary<Key, Weak<Element>>, Key> { return dict.keys } public subscript (key: Key) -> Element? { get { return dict[key]?.value } set { if newValue == nil { dict[key] = nil }else{ dict[key] = Weak( newValue! ) } } } }
mit
de5b794eec1b4c69e989a4d87409a545
21.966102
92
0.49262
4.182099
false
false
false
false
TurfDb/Turf
Turf/ChangeSet/CollectionRowChange.swift
1
729
public enum CollectionRowChange<Key: Equatable> { case insert(key: Key) case update(key: Key) case remove(key: Key) public var key: Key { switch self { case .insert(let key): return key case .update(let key): return key case .remove(let key): return key } } } public func ==<Key>(lhs: CollectionRowChange<Key>, rhs: CollectionRowChange<Key>) -> Bool { switch (lhs, rhs) { case (.insert(let leftKey), .insert(let rightKey)): return leftKey == rightKey case (.update(let leftKey), .update(let rightKey)): return leftKey == rightKey case (.remove(let leftKey), .remove(let rightKey)): return leftKey == rightKey default: return false } }
mit
9270522702873414d0f4461f02d09eb0
30.695652
91
0.631001
3.898396
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Announcements/Test Doubles/CapturingAnnouncementsScene.swift
1
886
@testable import Eurofurence import EurofurenceModel import UIKit class CapturingAnnouncementsScene: UIViewController, AnnouncementsScene { private(set) var delegate: AnnouncementsSceneDelegate? func setDelegate(_ delegate: AnnouncementsSceneDelegate) { self.delegate = delegate } private(set) var capturedTitle: String? func setAnnouncementsTitle(_ title: String) { capturedTitle = title } private(set) var capturedAnnouncementsToBind: Int? private(set) var binder: AnnouncementsBinder? func bind(numberOfAnnouncements: Int, using binder: AnnouncementsBinder) { capturedAnnouncementsToBind = numberOfAnnouncements self.binder = binder } private(set) var capturedAnnouncementIndexToDeselect: Int? func deselectAnnouncement(at index: Int) { capturedAnnouncementIndexToDeselect = index } }
mit
24ded2726a9bae307d2e427e107f994c
29.551724
78
0.742664
5.181287
false
false
false
false
itsProf/quito-seguro-ios
Quito Seguro/Tips/TipsTableViewController.swift
1
4394
// // TipsTableViewController.swift // Quito Seguro // // Created by Jorge Tapia on 4/18/16. // Copyright © 2016 Prof Apps. All rights reserved. // import UIKit import Firebase let tipIdentifier = "TipCell" class TipsTableViewController: UITableViewController { var data = [FDataSnapshot]() override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) refresh() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - UI methods private func setupUI() { clearsSelectionOnViewWillAppear = false tableView.rowHeight = 88.0 tableView.tableFooterView = UIView(frame: CGRectZero) navigationController?.navigationBar.tintColor = UIColor.whiteColor() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) // Setup refresh control refreshControl = UIRefreshControl() refreshControl?.backgroundColor = AppTheme.primaryDarkColor refreshControl?.tintColor = UIColor.whiteColor() refreshControl?.addTarget(self, action: #selector(StatsTableViewController.refresh), forControlEvents: .ValueChanged) } // MARK: - Data methods func refresh() { let reportsRef = Firebase(url: "\(AppUtils.firebaseAppURL)/tips") reportsRef.observeEventType(.Value, withBlock: { (snapshot) in self.data.removeAll() for child in snapshot.children.allObjects as! [FDataSnapshot] { self.data.append(child) } reportsRef.removeAllObservers() dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.refreshControl?.endRefreshing() } }) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destinationViewController = segue.destinationViewController as! TipDetailTableViewController destinationViewController.tip = sender } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(tipIdentifier, forIndexPath: indexPath) let locale = NSLocale.preferredLanguages().first let tip = data[indexPath.row].value let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = AppTheme.tableVieCellSelectionColor cell.selectedBackgroundView = selectedBackgroundView cell.textLabel?.font = AppTheme.defaultMediumFont?.fontWithSize(16.0) cell.textLabel?.textColor = AppTheme.redColor cell.detailTextLabel?.font = AppTheme.defaultFont?.fontWithSize(14.0) if locale!.containsString("es") { cell.textLabel?.text = tip["titleES"] as? String cell.detailTextLabel?.text = tip["summaryES"] as? String } else { cell.textLabel?.text = tip["titleEN"] as? String cell.detailTextLabel?.text = tip["summaryEN"] as? String } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { if let url = NSURL(string: tip["thumbnail"] as! String) { if let data = NSData(contentsOfURL: url) { dispatch_async(dispatch_get_main_queue()) { if let updateCell = self.tableView.cellForRowAtIndexPath(indexPath) { updateCell.imageView?.image = UIImage(data: data) } } } } } return cell } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let tip = data[indexPath.row].value performSegueWithIdentifier("tipSegue", sender: tip) } }
mit
e61b1844e04497b3d598a9a909d2acf2
33.590551
125
0.622581
5.450372
false
false
false
false
mhv/Utils
Utils/SparseArray.swift
1
1441
// // SparseArray.swift // Signal // // Created by Mikhail Vroubel on 07/02/2015. // // import Foundation public struct SparseArray<T> : CollectionType { public init(){} public typealias Element = (Int, T) public typealias Index = DictionaryIndex<Int, T> var indices = NSMutableIndexSet() var accessor = [Int: T]() public var startIndex: Index {return accessor.startIndex} public var endIndex: Index {return accessor.endIndex} public subscript (position: Index) -> Element {return accessor[position]} public func generate() -> AnyGenerator<Element> { var last = indices.firstIndex - 1 return anyGenerator { last = self.indices.indexGreaterThanIndex(last) return last != NSNotFound ? (last, self.accessor[last]!) : nil } } public subscript (i idx:Int)->T? { get {return accessor[idx]} set (value) { if let v = value { append(v, index: idx) } else { removeAtIndex(idx) } } } public mutating func append(value:T, index:Int = 0)->Int { let next = max(indices.count > 0 ? indices.lastIndex + 1 : 0, index) indices.addIndex(next) accessor[index] = value return next } public mutating func removeAtIndex(index: Int) { accessor[index] = nil indices.removeIndex(index) } }
mit
5e0a6a164025c891e0f6b62e2455ff64
26.730769
77
0.58848
4.314371
false
false
false
false
programmerC/JNews
JNews/DetailShareTableViewCell.swift
1
1916
// // DetailShareTableViewCell.swift // JNews // // Created by ChenKaijie on 16/8/18. // Copyright © 2016年 com.ckj. All rights reserved. // import UIKit protocol DetailShareTableViewCellDelegate { func shareCellButtonCallBack() } class DetailShareTableViewCell: UITableViewCell { @IBOutlet weak var shareTitle: UILabel! @IBOutlet weak var shareButton: UIButton! var delegate: DetailShareTableViewCellDelegate? var newsType: NSInteger { get { return 0 } set(newValue) { var color: UIColor = UIColor.clearColor() switch newValue { case 0: color = TopLineColor case 1: color = EntertainmentColor case 2: color = SportsColor case 3: color = TechnologyColor case 4: color = PoliticsColor case 5: color = SocietyColor case 6: color = HealthColor case 7: color = InternationalColor default: return } // Assign shareButton.backgroundColor = color shareButton.layer.borderColor = color.CGColor } } override func awakeFromNib() { super.awakeFromNib() shareButton.layer.borderWidth = 1 shareButton.layer.cornerRadius = 18.0 shareButton.layer.masksToBounds = true } @IBAction func shareButtonAction(sender: UIButton) { guard delegate != nil else { print("你特么没代理啊!") return } delegate?.shareCellButtonCallBack() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
c19beaeca1755c3666a2fcb842e6c2dc
25.013699
63
0.558715
5.20274
false
false
false
false
Pacific3/P3UIKit
Sources/Extensions/UITableView.swift
1
2258
// // UITableView.swift // P3UIKit // // Created by Oscar Swanros on 7/11/16. // Copyright © 2016 Pacific3. All rights reserved. // #if os(iOS) || os(tvOS) public extension UITableView { func register<T: UITableViewCell>(cellClass: T.Type) { register(cellClass, forCellReuseIdentifier: UITableView.reuseIdentifier(class: cellClass)) } func dequeue<T: UITableViewCell>(for indexPath: IndexPath, type: T.Type) -> T { guard let c = dequeueReusableCell(withIdentifier: UITableView.reuseIdentifier(class: type), for: indexPath) as? T else { fatalError("Cell \(String(describing: type)) not configured correctly for reuse.") } return c } private static func reuseIdentifier<T: UITableViewCell>(class _class: T.Type) -> String { return (Bundle(for: _class).bundleIdentifier ?? "_P3BundleIdentifier") + String(describing: _class) } func p3_layoutTableHeaderView() { guard let headerView = self.tableHeaderView else { return } headerView.translatesAutoresizingMaskIntoConstraints = false let headerWidth = headerView.bounds.size.width; let temporaryWidthConstraints = NSLayoutConstraint.constraints( withVisualFormat: "[headerView(width)]", options: NSLayoutConstraint.FormatOptions(rawValue: UInt(0)), metrics: ["width": headerWidth], views: ["headerView": headerView] ) headerView.addConstraints(temporaryWidthConstraints) headerView.setNeedsLayout() headerView.layoutIfNeeded() let headerSize = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) let height = headerSize.height var frame = headerView.frame frame.size.height = height headerView.frame = frame self.tableHeaderView = headerView headerView.removeConstraints(temporaryWidthConstraints) headerView.translatesAutoresizingMaskIntoConstraints = true } } #endif
mit
e1c8b4bdf3dae0894815a5cc2e46fd23
38.596491
132
0.611431
5.713924
false
false
false
false
gang462234887/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/foodMaterial/view/CBMaterialCell.swift
1
4177
// // CBMaterialCell.swift // TestKitchen // // Created by qianfeng on 16/8/24. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class CBMaterialCell: UITableViewCell { var model:CBMaterialTypeModel?{ didSet{ if model != nil{ showData() } } } func showData(){ //1.删除之前的子视图 for oldSub in contentView.subviews{ oldSub.removeFromSuperview() } //2.添加子视图 //2.1标题 let titleLabel = UILabel.createLabel(model?.text, font: UIFont.systemFontOfSize(24), textAlignment: .Left, textColor: UIColor.blackColor()) titleLabel.frame = CGRectMake(20, 0, kScreenWidth-20*2, 40) contentView.addSubview(titleLabel) let spaceX:CGFloat = 10 let spaceY:CGFloat = 10 let colNum = 5 let h:CGFloat = 40 let w = (kScreenWidth-spaceX*CGFloat(colNum+1))/CGFloat(colNum) let offsetY:CGFloat = 40 //2.2图片 let imageFrame = CGRectMake(spaceX, offsetY, w*2+spaceX, h*2+spaceY) let imageView = UIImageView.createImageView(nil) imageView.frame = imageFrame let url = NSURL(string: (model?.image)!) imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) contentView.addSubview(imageView) //2.3循环创建按钮 if model?.data?.count > 0{ for i in 0..<(model?.data?.count)!{ var btnFrame = CGRectZero if i<6{ //前两行的按钮 let row = i/3 let col = i%3 btnFrame = CGRectMake(w*2+spaceX*3+CGFloat(col)*(w+spaceX), offsetY+CGFloat(row)*(h+spaceY), w, h) }else{ //后面两行的按钮 let row = (i-6)/5 let col = (i-6)%5 btnFrame = CGRectMake(spaceX+CGFloat(col)*(spaceX+w), offsetY+2*(h+spaceY)+CGFloat(row)*(h+spaceY), w, h) } let btn = CBMaterialBtn(frame: btnFrame) let subModel = model?.data![i] btn.model = subModel contentView.addSubview(btn) } } } class func heightWithModel(model:CBMaterialTypeModel)->CGFloat{ var h:CGFloat = 0 let offsetY:CGFloat = 40 let spaceY:CGFloat = 20 let btnH:CGFloat = 40 if model.data?.count > 0{ if model.data?.count < 6{ h = offsetY+(btnH+spaceY)*2 }else{ //计算多少行 h = offsetY+(btnH+spaceY)*2 var rowNum = ((model.data?.count)!-6) / 5 if ((model.data?.count)! - 6)%5 > 0 { rowNum += 1 } h += CGFloat(rowNum)*(btnH+spaceY) } } return h } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } class CBMaterialBtn: UIControl { private var titleLabel:UILabel? var model:CBMaterialSubtypeModel?{ didSet{ titleLabel?.text = model?.text } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(white: 0.8, alpha: 1.0) titleLabel = UILabel.createLabel(nil, font: UIFont.systemFontOfSize(14), textAlignment: .Center, textColor: UIColor.blackColor()) titleLabel?.frame = bounds addSubview(titleLabel!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
5af2dfb05e8b4ff7c4867899c81aaf8b
27.027397
154
0.51784
4.511577
false
false
false
false
taketo1024/SwiftyAlgebra
Tests/SwmCoreTests/Polynomials/PolynomialTests.swift
1
3863
// // PolynomialTests.swift // SwiftyKnotsTests // // Created by Taketo Sano on 2018/04/10. // import XCTest @testable import SwmCore class PolynomialTests: XCTestCase { struct _x: PolynomialIndeterminate { static let degree: Int = 1 static let symbol: String = "x" } typealias A = Polynomial<𝐙, _x> typealias B = Polynomial<𝐐, _x> func testInitFromInt() { let a = A(from: 3) XCTAssertEqual(a, A(elements: [0: 3])) } func testInitFromIntLiteral() { let a: A = 3 XCTAssertEqual(a, A(elements: [0: 3])) } func testInitFromCoeffList() { let a = A(coeffs: 3, 5, -1) XCTAssertEqual(a, A(elements: [0: 3, 1: 5, 2: -1])) } func testProperties() { let a = A(coeffs: 3, 4, 0, 5) XCTAssertEqual(a.leadCoeff, 5) XCTAssertEqual(a.leadTerm, A(elements: [3: 5])) XCTAssertEqual(a.constTerm, A(3)) XCTAssertEqual(a.leadExponent, 3) XCTAssertEqual(a.degree, 3) XCTAssertFalse(a.isMonomial) } func testIndeterminate() { let x = A.indeterminate XCTAssertEqual(x, A(elements: [1: 1])) XCTAssertEqual(x.description, "x") XCTAssertEqual(x.degree, 1) XCTAssertEqual(x.leadExponent, 1) XCTAssertTrue (x.isMonomial) } func testSum() { let a = A(coeffs: 1, 2, 3) let b = A(coeffs: 0, 1, 0, 2) XCTAssertEqual(a + b, A(coeffs: 1, 3, 3, 2)) } func testZero() { let a = A(coeffs: 1, 2, 3) XCTAssertEqual(a + A.zero, a) XCTAssertEqual(A.zero + a, a) } func testNeg() { let a = A(coeffs: 1, 2, 3) XCTAssertEqual(-a, A(coeffs: -1, -2, -3)) } func testScalarMul() { let a = A(coeffs: 1, 2, 3) XCTAssertEqual(3 * a, A(coeffs: 3, 6, 9)) } func testMul() { let a = A(coeffs: 1, 2, 3) let b = A(coeffs: 3, 4) XCTAssertEqual(a * b, A(coeffs: 3, 10, 17, 12)) } func testId() { let a = A(coeffs: 1, 2, 3) let e = A.identity XCTAssertEqual(a * e, a) XCTAssertEqual(e * a, a) } func testInv() { let a = A(coeffs: -1) XCTAssertEqual(a.inverse!, a) let b = A(coeffs: 3) XCTAssertNil(b.inverse) let c = A(coeffs: 1, 1) XCTAssertNil(c.inverse) } func testPow() { let a = A(coeffs: 1, 2) XCTAssertEqual(a.pow(0), A.identity) XCTAssertEqual(a.pow(1), a) XCTAssertEqual(a.pow(2), A(coeffs: 1, 4, 4)) XCTAssertEqual(a.pow(3), A(coeffs: 1, 6, 12, 8)) } func testDerivative() { let a = A(coeffs: 1, 2, 3, 4) XCTAssertEqual(a.derivative, A(coeffs: 2, 6, 12)) } func testEvaluate() { let a = A(coeffs: 1, 2, 3) XCTAssertEqual(a.evaluate(by: -1), 2) } func testIsMonic() { let a = A(coeffs: 1, 2, 1) XCTAssertTrue(a.isMonic) let b = A(coeffs: 1, 2, 3) XCTAssertFalse(b.isMonic) } func testEucDiv() { let a = B(coeffs: 1, 2, 1) let b = B(coeffs: 3, 2) let (q, r) = a /% b XCTAssertEqual(q, B(coeffs: 1./4, 1./2)) XCTAssertEqual(r, B(1./4)) XCTAssertTrue(a.euclideanDegree > r.euclideanDegree) XCTAssertEqual(a, q * b + r) } struct _t: PolynomialIndeterminate { static var symbol = "t" static var degree = 2 } func testCustomIndeterminate() { typealias T = Polynomial<𝐙, _t> let t = T.indeterminate XCTAssertEqual(t, T(elements: [1: 1])) XCTAssertEqual(t.description, "t") XCTAssertEqual(t.degree, 2) XCTAssertEqual(t.leadExponent, 1) } }
cc0-1.0
2e7ac2a067485e85b0635f5b22e5b139
24.865772
60
0.520758
3.322414
false
true
false
false
Eonil/JSON.Swift
Sources/JSON.swift
1
5067
// // JSON.swift // EoniJSON // // Created by Hoon H. on 10/21/14. // // import Foundation public struct JSON { public static func deserialize(_ data: Data) throws -> JSONValue { let o1 = try JSONSerialization.jsonObject(with: data, options: []) guard let o2 = o1 as? NSObject else { throw JSONError("Internal `NSJSONSerialization.JSONObjectWithData` returned non-`NSObject` object. Unacceptable. \(o1)") } let o3 = try Converter.convertFromOBJC(o2) return o3 } /// /// Encoding a JSON data does not support encoding of JSON fragment. /// Input JSON value must be one of `JSONArray` or `JSONObject`. /// This is due to limitation of `JSONSerialization` class. /// public static func serialize(_ value: JSONValue) throws -> Data { guard value.object != nil || value.array != nil else { throw JSONError("For now, encoding of JSON fragment is not supported.") } let o2:AnyObject = Converter.convertFromSwift(value) let d3:Data = try JSONSerialization.data(withJSONObject: o2, options: [.prettyPrinted]) return d3 } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MARK: - Privates //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Converts JSON tree between Objective-C and Swift representations. private struct Converter { typealias Value = JSONValue /// Gets strongly typed JSON tree. /// /// This function assumes input fully convertible data. /// Throws any error in conversion. /// /// Objective-C `nil` is not supported as an input. /// Use `NSNull` which is standard way to represent `nil` /// in data-structures in Cocoa. static func convertFromOBJC(_ v1: NSObject) throws -> Value { func convertArray(_ v1:NSArray) throws -> Value { var a2 = [] as [Value] for m1 in v1 { /// Must be an OBJC type. guard let m1 = m1 as? NSObject else { throw JSONError("Non-OBJC type object (that is not convertible) discovered.") } let m2 = try convertFromOBJC(m1) a2.append(m2) } return Value.array(a2) } func convertObject(_ v1: NSDictionary) throws -> Value { var o2 = [:] as [String:Value] for p1 in v1 { guard let k1 = p1.key as? NSString as String? else { throw JSONError("") } guard let p2 = p1.value as? NSObject else { throw JSONError("") } let v2 = try convertFromOBJC(p2) o2[k1] = v2 } return Value.object(o2) } if v1 is NSNull { return Value.null(Void()) } if let v2 = v1 as? NSNumber { /// `NSNumber` can be a `CFBoolean` exceptionally if it was created from a boolean value. if CFGetTypeID(v2) == CFBooleanGetTypeID() { let v3 = CFBooleanGetValue(v2) return Value.boolean(v3) } if CFNumberIsFloatType(v2) { return Value.number(try JSONNumber(v2.doubleValue)) } else { return Value.number(JSONNumber(v2.int64Value)) } } if let v1 = v1 as? NSString as String? { return Value.string(v1) } if let v1 = v1 as? NSArray { return try convertArray(v1) } if let v1 = v1 as? NSDictionary { return try convertObject(v1) } throw JSONError("Unsupported type. Failed.") } static func convertFromSwift(_ v1: Value) -> NSObject { func convertArray(_ a1: [Value]) -> NSArray { let a2 = NSMutableArray() for m1 in a1 { let m2 = convertFromSwift(m1) a2.add(m2) } return a2 } func convertObject(_ o1: [String: Value]) -> NSDictionary { let o2 = NSMutableDictionary() for (k1, v1) in o1 { let k2 = k1 as NSString let v2 = convertFromSwift(v1) o2.setObject(v2, forKey: k2) } return o2 } switch v1 { case Value.null(): return NSNull() case Value.boolean(let boolValue): return NSNumber(value: boolValue as Bool) case Value.number(let numberValue): switch numberValue.storage { case JSONNumber.Storage.int64(let int64Value): return NSNumber(value: int64Value as Int64) case JSONNumber.Storage.float64(let floatValue): return NSNumber(value: floatValue as Double) } case Value.string(let stringValue): return stringValue as NSString case Value.array(let arrayValue): return convertArray(arrayValue) case Value.object(let objectValue): return convertObject(objectValue) } } }
mit
4c854bb9b5176f62db16c508a6e799a8
36.257353
168
0.542925
4.52815
false
false
false
false
ithree1113/LocationTalk
LocationTalk/FriendInfo.swift
1
1386
// // FriendInfo.swift // LocationTalk // // Created by 鄭宇翔 on 2016/12/29. // Copyright © 2016年 鄭宇翔. All rights reserved. // import UIKit import Foundation enum FriendState { case friends case invite case beInvited case none } struct FriendInfo { var email: String var username: String var state: FriendState init(_ info: Dictionary<String, Any>) { self.email = info[Constants.FirebaseKey.email] as! String self.username = info[Constants.FirebaseKey.username] as! String switch info[Constants.FirebaseKey.state] as! String { case "\(FriendState.friends)": self.state = .friends break case "\(FriendState.invite)": self.state = .invite break case "\(FriendState.beInvited)": self.state = .beInvited break default: self.state = .none break } } init(email: String, username: String, state: FriendState) { self.email = email self.username = username self.state = state } func generateDict() -> Dictionary<String, Any> { let info = [Constants.FirebaseKey.email: self.email, Constants.FirebaseKey.username: self.username, Constants.FirebaseKey.state: "\(self.state)"] return info } }
mit
618c15a62e11c0f1b651b42a78b21edb
23.482143
153
0.59081
4.297806
false
false
false
false
jeffellin/VideoPlayer
VideoPlayer/ViewController.swift
1
1507
// // ViewController.swift // VideoPlayer // // Created by Jeffrey Ellin on 11/2/15. // Copyright © 2015 Jeffrey Ellin. All rights reserved. // import UIKit import AVKit import AVFoundation class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func doSomething() { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let fileManager = NSFileManager.defaultManager() let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(paths)! print (paths) var file:String = "" while let element = enumerator.nextObject() as? String { file = element } let url = NSURL.fileURLWithPath("\(paths)/\(file)") let player = AVPlayer(URL: url.absoluteURL) print(url.absoluteURL) let playerViewController = AVPlayerViewController() playerViewController.player = player self.addChildViewController(playerViewController) self.view.addSubview(playerViewController.view) playerViewController.view.frame = self.view.frame player.play() } }
apache-2.0
89aa45398efeec1023d1f159c5e66dab
23.688525
111
0.644754
5.456522
false
false
false
false
mcxiaoke/learning-ios
swift-language-guide/02_BasicOperators.playground/Contents.swift
1
1744
//: Playground - noun: a place where people can play // https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID60 // http://wiki.jikexueyuan.com/project/swift/chapter2/02_Basic_Operators.html import UIKit let b = 10 var a = 5 a = b let (x, y) = (1, 2) //if x = y { // = return nothing // code //} "hello, " + "world" 9 % 4 -9 % 4 8 % 2.5 9 % 2.5 var i = 0 ++i var aa = 0 let bb = ++aa let cc = aa++ let three = 3 let minusThree = -three let plusThree = -minusThree var a1 = 1 a1 += 2 let name = "world" if name == "world" { print("hello, world") }else{ print("hello, nobody") } let contentHeight = 40 let hasHeader = true let rowHeight = contentHeight + (hasHeader ? 50 : 20) var aStr: String? var bStr = "B String" aStr ?? bStr aStr != nil ? aStr! : bStr aStr = "A String" aStr ?? bStr aStr != nil ? aStr! : bStr let defaultColorName = "red" var userDefinedColorName: String? // default = nil var colorNameToUse = userDefinedColorName ?? defaultColorName for index in 1 ... 5 { print("\(index)*5 = \(index * 5)") } for index in 1 ..< 5 { print("\(index)*5 = \(index * 5)") } let names = ["Anna", "Alex", "Brian", "Jack"] let count = names.count for i in 0 ..< count { print("No.\(i+1) = \(names[i])") } let allowedEntry = false if !allowedEntry { print("Access Denied") } let enteredDoorCode = true let passedRetinaScan = false if enteredDoorCode && passedRetinaScan { print("Welcome!") }else{ print("Access Denied") } let hasDoorKey = false let knowsOverridePassword = true if hasDoorKey || knowsOverridePassword { print("Welcome!") }else{ print("Access Denied") }
apache-2.0
9207b49820df82e2e04390b1f363bf76
12.732283
160
0.642202
3.006897
false
false
false
false
typelift/Basis
Basis/Operators.swift
2
6516
// // Operators.swift // Basis // // Created by Robert Widmann on 9/7/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // /// MARK: Data.Combinator /// Function Composition | Composes the target of the left function with the source of the second /// function to pipe the results through one larger function from left source to right target. /// /// g • f x = g(f(x)) infix operator • { precedence 190 associativity right } /// Pair Formation | Forms a pair from two arguments. (⌥ + ⇧ + P) infix operator ∏ {} /// Pipe Backward | Applies the function to its left to an argument on its right. /// /// Chains of regular function applications are often made unnecessarily verbose and tedius by /// large amounts of parenthesis. Because this operator has a low precedence and is right- /// associative, it can often be used to elide parenthesis such that the following holds: /// /// f <| g <| h x = f (g (h x)) /// /// Haskellers will know this as the ($) combinator. infix operator <<| { precedence 0 associativity right } /// Pipe Forward | Applies the argument on its left to a function on its right. /// /// Sometimes, a computation looks more natural when data is organizaed with this operator. For /// example, this: /// /// and(zip(nubBy(==)(x))(y).map(==)) /// /// can also be written as: /// /// nubBy(==)(x) |>> zip(y) /// |>> map(==) /// |>> and infix operator |>> { precedence 0 associativity left } /// Cons | Constructs a list by appending a given element to the front of a list. infix operator <| { precedence 100 associativity right } /// Snoc | Constructs a list by appending a given element to the end of a list. infix operator |> { precedence 100 associativity left } /// On | Given a "combining" function and a function that converts arguments to the target of the /// combiner, returns a function that applies the right hand side to two arguments, then runs both /// results through the combiner. infix operator |*| { precedence 100 associativity left } /// "As Type Of" | A type-restricted version of const. In cases of typing ambiguity, using this /// function forces its first argument to resolve to the type of the second argument. /// /// Composed because it is the face one makes when having to tell the typechecker how to do its job. infix operator >-< { precedence 100 associativity left } /// MARK: Data.Monoid /// Mappend | An associative binary operator that combines two elements of a monoid's set. infix operator <> { precedence 160 associativity right } /// MARK: Control.Category /// Right-to-Left Composition | Composes two categories to form a new category with the source of /// the second category and the target of the first category. /// /// This function is literally `•`, but for Categories. infix operator <<< { precedence 110 associativity right } /// Left-to-Right Composition | Composes two categories to form a new category with the source of /// the first category and the target of the second category. /// /// Function composition with the arguments flipped. infix operator >>> { precedence 110 associativity right } /// MARK: Data.Functor /// "Replace" | Maps all the values "inside" one functor to a user-specified constant. infix operator <% { precedence 140 associativity left } /// Fmap | Like fmap, but infix for your convenience. infix operator <%> { precedence 140 associativity left } /// MARK: Data.Functor.Contravariant /// Contramap | Maps all values "inside" one functor contravariantly. infix operator >%< { precedence 140 associativity left } /// Replace | Maps all points to a specified constant contravariantly. infix operator >% { precedence 140 associativity left } /// MARK: Control.Applicative /// Ap | Promotes function application. infix operator <*> { precedence 140 associativity left } /// Sequence Right | Disregards the Functor on the Left. /// /// Default definition: /// `const(id) <%> a <*> b` infix operator *> { precedence 140 associativity left } /// Sequence Left | Disregards the Functor on the Right. /// /// Default definition: /// `const <%> a <*> b` infix operator <* { precedence 140 associativity left } /// Choose | Makes Applicative a monoid. infix operator <|> { precedence 130 associativity left } /// MARK: Control.Monad /// Bind | Composes two monadic actions by passing the value inside the monad on the left to the /// function on the right. infix operator >>- { precedence 110 associativity left } /// Bind | Composes two monadic actions by passing the value inside the monad on the right to the /// funciton on the left. infix operator -<< { precedence 110 associativity right } /// Left-to-Right Kleisli | infix operator >-> { precedence 110 associativity right } /// Right-to-Left Kleisli | infix operator <-< { precedence 110 associativity right } /// MARK: System.IO /// Extract | Extracts a value from a monadic computation. prefix operator ! {} /// MARK: Control.Arrow /// Split | Splits two computations and combines the result into one Arrow yielding a tuple of /// the result of each side. infix operator *** { precedence 130 associativity right } /// Fanout | Given two functions with the same source but different targets, this function /// splits the computation and combines the result of each Arrow into a tuple of the result of /// each side. infix operator &&& { precedence 130 associativity right } /// MARK: Control.Arrow.Choice /// Splat | Splits two computations and combines the results into Eithers on the left and right. infix operator +++ { precedence 120 associativity right } /// Fanin | Given two functions with the same target but different sources, this function splits /// the input between the two and merges the output. infix operator ||| { precedence 120 associativity right } /// MARK: Control.Arrow.Plus /// Op | Combines two ArrowZero monoids. infix operator <+> { precedence 150 associativity right } /// MARK: Control.Comonad.Apply /// Ap | Promotes function application. infix operator >*< { precedence 140 associativity left } /// Sequence Right | Disregards the Functor on the Left. infix operator *< { precedence 140 associativity left } /// Sequence Left | Disregards the Functor on the Right. infix operator >* { precedence 140 associativity left } /// Lift | Lifts a function to an Arrow. prefix operator ^ {} /// Lower | Lowers an arrow to a function. postfix operator ^ {}
mit
dac10b0476ba02c41011e9938c4fbfb5
23.178439
100
0.709717
3.839433
false
false
false
false
Appudo/Appudo.github.io
static/dashs/probe/c/s/3/2.swift
1
1070
import libappudo import libappudo_run import libappudo_env struct RegData : FastCodable { let url : String let mail : String let ticket : String let lID : Int? } func onControl(ev : PageEvent) -> ControlResult { let outBuffer = ManagedCharBuffer.create(128) if let data = RegData.from(json:ev.data as? String ?? ""), let kn = <!libappudo.URL.encode(data.ticket, outBuffer), let ticket = outBuffer.toString(kn), let nn = <!libappudo.URL.encode(data.mail, outBuffer), let mail = outBuffer.toString(nn) { MAIL(mail) TICKET(ticket) URL("\(data.url)probe.html#login/register") Page.skinId = UInt32(data.lID ?? 1) return .OK } return .ABORT } func main() { printSub() } func SUBJECT() -> Void { if var s = readSub() { print(String(format: "%08d", s.utf8.count)) print(s) } } func URL(_ url : String) -> Void { print(url) } func MAIL(_ mail : String) -> Void { print(mail) } func TICKET(_ ticket : String) -> Void { print(ticket) }
apache-2.0
48afcdad80c7b28883c870500d42884d
20.4
63
0.601869
3.222892
false
false
false
false
CodansWJ/WJWheel
demo-wheel/WheelImage/WheelImageView.swift
1
7404
// // WheelImageView.swift // WheelImageView // // Created by 汪俊 on 2016/12/28. // Copyright © 2016年 Codans. All rights reserved. // import UIKit @objc protocol WheelImageViewDelegate { @objc optional func wheelImageViewDidSelected(index:Int) } enum Distance { case right case left } enum TimerStatus { case run case stop } class WheelImageView: UIView { var delegate:WheelImageViewDelegate? private var imageManager = loadImageManager() // 网络图片本地缓存管理对象 var mainScrollerView = UIScrollView() // 总的滑动View var mainLongView = UIView() // 3个imageView下的长View var pageVT = UIPageControl() // 指示点 var View_Width:CGFloat = 0 // 自身宽度 var View_height:CGFloat = 0 // 自身高度 var imageViewArray = [UIImageView]() // 3个用于展示的imageView数组 var imageArray:[UIImage] = [UIImage]() // 用于展示的图片数组 var imageUrlArray = [String]() // 网络图片urlString数组 var imageLoadType:Int = 0 // 图片加载的形式: 0-本地加载 1-网络加载 var imageIndex:Int = 0 // 标记现在所显示的下标 var lastImageIndex:Int! var nextImageIndex:Int! var timer:Timer! // 定时器 var timerFrequency:CGFloat = 3 // 定时时间 /** * 滑动方向:默认右划 */ var scrollDistance:Distance = Distance.right /** * 定时器默认开启 */ var scrollStatus:TimerStatus = TimerStatus.run { didSet { if scrollStatus == .run { creatAutoTimer() }else{ removeTimer() } } } init(frame: CGRect, imageUrlArray:[String], placehold:UIImage?, frequency:CGFloat) { super.init(frame: frame) imageManager.delegate = self self.imageUrlArray = imageUrlArray var placeholdImage = UIImage() if placehold == nil { placeholdImage = #imageLiteral(resourceName: "wheelImagePlaceHold.png") } imageManager.downLoadImages(WithUrlArray: imageUrlArray, placehold: placeholdImage) imageLoadType = 1 timerFrequency = frequency initAction() } init(frame: CGRect, imageArray:[UIImage], frequency:CGFloat) { super.init(frame: frame) self.imageArray = imageArray imageLoadType = 0 timerFrequency = frequency initAction() } func initAction() { View_Width = frame.size.width View_height = frame.size.height mainScrollerView.delegate = self creatView() creatAutoTimer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension WheelImageView:UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.x == View_Width*2 { scrollView.contentOffset.x = View_Width resetImages(isRight: true) }else if scrollView.contentOffset.x == 0 { scrollView.contentOffset.x = View_Width resetImages(isRight: false) }else{ return } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if timer != nil { removeTimer() } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if timer == nil { creatAutoTimer() } } func beTouches() { if self.delegate != nil { self.delegate?.wheelImageViewDidSelected!(index: imageIndex + 1) } } // MARK: - 重新设置图片 func resetImages(isRight:Bool) { imageIndex = isRight ? imageIndex + 1 : imageIndex - 1 if imageIndex <= -1 { imageIndex = imageArray.count - 1 }else if imageIndex >= imageArray.count { imageIndex = 0 } lastImageIndex = imageIndex - 1 < 0 ? imageArray.count - 1 : imageIndex - 1 nextImageIndex = imageIndex + 1 > imageArray.count - 1 ? 0 : imageIndex + 1 imageViewArray[0].image = imageArray[lastImageIndex] imageViewArray[1].image = imageArray[imageIndex] imageViewArray[2].image = imageArray[nextImageIndex] pageVT.currentPage = imageIndex } } extension WheelImageView { // MARK: - 创建页面 func creatView() { mainLongView.frame = CGRect(x: 0, y: 0, width: View_Width*3, height: View_height) mainScrollerView.frame = CGRect(x: 0, y: 0, width: View_Width, height: View_height) mainScrollerView.contentSize = CGSize(width: mainLongView.bounds.size.width, height: 0) mainScrollerView.contentOffset.x = View_Width mainScrollerView.isPagingEnabled = true mainScrollerView.bounces = false mainScrollerView.showsVerticalScrollIndicator = false mainScrollerView.showsHorizontalScrollIndicator = false let tag = UITapGestureRecognizer(target: self, action: #selector(beTouches)) self.isUserInteractionEnabled = true self.addGestureRecognizer(tag) pageVT.frame = CGRect(x: 0, y: View_height - 20, width: View_Width, height: 20) pageVT.numberOfPages = imageArray.count pageVT.pageIndicatorTintColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) pageVT.currentPageIndicatorTintColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1) pageVT.currentPage = imageIndex for i in 0..<3 { let imageView = UIImageView(frame: CGRect(x: CGFloat(i)*View_Width, y: 0, width: View_Width, height: View_height)) imageView.image = imageArray[i] imageViewArray.append(imageView) mainLongView.addSubview(imageView) } mainScrollerView.addSubview(mainLongView) self.addSubview(mainScrollerView) self.addSubview(pageVT) } // MARK: - 创建定时器 func creatAutoTimer() { timer = Timer(timeInterval: TimeInterval(timerFrequency), target: self, selector: #selector(updateTimer(timer:)), userInfo: nil, repeats: true) RunLoop.main.add(timer, forMode: .commonModes) } // MARK: - 移除定时器 func removeTimer() { timer.invalidate() timer = nil } func updateTimer(timer:Timer) { switch scrollDistance { case .left: self.mainScrollerView.setContentOffset(CGPoint(x: 0, y: 0), animated: true) default: self.mainScrollerView.setContentOffset(CGPoint(x: View_Width*2, y: 0), animated: true) } } } extension WheelImageView:managerDelegate { func loadImageManagerReloadImageArray(imageArray: [UIImage]) { self.imageArray = imageArray } }
mit
e0cc846ebaaa12b3de05313665a62f8c
30.372807
151
0.587306
4.623788
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Third Party Code/SWStepSlider/SWStepSlider.swift
1
7807
// // SWStepSlider.swift // Pods // // Created by Sarun Wongpatcharapakorn on 2/4/16. // // import UIKit @IBDesignable open class SWStepSlider: UIControl { @IBInspectable open var minimumValue: Int = 0 @IBInspectable open var maximumValue: Int = 4 @IBInspectable open var value: Int = 2 { didSet { if self.value != oldValue && self.continuous { self.sendActions(for: .valueChanged) } } } @IBInspectable open var continuous: Bool = true // if set, value change events are generated any time the value changes due to dragging. default = YES let trackLayer = CALayer() var trackHeight: CGFloat = 1 var trackColor = UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1) var tickHeight: CGFloat = 8 var tickWidth: CGFloat = 1 var tickColor = UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1) let thumbLayer = CAShapeLayer() var thumbFillColor = UIColor.white var thumbStrokeColor = UIColor(red: 222.0/255.0, green: 222.0/255.0, blue: 222.0/255.0, alpha: 1) var thumbDimension: CGFloat = 28 var stepWidth: CGFloat { return self.trackWidth / CGFloat(self.maximumValue) } var trackWidth: CGFloat { return self.bounds.size.width - self.thumbDimension } var trackOffset: CGFloat { return (self.bounds.size.width - self.trackWidth) / 2 } var numberOfSteps: Int { return self.maximumValue - self.minimumValue + 1 } required public init?(coder: NSCoder) { super.init(coder: coder) self.commonInit() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } fileprivate func commonInit() { self.isAccessibilityElement = true self.accessibilityTraits = UIAccessibilityTraitAdjustable self.trackLayer.backgroundColor = self.trackColor.cgColor self.layer.addSublayer(trackLayer) self.thumbLayer.backgroundColor = UIColor.clear.cgColor self.thumbLayer.fillColor = self.thumbFillColor.cgColor self.thumbLayer.strokeColor = self.thumbStrokeColor.cgColor self.thumbLayer.lineWidth = 0.5 self.thumbLayer.frame = CGRect(x: 0, y: 0, width: self.thumbDimension, height: self.thumbDimension) self.thumbLayer.path = UIBezierPath(ovalIn: self.thumbLayer.bounds).cgPath // Shadow self.thumbLayer.shadowOffset = CGSize(width: 0, height: 2) self.thumbLayer.shadowColor = UIColor.black.cgColor self.thumbLayer.shadowOpacity = 0.3 self.thumbLayer.shadowRadius = 2 self.thumbLayer.contentsScale = UIScreen.main.scale // Tap Gesture Recognizer let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:))) self.addGestureRecognizer(tap) self.layer.addSublayer(self.thumbLayer) } open override func layoutSubviews() { super.layoutSubviews() var rect = self.bounds rect.origin.x = self.trackOffset rect.origin.y = (rect.size.height - self.trackHeight) / 2 rect.size.height = self.trackHeight rect.size.width = self.trackWidth self.trackLayer.frame = rect let center = CGPoint(x: self.trackOffset + CGFloat(self.value) * self.stepWidth, y: self.bounds.midY) let thumbRect = CGRect(x: center.x - self.thumbDimension / 2, y: center.y - self.thumbDimension / 2, width: self.thumbDimension, height: self.thumbDimension) self.thumbLayer.frame = thumbRect } open override func draw(_ rect: CGRect) { super.draw(rect) guard let ctx = UIGraphicsGetCurrentContext() else { return } ctx.saveGState() // Draw ticks ctx.setFillColor(self.tickColor.cgColor) for index in 0..<self.numberOfSteps { let x = self.trackOffset + CGFloat(index) * self.stepWidth - 0.5 * self.tickWidth let y = self.bounds.midY - 0.5 * self.tickHeight // Clip the tick let tickPath = UIBezierPath(rect: CGRect(x: x , y: y, width: self.tickWidth, height: self.tickHeight)) // Fill the tick ctx.addPath(tickPath.cgPath) ctx.fillPath() } ctx.restoreGState() } open override var intrinsicContentSize : CGSize { return CGSize(width: self.thumbDimension * CGFloat(self.numberOfSteps), height: self.thumbDimension) } // MARK: - Touch var previousLocation: CGPoint! var dragging = false var originalValue: Int! open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: self) self.originalValue = self.value if self.thumbLayer.frame.contains(location) { self.dragging = true } else { self.dragging = false } self.previousLocation = location return self.dragging } open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: self) let deltaLocation = location.x - self.previousLocation.x let deltaValue = self.deltaValue(deltaLocation) if deltaLocation < 0 { // minus self.value = self.clipValue(self.originalValue - deltaValue) } else { self.value = self.clipValue(self.originalValue + deltaValue) } CATransaction.begin() CATransaction.setDisableActions(true) // Update UI without animation self.setNeedsLayout() CATransaction.commit() return true } open override func endTracking(_ touch: UITouch?, with event: UIEvent?) { self.previousLocation = nil self.originalValue = nil self.dragging = false if self.continuous == false { self.sendActions(for: .valueChanged) } } // MARK: - Helper func deltaValue(_ deltaLocation: CGFloat) -> Int { return Int(round(fabs(deltaLocation) / self.stepWidth)) } func clipValue(_ value: Int) -> Int { return min(max(value, self.minimumValue), self.maximumValue) } // MARK: - Tap Gesture Recognizer @objc func handleTap(_ sender: UIGestureRecognizer) { if !self.dragging { let pointTapped: CGPoint = sender.location(in: self) let widthOfSlider: CGFloat = self.bounds.size.width let newValue = pointTapped.x * (CGFloat(self.numberOfSteps) / widthOfSlider) self.value = Int(newValue) if self.continuous == false { self.sendActions(for: .valueChanged) } self.setNeedsLayout() } } // MARK: - Accessibility open override func accessibilityIncrement() { guard self.value < self.maximumValue else { return } self.value = self.value + 1 if self.continuous == false { self.sendActions(for: .valueChanged) } self.setNeedsLayout() } open override func accessibilityDecrement() { guard self.value > self.minimumValue else { return } self.value = self.value - 1 if self.continuous == false { self.sendActions(for: .valueChanged) } self.setNeedsLayout() } }
mit
f34da3b2184525335fdc3dc597946f79
31.127572
165
0.596388
4.557501
false
false
false
false
digdoritos/RestfulAPI-Example
RestfulAPI-Example/SearchTableViewController.swift
1
3153
// // SearchTableViewController.swift // RestfulAPI-Example // // Created by Chun-Tang Wang on 26/03/2017. // Copyright © 2017 Chun-Tang Wang. All rights reserved. // import UIKit class SearchTableViewController: 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() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
24169980f9026af1d56aec60bc124194
32.178947
136
0.671954
5.297479
false
false
false
false
wesj/firefox-ios-1
Client/Frontend/Browser/TabManager.swift
2
3357
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit protocol TabManagerDelegate: class { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) func tabManager(tabManager: TabManager, didCreateTab tab: Browser) func tabManager(tabManager: TabManager, didAddTab tab: Browser) func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) } class TabManager { weak var delegate: TabManagerDelegate? = nil private var tabs: [Browser] = [] private var _selectedIndex = -1 var selectedIndex: Int { return _selectedIndex } private let defaultNewTabRequest: NSURLRequest init(defaultNewTabRequest: NSURLRequest) { self.defaultNewTabRequest = defaultNewTabRequest } var count: Int { return tabs.count } var selectedTab: Browser? { if !(0..<count ~= _selectedIndex) { return nil } return tabs[_selectedIndex] } func getTab(index: Int) -> Browser { return tabs[index] } func getTab(webView: WKWebView) -> Browser? { for tab in tabs { if tab.webView === webView { return tab } } return nil } func selectTab(tab: Browser?) { if selectedTab === tab { return } let previous = selectedTab _selectedIndex = -1 for i in 0..<count { if tabs[i] === tab { _selectedIndex = i break } } assert(tab === selectedTab, "Expected tab is selected") delegate?.tabManager(self, didSelectedTabChange: tab, previous: previous) } func addTab(var request: NSURLRequest! = nil, configuration: WKWebViewConfiguration = WKWebViewConfiguration()) -> Browser { if request == nil { request = defaultNewTabRequest } let tab = Browser(configuration: configuration) delegate?.tabManager(self, didCreateTab: tab) tabs.append(tab) delegate?.tabManager(self, didAddTab: tab) tab.loadRequest(request) selectTab(tab) return tab } func removeTab(tab: Browser) { // If the removed tab was selected, find the new tab to select. if tab === selectedTab { let index = getIndex(tab) if index + 1 < count { selectTab(tabs[index + 1]) } else if index - 1 >= 0 { selectTab(tabs[index - 1]) } else { assert(count == 1, "Removing last tab") selectTab(nil) } } let prevCount = count for i in 0..<count { if tabs[i] === tab { tabs.removeAtIndex(i) break } } assert(count == prevCount - 1, "Tab removed") delegate?.tabManager(self, didRemoveTab: tab) } private func getIndex(tab: Browser) -> Int { for i in 0..<count { if tabs[i] === tab { return i } } assertionFailure("Tab not in tabs list") } }
mpl-2.0
e1ade4d0b62046392081e426e7202ff7
26.52459
128
0.563896
4.858177
false
false
false
false
devpunk/punknote
punknote/Support/Extensions/ExtensionString.swift
4
679
import Foundation extension String { func capitalizedFirstLetter() -> String { let count:Int = characters.count if count < 1 { return self } else if count == 1 { return uppercased() } let firstLetter:String = String(self[startIndex]).uppercased() let remainRange:Range = Range(uncheckedBounds:( lower:index(startIndex, offsetBy:1), upper:index(startIndex, offsetBy:count))) let remain:String = self[remainRange].lowercased() let newString:String = "\(firstLetter)\(remain)" return newString } }
mit
92859894b06181599ee7b1d6951987c4
24.148148
70
0.553756
5.183206
false
false
false
false
statusbits/HomeKit-Demo
BetterHomeKit/UsersViewController.swift
1
3973
// // UsersViewController.swift // BetterHomeKit // // Created by Khaos Tian on 8/6/14. // Copyright (c) 2014 Oltica. All rights reserved. // import UIKit import HomeKit class UsersViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var usersTableView: UITableView! lazy var usersArray = [HMUser]() override func viewDidLoad() { super.viewDidLoad() fetchUsers() // Do any additional setup after loading the view. } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.usersTableView.setEditing(false, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func fetchUsers() { usersArray.removeAll(keepCapacity: false) if let currentHome = Core.sharedInstance.currentHome { for user in currentHome.users as [HMUser]{ usersArray.append(user) } } usersTableView.reloadData() } @IBAction func addUser(sender: AnyObject) { /*let alert = UIAlertController(title: "New User", message: "Enter the iCloud address of user you want to add. (The users list will get updated once user accept the invitation.)", preferredStyle: UIAlertControllerStyle.Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: { [weak self] (action:UIAlertAction!) in let textField = alert.textFields?[0] as UITextField Core.sharedInstance.currentHome?.addUserWithCompletionHandler { user, error in if error != nil { NSLog("Add user failed: \(error)") } else { self?.fetchUsers() } } }))*/ Core.sharedInstance.currentHome?.addUserWithCompletionHandler { user, error in if error != nil { NSLog("Add user failed: \(error)") } else { self.fetchUsers() } } /*dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) })*/ } @IBAction func dismissVC(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return usersArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userCell", forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = usersArray[indexPath.row].name cell.detailTextLabel?.text = "User" return cell } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let userID = usersArray[indexPath.row] Core.sharedInstance.currentHome?.removeUser(userID) { [weak self] error in if error != nil { NSLog("Failed removing user, error:\(error)") } else { self?.fetchUsers() } } } } }
mit
0cb804531986ab4a17be97d5fa1b9119
34.473214
233
0.602567
5.495159
false
false
false
false
PatrickChow/Swift-Awsome
News/Modules/Profile/Setting/ViewController/SettingsViewController.swift
1
4936
// // Created by Patrick Chow on 2017/5/26. // Copyright (c) 2017 Jiemian Technology. All rights reserved. import UIKit import RxSwift class SettingsViewController: ViewController, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! private var features: [SettingsOption] = [.version, .cache, .about, .contact, .notification, .cellularData, .QRCode] override func viewDidLoad() { super.viewDidLoad() title = "设置" view.nv.backgroundColor(UIColor(hexNumber: 0xf6f6f6), night: UIColor(hexNumber: 0x3f3f3f)) tableView = UITableView(frame: view.bounds, style: .plain) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.backgroundColor = .clear tableView.delegate = self tableView.dataSource = self tableView.decelerationRate = 0.1 tableView.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) tableView.layoutMargins = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) tableView.register(SettingsCell.self, forCellReuseIdentifier: "cell") tableView.register(SettingsIconCell.self, forCellReuseIdentifier: "icon.cell") tableView.register(SettingsSwitchCell.self, forCellReuseIdentifier: "switch.cell") if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } view.addSubview(tableView) let footerView = SettingsFooterView(frame: CGRect(origin: .zero, size: CGSize(width: view.bounds.width, height: 200))) tableView.tableFooterView = footerView footerView.tap.subscribe(onNext: { // TODO: print($0) }) .disposed(by: disposeBag) // TODO: 判断登录 features.insert(.signOut, at: 6) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } } // MARK: Private Method fileprivate func pushViewController(with feature: SettingsOption) { var vc: UIViewController? switch feature { case .about: vc = Mediator.viewController(for: .url(.provider(title: "关于界面",token: .about))) case .contact: vc = Mediator.viewController(for: .url(.provider(title: "联系我们", token: .contact))) case .QRCode: vc = Mediator.viewController(for: .profile(.scan)) default:break } if let vc = vc { pushViewController(vc) } } // MARK: UITableViewDataSource UITableViewDelegate public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return features.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var identifier: String switch indexPath.row { case 2..<4: identifier = "icon.cell" case 4..<6: identifier = "switch.cell" default: identifier = "cell" } let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! SettingsCell cell.setViewModel(features[indexPath.row]) if let switchCell = cell as? SettingsSwitchCell { let isOn = switchCell.isOn.takeUntil(switchCell.preparingForReuse) isOn.subscribe(onNext: { [weak self] _ in print("切换") }) .disposed(by: disposeBag) } return cell } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return UIView() } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { pushViewController(with: features[indexPath.row]) } } extension SettingsViewController: TargetActionRouter { func performAction(_ sender: UIResponder?, from: Any?, with message: TAIdentifier?, object: [AnyHashable: Any]?) { if let isOn = object?[kTableCellSwitchValueKey] as? Bool, let cell = from as? UITableViewCell, let index = tableView.indexPath(for: cell)?.row { switch index { case 4: handelNotification(isOn: isOn) case 5: handelUseCellularDataToPlay(isOn: isOn) default:break } } } /// 处理新闻推送的开关 func handelNotification(isOn: Bool) { } /// 处理流量播放的开关 func handelUseCellularDataToPlay(isOn: Bool) { } }
mit
94f4f990f5fd266c648994f10d692bbf
34.275362
126
0.624076
4.85344
false
false
false
false
Swinject/SwinjectStoryboard
Sources/ViewController+Swinject.swift
1
2921
// // ViewController+Swinject.swift // Swinject // // Created by Yoichi Tagaya on 7/31/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import ObjectiveC #if canImport(UIKit) import UIKit private var uivcRegistrationNameKey: String = "UIViewController.swinjectRegistrationName" private var uivcWasInjectedKey: String = "UIViewController.wasInjected" extension UIViewController: RegistrationNameAssociatable, InjectionVerifiable { public var swinjectRegistrationName: String? { get { return getAssociatedString(key: &uivcRegistrationNameKey) } set { setAssociatedString(newValue, key: &uivcRegistrationNameKey) } } public var wasInjected: Bool { get { return getAssociatedBool(key: &uivcWasInjectedKey) ?? false } set { setAssociatedBool(newValue, key: &uivcWasInjectedKey) } } } #elseif canImport(Cocoa) import Cocoa private var nsvcRegistrationNameKey: String = "NSViewController.swinjectRegistrationName" private var nswcRegistrationNameKey: String = "NSWindowController.swinjectRegistrationName" private var nsvcWasInjectedKey: String = "NSViewController.wasInjected" private var nswcWasInjectedKey: String = "NSWindowController.wasInjected" extension NSViewController: RegistrationNameAssociatable, InjectionVerifiable { internal var swinjectRegistrationName: String? { get { return getAssociatedString(key: &nsvcRegistrationNameKey) } set { setAssociatedString(newValue, key: &nsvcRegistrationNameKey) } } internal var wasInjected: Bool { get { return getAssociatedBool(key: &nsvcWasInjectedKey) ?? false } set { setAssociatedBool(newValue, key: &nsvcWasInjectedKey) } } } extension NSWindowController: RegistrationNameAssociatable, InjectionVerifiable { internal var swinjectRegistrationName: String? { get { return getAssociatedString(key: &nsvcRegistrationNameKey) } set { setAssociatedString(newValue, key: &nsvcRegistrationNameKey) } } internal var wasInjected: Bool { get { return getAssociatedBool(key: &nswcWasInjectedKey) ?? false } set { setAssociatedBool(newValue, key: &nswcWasInjectedKey) } } } #endif extension NSObject { fileprivate func getAssociatedString(key: UnsafeRawPointer) -> String? { return objc_getAssociatedObject(self, key) as? String } fileprivate func setAssociatedString(_ string: String?, key: UnsafeRawPointer) { objc_setAssociatedObject(self, key, string, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } fileprivate func getAssociatedBool(key: UnsafeRawPointer) -> Bool? { return (objc_getAssociatedObject(self, key) as? NSNumber)?.boolValue } fileprivate func setAssociatedBool(_ bool: Bool, key: UnsafeRawPointer) { objc_setAssociatedObject(self, key, NSNumber(value: bool), objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } }
mit
5755e74f3863e74ab470d2bb54dbcfc0
35.962025
112
0.746918
4.238026
false
false
false
false
Eonil/Editor
Editor4/State.swift
1
3512
// // State.swift // Editor4 // // Created by Hoon H. on 2016/04/19. // Copyright © 2016 Eonil. All rights reserved. // /// Root container of all user-interaction state. /// /// This does not contain much things. Each workspaces contain most /// data. /// /// Each workspaces has thier own databases. /// Workspace contains `window` which represents whole navigation stack. /// /// - Note: /// If copying cost becomes too big, consider using of COW objects. /// struct State { private(set) var version = Version() /// Currently selected workspace. /// /// Window ordering and main-window state are managed /// by AppKit and we don't care. Then why do we need /// to track current main-window? To send main-menu /// command to correct window. var currentWorkspaceID: WorkspaceID? = nil { didSet { version.revise() } } // var mainMenu = MainMenuState() private(set) var workspaces = KeyJournalingDictionary<WorkspaceID, WorkspaceState>() { didSet { version.revise() } } var cargo = CargoServiceState() { didSet { version.revise() } } /// Will be dispatched from `DebugService`. private(set) var debug = DebugState() { didSet { version.revise() } } mutating func revise() { version.revise() } } extension State { /// Accesses current workspace state. /// Settings back to this property will update `WorkspaceState` for `currentWorkspaceID`. var currentWorkspace: WorkspaceState? { get { guard let workspaceID = currentWorkspaceID else { return nil } return workspaces[workspaceID] } set { guard let workspaceID = currentWorkspaceID else { reportErrorToDevelopers("Assigning back to this property is not a critical error, but this is not likely to be a proper mutation.") return } workspaces[workspaceID] = newValue } } } extension State { mutating func process<T>(workspaceID: WorkspaceID, @noescape _ transaction: (inout WorkspaceState) throws -> T) throws -> T { guard let workspaceState = workspaces[workspaceID] else { throw StateError.missingWorkspaceStateFor(workspaceID) } var workspaceState1 = workspaceState let result = try transaction(&workspaceState1) workspaces[workspaceID] = workspaceState1 return result } mutating func addWorkspace() -> WorkspaceID { let workspaceID = WorkspaceID() workspaces[workspaceID] = WorkspaceState() return workspaceID } mutating func removeWorkspace(workspaceID: WorkspaceID) throws { if currentWorkspaceID == workspaceID { currentWorkspaceID = nil } guard workspaces[workspaceID] != nil else { throw StateError.missingWorkspaceStateFor(workspaceID) } precondition(workspaces.removeValueForKey(workspaceID) != nil) } mutating func reloadWorkspace(workspaceID: WorkspaceID, workspaceState: WorkspaceState) throws { guard workspaces[workspaceID] != nil else { throw StateError.missingWorkspaceStateFor(workspaceID) } workspaces[workspaceID] = workspaceState } mutating func reviseDebugState(newDebugState: DebugState) { debug = newDebugState } } extension State { mutating func clearJournals() { workspaces.clearJournal() } } //struct ToolsetState { // var cargo = CargoServiceState() //}
mit
7044a5a44d84234304ceba71d871d5d4
27.778689
147
0.656793
4.577575
false
false
false
false
DanielAsher/TLSphinx
TLSphinx/Config.swift
3
1450
// // Config.swift // TLSphinx // // Created by Bruno Berisso on 5/29/15. // Copyright (c) 2015 Bruno Berisso. All rights reserved. // import Foundation import Sphinx.Base public class Config { var cmdLnConf: COpaquePointer private var cArgs: [UnsafeMutablePointer<Int8>] public init?(args: (String,String)...) { // Create [UnsafeMutablePointer<Int8>]. cArgs = args.flatMap { (name, value) -> [UnsafeMutablePointer<Int8>] in //strdup move the strings to the heap and return a UnsageMutablePointer<Int8> return [strdup(name),strdup(value)] } cmdLnConf = cmd_ln_parse_r(nil, ps_args(), CInt(cArgs.count), &cArgs, STrue) if cmdLnConf == nil { return nil } } deinit { for cString in cArgs { free(cString) } cmd_ln_free_r(cmdLnConf) } public var showDebugInfo: Bool { get { if cmdLnConf != nil { return cmd_ln_str_r(cmdLnConf, "-logfn") == nil } else { return false } } set { if cmdLnConf != nil { if newValue { cmd_ln_set_str_r(cmdLnConf, "-logfn", nil) } else { cmd_ln_set_str_r(cmdLnConf, "-logfn", "/dev/null") } } } } }
mit
81a09f84aa9de34d50e114bdb7e613e0
23.59322
89
0.491724
3.940217
false
false
false
false
shohei/firefox-ios
Storage/RemoteTabs.swift
5
2796
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared public struct ClientAndTabs: Equatable, Printable { public let client: RemoteClient public let tabs: [RemoteTab] public var description: String { return "<Client \(client.guid), \(tabs.count) tabs.>" } // See notes in RemoteTabsPanel.swift. public func approximateLastSyncTime() -> Timestamp { if tabs.isEmpty { return client.modified } return tabs.reduce(Timestamp(0), combine: { m, tab in return max(m, tab.lastUsed) }) } } public func ==(lhs: ClientAndTabs, rhs: ClientAndTabs) -> Bool { return (lhs.client == rhs.client) && (lhs.tabs == rhs.tabs) } public protocol RemoteClientsAndTabs { func wipeClients() -> Deferred<Result<()>> func wipeTabs() -> Deferred<Result<()>> func getClients() -> Deferred<Result<[RemoteClient]>> func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> func insertOrUpdateClient(client: RemoteClient) -> Deferred<Result<()>> func insertOrUpdateClients(clients: [RemoteClient]) -> Deferred<Result<()>> // Returns number of tabs inserted. func insertOrUpdateTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> // Insert into the local client. func insertOrUpdateTabsForClientGUID(clientGUID: String?, tabs: [RemoteTab]) -> Deferred<Result<Int>> func onRemovedAccount() -> Success } public struct RemoteTab: Equatable { public let clientGUID: String? public let URL: NSURL public let title: String public let history: [NSURL] public let lastUsed: Timestamp public let icon: NSURL? public init(clientGUID: String?, URL: NSURL, title: String, history: [NSURL], lastUsed: Timestamp, icon: NSURL?) { self.clientGUID = clientGUID self.URL = URL self.title = title self.history = history self.lastUsed = lastUsed self.icon = icon } public func withClientGUID(clientGUID: String?) -> RemoteTab { return RemoteTab(clientGUID: clientGUID, URL: URL, title: title, history: history, lastUsed: lastUsed, icon: icon) } } public func ==(lhs: RemoteTab, rhs: RemoteTab) -> Bool { return lhs.clientGUID == rhs.clientGUID && lhs.URL == rhs.URL && lhs.title == rhs.title && lhs.history == rhs.history && lhs.lastUsed == rhs.lastUsed && lhs.icon == rhs.icon } extension RemoteTab: Printable { public var description: String { return "<RemoteTab clientGUID: \(clientGUID), URL: \(URL), title: \(title), lastUsed: \(lastUsed)>" } }
mpl-2.0
05ad2cfe4a7b8439b11bf3b6c9f9f040
32.698795
122
0.653433
4.410095
false
false
false
false
GhostSK/SpriteKitPractice
FightDemo2/FightDemo2/UnitNode.swift
1
717
// // UnitNode.swift // FightDemo2 // // Created by 胡杨林 on 2017/12/27. // Copyright © 2017年 胡杨林. All rights reserved. // import Foundation import SpriteKit class baseUnitNode: SKSpriteNode { public var MaxHealth:Int = 100 public var Picture:SKTexture? = nil private var mainTexture: SKTexture? = nil private var backHPbarNode:SKShapeNode? = nil private var HPBarNode:SKShapeNode? = nil init(Maxhealth:Int, Size:CGSize) { super.init(texture: nil, color: SKColor.clear, size:Size) self.MaxHealth = Maxhealth } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
3e41d45f2f2fde0b242e82c62ec15911
21.645161
65
0.652422
3.794595
false
false
false
false
Raizlabs/ios-template
{{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Application/Debug/DebugMenu.swift
1
1406
// // DebugMenu.swift // {{ cookiecutter.project_name | replace(' ', '') }} // // Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}. // Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved. // import Swiftilities import Services import Crashlytics class DebugMenu { static func enableDebugGesture(_ viewController: UIViewController) { let debugGesture = UITapGestureRecognizer(target: self, action: #selector(openDebugAlert)) debugGesture.numberOfTapsRequired = 3 debugGesture.numberOfTouchesRequired = 2 viewController.view.addGestureRecognizer(debugGesture) } @objc static func openDebugAlert() { guard let delegate = UIApplication.shared.delegate as? AppDelegate, let rootViewController = delegate.window?.rootViewController else { Log.warn("Debug alert unable to present since the window rootViewController is nil") return } var topMostViewController: UIViewController? = rootViewController while topMostViewController?.presentedViewController != nil { topMostViewController = topMostViewController?.presentedViewController! } let debug = UINavigationController(rootViewController: DebugMenuViewController()) topMostViewController?.present(debug, animated: true, completion: nil) } }
mit
bcb12f33e2cadfb13e714259c664ab8c
38.027778
100
0.691815
5.488281
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Services/SharingService.swift
2
31298
import Foundation import CocoaLumberjack import WordPressShared import WordPressKit /// SharingService is responsible for wrangling publicize services, publicize /// connections, and keyring connections. /// open class SharingService: LocalCoreDataService { @objc let SharingAPIErrorNotFound = "not_found" // MARK: - Publicize Related Methods /// Syncs the list of Publicize services. The list is expected to very rarely change. /// /// - Parameters: /// - blog: The `Blog` for which to sync publicize services /// - success: An optional success block accepting no parameters /// - failure: An optional failure block accepting an `NSError` parameter /// @objc open func syncPublicizeServicesForBlog(_ blog: Blog, success: (() -> Void)?, failure: ((NSError?) -> Void)?) { guard let remote = remoteForBlog(blog) else { return } remote.getPublicizeServices({ remoteServices in // Process the results self.mergePublicizeServices(remoteServices, success: success) }, failure: failure) } /// Fetches the current user's list of keyring connections. Nothing is saved to core data. /// The success block should accept an array of `KeyringConnection` objects. /// /// - Parameters: /// - blog: The `Blog` for which to sync keyring connections /// - success: An optional success block accepting an array of `KeyringConnection` objects /// - failure: An optional failure block accepting an `NSError` parameter /// @objc open func fetchKeyringConnectionsForBlog(_ blog: Blog, success: (([KeyringConnection]) -> Void)?, failure: ((NSError?) -> Void)?) { guard let remote = remoteForBlog(blog) else { return } remote.getKeyringConnections({ keyringConnections in // Just return the result success?(keyringConnections) }, failure: failure) } /// Syncs Publicize connections for the specified wpcom blog. /// /// - Parameters: /// - blog: The `Blog` for which to sync publicize connections /// - success: An optional success block accepting no parameters. /// - failure: An optional failure block accepting an `NSError` parameter. /// @objc open func syncPublicizeConnectionsForBlog(_ blog: Blog, success: (() -> Void)?, failure: ((NSError?) -> Void)?) { let blogObjectID = blog.objectID guard let remote = remoteForBlog(blog) else { failure?(SharingServiceError.siteWithNoRemote as NSError) return } remote.getPublicizeConnections(blog.dotComID!, success: { remoteConnections in // Process the results self.mergePublicizeConnectionsForBlog(blogObjectID, remoteConnections: remoteConnections, onComplete: success) }, failure: failure) } /// Creates a new publicize connection for the specified `Blog`, using the specified /// keyring. Optionally the connection can target a particular external user account. /// /// - Parameters /// - blog: The `Blog` for which to sync publicize connections /// - keyring: The `KeyringConnection` to use /// - externalUserID: An optional string representing a user ID on the external service. /// - success: An optional success block accepting a `PublicizeConnection` parameter. /// - failure: An optional failure block accepting an NSError parameter. /// @objc open func createPublicizeConnectionForBlog(_ blog: Blog, keyring: KeyringConnection, externalUserID: String?, success: ((PublicizeConnection) -> Void)?, failure: ((NSError?) -> Void)?) { let blogObjectID = blog.objectID guard let remote = remoteForBlog(blog) else { return } let dotComID = blog.dotComID! remote.createPublicizeConnection(dotComID, keyringConnectionID: keyring.keyringID, externalUserID: externalUserID, success: { remoteConnection in let properties = [ "service": keyring.service ] WPAppAnalytics.track(.sharingPublicizeConnected, withProperties: properties, withBlogID: dotComID) do { let pubConn = try self.createOrReplacePublicizeConnectionForBlogWithObjectID(blogObjectID, remoteConnection: remoteConnection) ContextManager.sharedInstance().save(self.managedObjectContext, withCompletionBlock: { success?(pubConn) }) } catch let error as NSError { DDLogError("Error creating publicize connection from remote: \(error)") failure?(error) } }, failure: { (error: NSError?) in failure?(error) }) } /// Update the specified `PublicizeConnection`. The update to core data is performed /// optimistically. In case of failure the original value will be restored. /// /// - Parameters: /// - shared: True if the connection should be shared with all users of the blog. /// - pubConn: The `PublicizeConnection` to update /// - success: An optional success block accepting no parameters. /// - failure: An optional failure block accepting an NSError parameter. /// @objc open func updateSharedForBlog(_ blog: Blog, shared: Bool, forPublicizeConnection pubConn: PublicizeConnection, success: (() -> Void)?, failure: ((NSError?) -> Void)?) { if pubConn.shared == shared { success?() return } let oldValue = pubConn.shared pubConn.shared = shared ContextManager.sharedInstance().save(managedObjectContext) let blogObjectID = blog.objectID let siteID = pubConn.siteID guard let remote = remoteForBlog(blog) else { return } remote.updatePublicizeConnectionWithID(pubConn.connectionID, shared: shared, forSite: siteID, success: { remoteConnection in let properties = [ "service": pubConn.service, "is_site_wide": NSNumber(value: shared).stringValue ] WPAppAnalytics.track(.sharingPublicizeConnectionAvailableToAllChanged, withProperties: properties, withBlogID: siteID) do { _ = try self.createOrReplacePublicizeConnectionForBlogWithObjectID(blogObjectID, remoteConnection: remoteConnection) ContextManager.sharedInstance().save(self.managedObjectContext, withCompletionBlock: { success?() }) } catch let error as NSError { DDLogError("Error creating publicize connection from remote: \(error)") failure?(error) } }, failure: { (error: NSError?) in pubConn.shared = oldValue ContextManager.sharedInstance().save(self.managedObjectContext, withCompletionBlock: { failure?(error) }) }) } /// Update the specified `PublicizeConnection`. The update to core data is performed /// optimistically. In case of failure the original value will be restored. /// /// - Parameters: /// - externalID: True if the connection should be shared with all users of the blog. /// - pubConn: The `PublicizeConnection` to update /// - success: An optional success block accepting no parameters. /// - failure: An optional failure block accepting an NSError parameter. /// @objc open func updateExternalID(_ externalID: String, forBlog blog: Blog, forPublicizeConnection pubConn: PublicizeConnection, success: (() -> Void)?, failure: ((NSError?) -> Void)?) { if pubConn.externalID == externalID { success?() return } let blogObjectID = blog.objectID let siteID = pubConn.siteID guard let remote = remoteForBlog(blog) else { return } remote.updatePublicizeConnectionWithID(pubConn.connectionID, externalID: externalID, forSite: siteID, success: { remoteConnection in do { _ = try self.createOrReplacePublicizeConnectionForBlogWithObjectID(blogObjectID, remoteConnection: remoteConnection) ContextManager.sharedInstance().save(self.managedObjectContext, withCompletionBlock: { success?() }) } catch let error as NSError { DDLogError("Error creating publicize connection from remote: \(error)") failure?(error) } }, failure: failure) } /// Deletes the specified `PublicizeConnection`. The delete from core data is performed /// optimistically. The caller's `failure` block should be responsible for resyncing /// the deleted connection. /// /// - Parameters: /// - pubConn: The `PublicizeConnection` to delete /// - success: An optional success block accepting no parameters. /// - failure: An optional failure block accepting an NSError parameter. /// @objc open func deletePublicizeConnectionForBlog(_ blog: Blog, pubConn: PublicizeConnection, success: (() -> Void)?, failure: ((NSError?) -> Void)?) { // optimistically delete the connection locally. let siteID = pubConn.siteID managedObjectContext.delete(pubConn) ContextManager.sharedInstance().save(managedObjectContext) guard let remote = remoteForBlog(blog) else { return } remote.deletePublicizeConnection(siteID, connectionID: pubConn.connectionID, success: { let properties = [ "service": pubConn.service ] WPAppAnalytics.track(.sharingPublicizeDisconnected, withProperties: properties, withBlogID: siteID) success?() }, failure: { (error: NSError?) in if let errorCode = error?.userInfo[WordPressComRestApi.ErrorKeyErrorCode] as? String { if errorCode == self.SharingAPIErrorNotFound { // This is a special situation. If the call to disconnect the service returns not_found then the service // has probably already been disconnected and the call was made with stale data. // Assume this is the case and treat this error as a successful disconnect. success?() return } } failure?(error) }) } // MARK: - Public PublicizeService Methods /// Finds a cached `PublicizeService` matching the specified service name. /// /// - Parameter name: The name of the service. This is the `serviceID` attribute for a `PublicizeService` object. /// /// - Returns: The requested `PublicizeService` or nil. /// @objc open func findPublicizeServiceNamed(_ name: String) -> PublicizeService? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: PublicizeService.classNameWithoutNamespaces()) request.predicate = NSPredicate(format: "serviceID = %@", name) var services: [PublicizeService] do { services = try managedObjectContext.fetch(request) as! [PublicizeService] } catch let error as NSError { DDLogError("Error fetching Publicize Service named \(name) : \(error.localizedDescription)") services = [] } return services.first } /// Returns an array of all cached `PublicizeService` objects. /// /// - Returns: An array of `PublicizeService`. The array is empty if no objects are cached. /// @objc open func allPublicizeServices() -> [PublicizeService] { let request = NSFetchRequest<NSFetchRequestResult>(entityName: PublicizeService.classNameWithoutNamespaces()) let sortDescriptor = NSSortDescriptor(key: "order", ascending: true) request.sortDescriptors = [sortDescriptor] var services: [PublicizeService] do { services = try managedObjectContext.fetch(request) as! [PublicizeService] } catch let error as NSError { DDLogError("Error fetching Publicize Services: \(error.localizedDescription)") services = [] } return services } // MARK: - Private PublicizeService Methods /// Called when syncing Publicize services. Merges synced and cached data, removing /// anything that does not exist on the server. Saves the context. /// /// - Parameters /// - remoteServices: An array of `RemotePublicizeService` objects to merge. /// - success: An optional callback block to be performed when core data has saved the changes. /// fileprivate func mergePublicizeServices(_ remoteServices: [RemotePublicizeService], success: (() -> Void)? ) { managedObjectContext.perform { let currentPublicizeServices = self.allPublicizeServices() // Create or update based on the contents synced. let servicesToKeep = remoteServices.map { (remoteService) -> PublicizeService in let pubService = self.createOrReplaceFromRemotePublicizeService(remoteService) return pubService } // Delete any cached PublicizeServices that were not synced. for pubService in currentPublicizeServices { if !servicesToKeep.contains(pubService) { self.managedObjectContext.delete(pubService) } } // Save all the things. ContextManager.sharedInstance().save(self.managedObjectContext, withCompletionBlock: { success?() }) } } /// Composes a new `PublicizeService`, or updates an existing one, with data represented by the passed `RemotePublicizeService`. /// /// - Parameter remoteService: The remote publicize service representing a `PublicizeService` /// /// - Returns: A `PublicizeService`. /// fileprivate func createOrReplaceFromRemotePublicizeService(_ remoteService: RemotePublicizeService) -> PublicizeService { var pubService = findPublicizeServiceNamed(remoteService.serviceID) if pubService == nil { pubService = NSEntityDescription.insertNewObject(forEntityName: PublicizeService.classNameWithoutNamespaces(), into: managedObjectContext) as? PublicizeService } pubService?.connectURL = remoteService.connectURL pubService?.detail = remoteService.detail pubService?.externalUsersOnly = remoteService.externalUsersOnly pubService?.icon = remoteService.icon pubService?.jetpackModuleRequired = remoteService.jetpackModuleRequired pubService?.jetpackSupport = remoteService.jetpackSupport pubService?.label = remoteService.label pubService?.multipleExternalUserIDSupport = remoteService.multipleExternalUserIDSupport pubService?.order = remoteService.order pubService?.serviceID = remoteService.serviceID pubService?.type = remoteService.type return pubService! } // MARK: - Public PublicizeConnection Methods /// Finds a cached `PublicizeConnection` by its `connectionID` /// /// - Parameter connectionID: The ID of the `PublicizeConnection`. /// /// - Returns: The requested `PublicizeConnection` or nil. /// @objc open func findPublicizeConnectionByID(_ connectionID: NSNumber) -> PublicizeConnection? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: PublicizeConnection.classNameWithoutNamespaces()) request.predicate = NSPredicate(format: "connectionID = %@", connectionID) var services: [PublicizeConnection] do { services = try managedObjectContext.fetch(request) as! [PublicizeConnection] } catch let error as NSError { DDLogError("Error fetching Publicize Service with ID \(connectionID) : \(error.localizedDescription)") services = [] } return services.first } /// Returns an array of all cached `PublicizeConnection` objects. /// /// - Parameters /// - blog: A `Blog` object /// /// - Returns: An array of `PublicizeConnection`. The array is empty if no objects are cached. /// @objc open func allPublicizeConnectionsForBlog(_ blog: Blog) -> [PublicizeConnection] { let request = NSFetchRequest<NSFetchRequestResult>(entityName: PublicizeConnection.classNameWithoutNamespaces()) request.predicate = NSPredicate(format: "blog = %@", blog) var connections: [PublicizeConnection] do { connections = try managedObjectContext.fetch(request) as! [PublicizeConnection] } catch let error as NSError { DDLogError("Error fetching Publicize Connections: \(error.localizedDescription)") connections = [] } return connections } // MARK: - Private PublicizeConnection Methods /// Called when syncing Publicize connections. Merges synced and cached data, removing /// anything that does not exist on the server. Saves the context. /// /// - Parameters: /// - blogObjectID: the NSManagedObjectID of a `Blog` /// - remoteConnections: An array of `RemotePublicizeConnection` objects to merge. /// - onComplete: An optional callback block to be performed when core data has saved the changes. /// fileprivate func mergePublicizeConnectionsForBlog(_ blogObjectID: NSManagedObjectID, remoteConnections: [RemotePublicizeConnection], onComplete: (() -> Void)?) { managedObjectContext.perform { var blog: Blog do { blog = try self.managedObjectContext.existingObject(with: blogObjectID) as! Blog } catch let error as NSError { DDLogError("Error fetching Blog: \(error)") // Because of the error we'll bail early, but we still need to call // the success callback if one was passed. onComplete?() return } let currentPublicizeConnections = self.allPublicizeConnectionsForBlog(blog) // Create or update based on the contents synced. let connectionsToKeep = remoteConnections.map { (remoteConnection) -> PublicizeConnection in let pubConnection = self.createOrReplaceFromRemotePublicizeConnection(remoteConnection) pubConnection.blog = blog return pubConnection } // Delete any cached PublicizeServices that were not synced. for pubConnection in currentPublicizeConnections { if !connectionsToKeep.contains(pubConnection) { self.managedObjectContext.delete(pubConnection) } } // Save all the things. ContextManager.sharedInstance().save(self.managedObjectContext, withCompletionBlock: { onComplete?() }) } } /// Composes a new `PublicizeConnection`, or updates an existing one, with /// data represented by the passed `RemotePublicizeConnection`. /// /// - Parameter remoteConnection: The remote connection representing the publicize connection. /// /// - Returns: A `PublicizeConnection`. /// fileprivate func createOrReplaceFromRemotePublicizeConnection(_ remoteConnection: RemotePublicizeConnection) -> PublicizeConnection { var pubConnection = findPublicizeConnectionByID(remoteConnection.connectionID) if pubConnection == nil { pubConnection = NSEntityDescription.insertNewObject(forEntityName: PublicizeConnection.classNameWithoutNamespaces(), into: managedObjectContext) as? PublicizeConnection } pubConnection?.connectionID = remoteConnection.connectionID pubConnection?.dateExpires = remoteConnection.dateExpires pubConnection?.dateIssued = remoteConnection.dateIssued pubConnection?.externalDisplay = remoteConnection.externalDisplay pubConnection?.externalFollowerCount = remoteConnection.externalFollowerCount pubConnection?.externalID = remoteConnection.externalID pubConnection?.externalName = remoteConnection.externalName pubConnection?.externalProfilePicture = remoteConnection.externalProfilePicture pubConnection?.externalProfileURL = remoteConnection.externalProfileURL pubConnection?.keyringConnectionID = remoteConnection.keyringConnectionID pubConnection?.keyringConnectionUserID = remoteConnection.keyringConnectionUserID pubConnection?.label = remoteConnection.label pubConnection?.refreshURL = remoteConnection.refreshURL pubConnection?.service = remoteConnection.service pubConnection?.shared = remoteConnection.shared pubConnection?.status = remoteConnection.status pubConnection?.siteID = remoteConnection.siteID pubConnection?.userID = remoteConnection.userID return pubConnection! } /// Composes a new `PublicizeConnection`, with data represented by the passed `RemotePublicizeConnection`. /// Throws an error if unable to find a `Blog` for the `blogObjectID` /// /// - Parameter blogObjectID: And `NSManagedObjectID` for for a `Blog` entity. /// /// - Returns: A `PublicizeConnection`. /// fileprivate func createOrReplacePublicizeConnectionForBlogWithObjectID(_ blogObjectID: NSManagedObjectID, remoteConnection: RemotePublicizeConnection) throws -> PublicizeConnection { let blog = try managedObjectContext.existingObject(with: blogObjectID) as! Blog let pubConn = createOrReplaceFromRemotePublicizeConnection(remoteConnection) pubConn.blog = blog return pubConn } // MARK: Sharing Button Related Methods /// Syncs `SharingButton`s for the specified wpcom blog. /// /// - Parameters: /// - blog: The `Blog` for which to sync sharing buttons /// - success: An optional success block accepting no parameters. /// - failure: An optional failure block accepting an `NSError` parameter. /// @objc open func syncSharingButtonsForBlog(_ blog: Blog, success: (() -> Void)?, failure: ((NSError?) -> Void)?) { let blogObjectID = blog.objectID guard let remote = remoteForBlog(blog) else { return } remote.getSharingButtonsForSite(blog.dotComID!, success: { (remoteButtons: [RemoteSharingButton]) in self.mergeSharingButtonsForBlog(blogObjectID, remoteSharingButtons: remoteButtons, onComplete: success) }, failure: failure) } /// Pushes changes to the specified blog's `SharingButton`s back up to the blog. /// /// - Parameters: /// - blog: The `Blog` for which to update sharing buttons /// - sharingButtons: An array of `SharingButton` entities with changes either to order, or properties to sync back to the blog. /// - success: An optional success block accepting no parameters. /// - failure: An optional failure block accepting an `NSError` parameter. /// @objc open func updateSharingButtonsForBlog(_ blog: Blog, sharingButtons: [SharingButton], success: (() -> Void)?, failure: ((NSError?) -> Void)?) { let blogObjectID = blog.objectID guard let remote = remoteForBlog(blog) else { return } remote.updateSharingButtonsForSite(blog.dotComID!, sharingButtons: remoteShareButtonsFromShareButtons(sharingButtons), success: { (remoteButtons: [RemoteSharingButton]) in self.mergeSharingButtonsForBlog(blogObjectID, remoteSharingButtons: remoteButtons, onComplete: success) }, failure: failure) } /// Called when syncing sharng buttons. Merges synced and cached data, removing /// anything that does not exist on the server. Saves the context. /// /// - Parameters: /// - blogObjectID: the NSManagedObjectID of a `Blog` /// - remoteSharingButtons: An array of `RemoteSharingButton` objects to merge. /// - onComplete: An optional callback block to be performed when core data has saved the changes. /// fileprivate func mergeSharingButtonsForBlog(_ blogObjectID: NSManagedObjectID, remoteSharingButtons: [RemoteSharingButton], onComplete: (() -> Void)?) { managedObjectContext.perform { var blog: Blog do { blog = try self.managedObjectContext.existingObject(with: blogObjectID) as! Blog } catch let error as NSError { DDLogError("Error fetching Blog: \(error)") // Because of the error we'll bail early, but we still need to call // the success callback if one was passed. onComplete?() return } let currentSharingbuttons = self.allSharingButtonsForBlog(blog) // Create or update based on the contents synced. let buttonsToKeep = remoteSharingButtons.map { (remoteButton) -> SharingButton in return self.createOrReplaceFromRemoteSharingButton(remoteButton, blog: blog) } // Delete any cached PublicizeServices that were not synced. for button in currentSharingbuttons { if !buttonsToKeep.contains(button) { self.managedObjectContext.delete(button) } } // Save all the things. ContextManager.sharedInstance().save(self.managedObjectContext, withCompletionBlock: { onComplete?() }) } } /// Returns an array of all cached `SharingButtons` objects. /// /// - Parameters /// - blog: A `Blog` object /// /// - Returns: An array of `SharingButton`s. The array is empty if no objects are cached. /// @objc open func allSharingButtonsForBlog(_ blog: Blog) -> [SharingButton] { let request = NSFetchRequest<NSFetchRequestResult>(entityName: SharingButton.classNameWithoutNamespaces()) request.predicate = NSPredicate(format: "blog = %@", blog) request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)] var buttons: [SharingButton] do { buttons = try managedObjectContext.fetch(request) as! [SharingButton] } catch let error as NSError { DDLogError("Error fetching Publicize Connections: \(error.localizedDescription)") buttons = [] } return buttons } /// Composes a new `SharingButton`, or updates an existing one, with /// data represented by the passed `RemoteSharingButton`. /// /// - Parameters: /// - remoteButton: The remote connection representing the publicize connection. /// - blog: The `Blog` that owns or will own the button. /// /// - Returns: A `SharingButton`. /// fileprivate func createOrReplaceFromRemoteSharingButton(_ remoteButton: RemoteSharingButton, blog: Blog) -> SharingButton { var shareButton = findSharingButtonByID(remoteButton.buttonID, blog: blog) if shareButton == nil { shareButton = NSEntityDescription.insertNewObject(forEntityName: SharingButton.classNameWithoutNamespaces(), into: managedObjectContext) as? SharingButton } shareButton?.buttonID = remoteButton.buttonID shareButton?.name = remoteButton.name shareButton?.shortname = remoteButton.shortname shareButton?.custom = remoteButton.custom shareButton?.enabled = remoteButton.enabled shareButton?.visibility = remoteButton.visibility shareButton?.order = remoteButton.order shareButton?.blog = blog return shareButton! } /// Composes `RemoteSharingButton` objects from properties on an array of `SharingButton`s. /// /// - Parameters: /// - shareButtons: An array of `SharingButton` entities. /// /// - Returns: An array of `RemoteSharingButton` objects. /// fileprivate func remoteShareButtonsFromShareButtons(_ shareButtons: [SharingButton]) -> [RemoteSharingButton] { return shareButtons.map { (shareButton) -> RemoteSharingButton in let btn = RemoteSharingButton() btn.buttonID = shareButton.buttonID btn.name = shareButton.name btn.shortname = shareButton.shortname btn.custom = shareButton.custom btn.enabled = shareButton.enabled btn.visibility = shareButton.visibility btn.order = shareButton.order return btn } } /// Finds a cached `SharingButton` by its `buttonID` for the specified `Blog` /// /// - Parameters: /// - buttonID: The button ID of the `sharingButton`. /// - blog: The blog that owns the sharing button. /// /// - Returns: The requested `SharingButton` or nil. /// @objc open func findSharingButtonByID(_ buttonID: String, blog: Blog) -> SharingButton? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: SharingButton.classNameWithoutNamespaces()) request.predicate = NSPredicate(format: "buttonID = %@ AND blog = %@", buttonID, blog) var buttons: [SharingButton] do { buttons = try managedObjectContext.fetch(request) as! [SharingButton] } catch let error as NSError { DDLogError("Error fetching shareing button \(buttonID) : \(error.localizedDescription)") buttons = [] } return buttons.first } // MARK: Private Instance Methods /// Returns the remote to use with the service. /// /// - Parameter blog: The blog to use for the rest api. /// fileprivate func remoteForBlog(_ blog: Blog) -> SharingServiceRemote? { guard let api = blog.wordPressComRestApi() else { return nil } return SharingServiceRemote(wordPressComRestApi: api) } // Error for failure states enum SharingServiceError: Error { case siteWithNoRemote } }
gpl-2.0
ec46256ae5ef68b62158e4e4c03561e8
41.582313
165
0.6325
5.269024
false
false
false
false
ptsochantaris/trailer-cli
Sources/trailer/Data/Models/Reaction.swift
1
2527
// // Reaction.swift // trailer // // Created by Paul Tsochantaris on 18/08/2017. // Copyright © 2017 Paul Tsochantaris. All rights reserved. // import Foundation struct Reaction: Item { var id: String var parents: [String: [Relationship]] var syncState: SyncState var elementType: String var content = "" static let idField = "id" static var allItems = [String: Reaction]() private enum CodingKeys: CodingKey { case id case parents case elementType case content } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) parents = try c.decode([String: [Relationship]].self, forKey: .parents) elementType = try c.decode(String.self, forKey: .elementType) content = try c.decode(String.self, forKey: .content) syncState = .none } func encode(to encoder: Encoder) throws { var c = encoder.container(keyedBy: CodingKeys.self) try c.encode(id, forKey: .id) try c.encode(parents, forKey: .parents) try c.encode(elementType, forKey: .elementType) try c.encode(content, forKey: .content) } mutating func apply(_ node: [AnyHashable: Any]) -> Bool { guard node.keys.count >= 1 else { return false } content = node["content"] as? String ?? "" return true } init?(id: String, type: String, node: [AnyHashable: Any]) { self.id = id parents = [String: [Relationship]]() elementType = type syncState = .new if !apply(node) { return nil } } var user: User? { children(field: "user").first } mutating func setChildrenSyncStatus(_ status: SyncState) { if var u = user { u.setSyncStatus(status, andChildren: true) User.allItems[u.id] = u } } var emoji: String { switch content { case "THUMBS_UP": return "👍" case "THUMBS_DOWN": return "👎" case "LAUGH": return "😄" case "HOORAY": return "🎉" case "CONFUSED": return "😕" case "HEART": return "❤️" case "ROCKET": return "🚀" default: return "?" } } static let fragment = Fragment(name: "reactions", on: "Reaction", elements: [ Field.id, Field(name: "content"), Group(name: "user", fields: [User.fragment]) ]) }
mit
a8704cd1cd5c6e50e31c31a0f4c2d192
26.217391
81
0.571885
4
false
false
false
false
narner/AudioKit
AudioKit/Common/Internals/Audio File/AKAudioFile.swift
1
12514
// // AKAudioFile.swift // AudioKit // // Created by Laurent Veliscek, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Adding description property extension AVAudioCommonFormat: CustomStringConvertible { /// Text version of the format public var description: String { switch self { case .otherFormat: return "OtherFormat" case .pcmFormatFloat32 : return "PCMFormatFloat32" case .pcmFormatFloat64: return "PCMFormatFloat64" case .pcmFormatInt16: return "PCMFormatInt16" case .pcmFormatInt32: return "PCMFormatInt32" } } } /// Helpful additions for using AVAudioFiles within AudioKit @objc extension AVAudioFile { // MARK: - Public Properties /// The number of samples can be accessed by .length property, /// but samplesCount has a less ambiguous meaning open var samplesCount: Int64 { return length } /// strange that sampleRate is a Double and not an Integer open var sampleRate: Double { return fileFormat.sampleRate } /// Number of channels, 1 for mono, 2 for stereo open var channelCount: UInt32 { return fileFormat.channelCount } /// Duration in seconds open var duration: Double { return Double(samplesCount) / (sampleRate) } /// true if Audio Samples are interleaved open var interleaved: Bool { return fileFormat.isInterleaved } /// true only if file format is "deinterleaved native-endian float (AVAudioPCMFormatFloat32)" open var standard: Bool { return fileFormat.isStandard } /// Human-readable version of common format open var commonFormatString: String { return "\(fileFormat.commonFormat)" } /// the directory path as a URL object open var directoryPath: URL { return url.deletingLastPathComponent() } /// the file name with extension as a String open var fileNamePlusExtension: String { return url.lastPathComponent } /// the file name without extension as a String open var fileName: String { return url.deletingPathExtension().lastPathComponent } /// the file extension as a String (without ".") open var fileExt: String { return url.pathExtension } override open var description: String { return super.description + "\n" + String(describing: fileFormat) } /// returns file Mime Type if exists /// Otherwise, returns nil /// (useful when sending an AKAudioFile by email) public var mimeType: String? { switch fileExt.lowercased() { case "wav": return "audio/wav" case "caf": return "audio/x-caf" case "aif", "aiff", "aifc": return "audio/aiff" case "m4r": return "audio/x-m4r" case "m4a": return "audio/x-m4a" case "mp4": return "audio/mp4" case "m2a", "mp2": return "audio/mpeg" case "aac": return "audio/aac" case "mp3": return "audio/mpeg3" default: return nil } } /// Static function to delete all audiofiles from Temp directory /// /// AKAudioFile.cleanTempDirectory() /// public static func cleanTempDirectory() { var deletedFilesCount = 0 let fileManager = FileManager.default let tempPath = NSTemporaryDirectory() do { let fileNames = try fileManager.contentsOfDirectory(atPath: "\(tempPath)") // function for deleting files func deleteFileWithFileName(_ fileName: String) { let filePathName = "\(tempPath)/\(fileName)" do { try fileManager.removeItem(atPath: filePathName) AKLog("\"\(fileName)\" deleted.") deletedFilesCount += 1 } catch let error as NSError { AKLog("Couldn't delete \(fileName) from Temp Directory") AKLog("Error: \(error)") } } // Checks file type (only Audio Files) fileNames.forEach { fn in let lower = fn.lowercased() _ = [".wav", ".caf", ".aif", ".mp4", ".m4a"].first { lower.hasSuffix($0) }.map { _ in deleteFileWithFileName(fn) } } AKLog("\(deletedFilesCount) files deleted") } catch let error as NSError { AKLog("Couldn't access Temp Directory") AKLog("Error: \(error)") } } } /// Audio file, inherits from AVAudioFile and adds functionality @objc open class AKAudioFile: AVAudioFile { // MARK: - embedded enums /// Common places for files /// /// - Temp: Temp Directory /// - Documents: Documents Directory /// - Resources: Resources Directory (Shouldn't be used for writing / recording files) /// - Custom: The same directory as the input file. This is mainly for OS X projects. /// public enum BaseDirectory { /// Temporary directory case temp /// Documents directory case documents /// Resources directory case resources /// Same directory as the input file case custom func create(file path: String, write: Bool = false) throws -> String { switch (self, write) { case (.temp, _): return NSTemporaryDirectory() + path case (.documents, _): return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/" + path case (.resources, false): return try Bundle.main.path(forResource: path, ofType: "") ?? NSError.fileCreateError case (.custom, _): AKLog("ERROR AKAudioFile: custom creation directory not implemented yet") fallthrough default: throw NSError.fileCreateError } } } // MARK: - private vars // Used for exporting, can be accessed with public .avAsset property fileprivate lazy var internalAVAsset: AVURLAsset = { AVURLAsset(url: URL(fileURLWithPath: self.url.path)) }() // MARK: - open vars /// Returns an AVAsset from the AKAudioFile open var avAsset: AVURLAsset { return internalAVAsset } // Make our types Human Friendly™ public typealias FloatChannelData = [[Float]] /// Returns audio data as an `Array` of `Float` Arrays. /// /// If stereo: /// - `floatChannelData?[0]` will contain an Array of left channel samples as `Float` /// - `floatChannelData?[1]` will contains an Array of right channel samples as `Float` open lazy var floatChannelData: FloatChannelData? = { // Do we have PCM channel data? guard let pcmFloatChannelData = self.pcmBuffer.floatChannelData else { return nil } let channelCount = Int(self.pcmBuffer.format.channelCount) let frameLength = Int(self.pcmBuffer.frameLength) let stride = self.pcmBuffer.stride // Preallocate our Array so we're not constantly thrashing while resizing as we append. var result = Array(repeating: [Float](zeros: frameLength), count: channelCount) // Loop across our channels... for channel in 0..<channelCount { // Make sure we go through all of the frames... for sampleIndex in 0..<frameLength { result[channel][sampleIndex] = pcmFloatChannelData[channel][sampleIndex * stride] } } return result }() /// returns audio data as an AVAudioPCMBuffer open lazy var pcmBuffer: AVAudioPCMBuffer = { let buffer = AVAudioPCMBuffer(pcmFormat: self.processingFormat, frameCapacity: AVAudioFrameCount(self.length)) do { try self.read(into: buffer!) } catch let error as NSError { AKLog("error cannot readIntBuffer, Error: \(error)") } return buffer! }() /// returns the peak level expressed in dB ( -> Float). open lazy var maxLevel: Float = { var maxLev: Float = 0 let buffer = self.pcmBuffer if self.samplesCount > 0 { for c in 0..<Int(self.channelCount) { let floats = UnsafeBufferPointer(start: buffer.floatChannelData?[c], count: Int(buffer.frameLength)) let cmax = floats.max() let cmin = floats.min() // positive max maxLev = max(cmax ?? maxLev, maxLev) // negative max maxLev = -min(abs(cmin ?? -maxLev), -maxLev) } } if maxLev == 0 { return Float.leastNormalMagnitude } else { return 10 * log10(maxLev) } }() /// Initialize the audio file /// /// - parameter fileURL: URL of the file /// /// - returns: An initialized AKAudioFile object for reading, or nil if init failed. /// public override init(forReading fileURL: URL) throws { try super.init(forReading: fileURL) } /// Initialize the audio file /// /// - Parameters: /// - fileURL: URL of the file /// - format: The processing commonFormat to use when reading from the file. /// - interleaved: Whether to use an interleaved processing format. /// /// - returns: An initialized AKAudioFile object for reading, or nil if init failed. /// public override init(forReading fileURL: URL, commonFormat format: AVAudioCommonFormat, interleaved: Bool) throws { try super.init(forReading: fileURL, commonFormat: format, interleaved: interleaved) } /// Initialize the audio file /// /// From Apple doc: The file type to create is inferred from the file extension of fileURL. /// This method will overwrite a file at the specified URL if a file already exists. /// /// The file is opened for writing using the standard format, AVAudioPCMFormatFloat32. /// /// Note: It seems that Apple's AVAudioFile class has a bug with .wav files. They cannot be set /// with a floating Point encoding. As a consequence, such files will fail to record properly. /// So it's better to use .caf (or .aif) files for recording purpose. /// /// - Parameters: /// - fileURL: URL of the file. /// - settings: The format of the file to create. /// - format: The processing commonFormat to use when writing. /// - interleaved: Whether to use an interleaved processing format. /// - throws: NSError if init failed /// - returns: An initialized AKAudioFile for writing, or nil if init failed. /// public override init(forWriting fileURL: URL, settings: [String : Any], commonFormat format: AVAudioCommonFormat, interleaved: Bool) throws { try super.init(forWriting: fileURL, settings: settings, commonFormat: format, interleaved: interleaved) } /// Super.init inherited from AVAudioFile superclass /// /// - Parameters: /// - fileURL: URL of the file. /// - settings: The settings of the file to create. /// /// - Returns: An initialized AKAudioFile for writing, or nil if init failed. /// /// From Apple doc: The file type to create is inferred from the file extension of fileURL. /// This method will overwrite a file at the specified URL if a file already exists. /// /// The file is opened for writing using the standard format, AVAudioPCMFormatFloat32. /// /// Note: It seems that Apple's AVAudioFile class has a bug with .wav files. They cannot be set /// with a floating Point encoding. As a consequence, such files will fail to record properly. /// So it's better to use .caf (or .aif) files for recording purpose. /// public override init(forWriting fileURL: URL, settings: [String: Any]) throws { try super.init(forWriting: fileURL, settings: settings) } }
mit
95ccf3c6d6f7979a6d8216e1413859a0
32.451872
116
0.591479
4.929472
false
false
false
false
emadhegab/GenericDataSource
GenericDataSourceTests/TableView.swift
1
4816
// // TableView.swift // GenericDataSource // // Created by Mohamed Afifi on 3/27/16. // Copyright © 2016 mohamede1945. All rights reserved. // import UIKit import GenericDataSource class TableView: UITableView { func reset() { indexPath = nil identifier = nil section = nil cellClass = nil nib = nil called = false sectionsSet = nil animation = nil toSection = nil indexPaths = nil toIndexPath = nil scrollPosition = nil animated = nil cell = nil dequeCell = UITableViewCell() point = nil cells = [] } var indexPath: IndexPath? var identifier: String? var section: Int? var called = false var sectionsSet: IndexSet? var animation: UITableViewRowAnimation? var indexPaths: [IndexPath]? var scrollPosition: UITableViewScrollPosition? var animated: Bool? var cell: UITableViewCell? var cellClass: AnyClass? override func register(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) { self.cellClass = cellClass self.identifier = identifier } var nib: UINib? override func register(_ nib: UINib?, forCellReuseIdentifier identifier: String) { self.nib = nib self.identifier = identifier } var dequeCell = UITableViewCell() override func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell { self.identifier = identifier self.indexPath = indexPath return dequeCell } var sections: Int = 0 override var numberOfSections: Int { return sections } var items: Int = 0 override func numberOfRows(inSection section: Int) -> Int { self.section = section return items } override func reloadData() { called = true } override func ds_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) { called = true } override func insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) { sectionsSet = sections self.animation = animation } override func deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) { sectionsSet = sections self.animation = animation } override func reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) { sectionsSet = sections self.animation = animation } var toSection: Int? override func moveSection(_ section: Int, toSection newSection: Int) { self.section = section toSection = newSection } override func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) { self.indexPaths = indexPaths self.animation = animation } override func deleteRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) { self.indexPaths = indexPaths self.animation = animation } override func reloadRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) { self.indexPaths = indexPaths self.animation = animation } var toIndexPath: IndexPath? override func moveRow(at indexPath: IndexPath, to newIndexPath: IndexPath) { self.indexPath = indexPath self.toIndexPath = newIndexPath } override func scrollToRow(at indexPath: IndexPath, at scrollPosition: UITableViewScrollPosition, animated: Bool) { self.indexPath = indexPath self.scrollPosition = scrollPosition self.animated = animated } override func selectRow(at indexPath: IndexPath?, animated: Bool, scrollPosition: UITableViewScrollPosition) { self.indexPath = indexPath self.animated = animated self.scrollPosition = scrollPosition } override func deselectRow(at indexPath: IndexPath, animated: Bool) { self.indexPath = indexPath self.animated = animated } override func indexPath(for cell: UITableViewCell) -> IndexPath? { self.cell = cell return indexPath } var point: CGPoint? override func indexPathForRow(at point: CGPoint) -> IndexPath? { self.point = point return indexPath } override var indexPathsForVisibleRows: [IndexPath]? { return indexPaths ?? [] } override var indexPathsForSelectedRows: [IndexPath]? { return indexPaths ?? [] } var cells: [UITableViewCell] = [] override var visibleCells: [UITableViewCell] { return cells } override func cellForRow(at indexPath: IndexPath) -> UITableViewCell? { self.indexPath = indexPath return cell } }
mit
b87b2b92135b33a751aa53ffd543f048
27.157895
119
0.652752
5.385906
false
false
false
false
mergesort/TableFlip
Example/TableFlipExample/TableViewController.swift
1
4307
// // TableViewController.swift // TableFlipExample // // Created by Joe Fabisevich on 8/27/17. // Copyright © 2017 Mergesort. All rights reserved. // import UIKit enum ExampleAnimation { case fade case top case left case custom case indexPaths } final class TableViewController: UIViewController { private let animation: ExampleAnimation private let dataSource = ExampleDataSource() let tableView: UITableView = { let tableView = UITableView() tableView.rowHeight = 64.0 tableView.tableFooterView = UIView() return tableView }() // MARK: Initializers init(animation: ExampleAnimation) { self.animation = animation super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("Unimplemented, and loving it.") } // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() self.setup() } } private extension TableViewController { func setup() { self.tableView.dataSource = self.dataSource self.view.addSubview(self.tableView) self.title = self.animation.title self.setupConstraints() // Delayed to simulate a network connection, like in the real world, which is where I live. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { self.dataSource.hasLoaded = true self.tableView.reloadData() self.animateTableView() } } func setupConstraints() { self.tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.tableView.topAnchor.constraint(equalTo: self.view.topAnchor), self.tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), ]) } func animateTableView() { switch self.animation { case .top: let topAnimation = TableViewAnimation.Table.top(duration: 0.8) self.tableView.animate(animation: topAnimation) case .fade: let fadeAnimation = TableViewAnimation.Cell.fade(duration: 0.3) self.tableView.animate(animation: fadeAnimation) case .left: let leftAnimation = TableViewAnimation.Cell.left() self.tableView.animate(animation: leftAnimation, indexPaths: nil, completion: nil) case .custom: let degrees = sin(90.0 * CGFloat.pi/180.0) let rotationTransform = CGAffineTransform(rotationAngle: degrees) let flipTransform = CGAffineTransform(scaleX: -1, y: -1) let customTransform = rotationTransform.concatenating(flipTransform) let customAnimation = TableViewAnimation.Cell.custom(duration: 0.6, transform: customTransform, options: .curveEaseInOut) self.tableView.animate(animation: customAnimation, completion: nil) case .indexPaths: let groupedItems = Dictionary(grouping: (0..<self.dataSource.exampleItems.count), by: { $0 % 2 }) let oddIndices = groupedItems[1]?.compactMap { IndexPath(row: $0, section: 0) } let leftAnimation = TableViewAnimation.Cell.left() self.tableView.animate(animation: leftAnimation, indexPaths: oddIndices, completion: nil) let evenIndices = groupedItems[0]?.compactMap { IndexPath(row: $0, section: 0) } let rightAnimation = TableViewAnimation.Cell.right() self.tableView.animate(animation: rightAnimation, indexPaths: evenIndices, completion: nil) } } } private extension ExampleAnimation { var title: String { switch self { case .custom: return "Custom Animation" case .top: return "Top Animation" case .left: return "Left Animation" case .fade: return "Fade Animation" case .indexPaths: return "Select Index Paths Animation" } } }
mit
8fd7437893ac53f212c7369ccf1fe01f
28.493151
133
0.632606
4.876557
false
false
false
false