repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
BanyaKrylov/Learn-Swift
refs/heads/master
Skill/Homework 6/Homework 6.6.3/Homework 6.6.3/ViewController.swift
apache-2.0
1
// // ViewController.swift // Homework 6.6.3 // // Created by Ivan Krylov on 03.02.2020. // Copyright © 2020 Ivan Krylov. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var numberOne: UITextField! @IBOutlet weak var operatorForCalc: UITextField! @IBOutlet weak var numberTwo: UITextField! @IBAction func calculationButton(_ sender: Any) { let operators: Optional = (plus: "+", minus: "-", division: "/", multiple: "*") if Int(numberOne.text!) != nil && Int(numberTwo.text!) != nil && operators != nil{ switch operatorForCalc.text! { case operators!.plus: resultLabel.text = String(Int(numberOne.text!)! + Int(numberTwo.text!)!) case operators!.minus: resultLabel.text = String(Int(numberOne.text!)! - Int(numberTwo.text!)!) case operators!.division: resultLabel.text = String(Double(Int(numberOne.text!)!) / Double(Int(numberTwo.text!)!)) case operators!.multiple: resultLabel.text = String(Int(numberOne.text!)! * Int(numberTwo.text!)!) default: resultLabel.text = "Некорректные данные" } } else { resultLabel.text = "Некорректные данные" } } }
e80f4abfe09fa030c77ef19df588f619
34.738095
104
0.602931
false
false
false
false
youkchansim/CSPhotoGallery
refs/heads/master
Example/CSPhotoGallery/ViewController.swift
mit
1
// // ViewController.swift // CSPhotoGallery // // Created by chansim.youk on 12/30/2016. // Copyright (c) 2016 chansim.youk. All rights reserved. // import UIKit import CSPhotoGallery import Photos class ViewController: UIViewController { @IBAction func btnAction(_ sender: Any) { let designManager = CSPhotoDesignManager.instance // Main designManager.photoGalleryOKButtonTitle = "OK" let vc = CSPhotoGalleryViewController.instance vc.delegate = self vc.CHECK_MAX_COUNT = 10 vc.horizontalCount = 4 // present(vc, animated: true) navigationController?.pushViewController(vc, animated: true) } 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. } } extension ViewController: CSPhotoGalleryDelegate { func getAssets(assets: [PHAsset]) { assets.forEach { let size = CGSize(width: $0.pixelWidth, height: $0.pixelHeight) PhotoManager.sharedInstance.assetToImage(asset: $0, imageSize: size, completionHandler: nil) } } }
5b923af69914208e7c25c9ae2c8f6808
27.73913
104
0.657337
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainUI/Accessibility+CryptoDomain.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. enum AccessibilityIdentifiers { // MARK: - How it Works Sceren enum HowItWorks { static let prefix = "HowItWorksScreen." static let headerTitle = "\(prefix)headerTitle" static let headerDescription = "\(prefix)headerDescription" static let introductionList = "\(prefix)instructionList" static let smallButton = "\(prefix)smallButton" static let instructionText = "\(prefix)instructionText" static let ctaButton = "\(prefix)ctaButton" } // MARK: - Benefits Screen enum Benefits { static let prefix = "CryptoDomainBenefitsScreen." static let headerTitle = "\(prefix)headerTitle" static let headerDescription = "\(prefix)headerDescription" static let benefitsList = "\(prefix)benefitsList" static let ctaButton = "\(prefix)ctaButton" } // MARK: - Search Domain Screen enum SearchDomain { static let prefix = "SearchDomainScreen." static let searchBar = "\(prefix)searchBar" static let alertCard = "\(prefix)alertCard" static let domainList = "\(prefix)domainList" static let domainListRow = "\(prefix)domainListRow" } // MARK: - Domain Checkout Screen enum DomainCheckout { static let prefix = "DomainCheckoutScreen." static let selectedDomainList = "\(prefix)selectedDomainList" static let termsSwitch = "\(prefix)termsSwitch" static let termsText = "\(prefix)termsText" static let ctaButton = "\(prefix)ctaButton" static let emptyStateIcon = "\(prefix)emptyStateIcon" static let emptyStateTitle = "\(prefix)emptyStateTitle" static let emptyStateDescription = "\(prefix)emptyStateDescription" static let browseButton = "\(prefix)browseButton" } enum RemoveDomainBottomSheet { static let prefix = "RemoveDomainBottomSheet." static let removeIcon = "\(prefix)removeIcon" static let removeTitle = "\(prefix)removeTitle" static let removeButton = "\(prefix)removeButton" static let nevermindButton = "\(prefix)nevermindButton" } enum BuyDomainBottomSheet { static let prefix = "BuyDomainBottomSheet." static let buyTitle = "\(prefix)buyTitle" static let buyDescription = "\(prefix)buyTitle" static let buyButton = "\(prefix)buyButton" static let goBackButton = "\(prefix)goBackButton" } // MARK: - Checkout Confirmation Screen enum CheckoutConfirmation { static let prefix = "DomainCheckoutConfirmationScreen." static let icon = "\(prefix)icon" static let title = "\(prefix)title" static let description = "\(prefix)description" static let learnMoreButton = "\(prefix)learnMoreButton" static let okayButton = "\(prefix)okayButton" } }
cb158e47f0c258ac74d35c88f43f8a09
36.883117
75
0.661981
false
false
false
false
lfkdsk/JustUiKit
refs/heads/master
JustUiKit/params/JustLayoutParams.swift
mit
1
/// MIT License /// /// Copyright (c) 2017 JustWe /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in all /// copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. import UIKit public class LayoutParams { public static let MATCH_PARENT: CGFloat = -1 public static let WRAP_CONTENT: CGFloat = -2 public var width: CGFloat = 0 public var height: CGFloat = 0 public var bindView: UIView? = nil public init(width: CGFloat, height: CGFloat) { self.width = width self.height = height } public func bindWith(view: UIView?) { self.bindView = view } public init(_ params: LayoutParams) { self.width = params.width self.height = params.height } public static func generateDefaultLayoutParams() -> LayoutParams { return LayoutParams(width: 0, height: 0) } } public class MarginLayoutParams: LayoutParams { private static let DEFAULT_MARGIN: Int = 0; public var leftMargin = DEFAULT_MARGIN public var rightMargin = DEFAULT_MARGIN public var topMargin = DEFAULT_MARGIN public var bottomMargin = DEFAULT_MARGIN public var startMargin = DEFAULT_MARGIN public var endMargin = DEFAULT_MARGIN override public init(_ source: LayoutParams) { super.init(source) } override public init(width: CGFloat, height: CGFloat) { super.init(width: width, height: height) } public init(source: MarginLayoutParams) { super.init(width: source.width, height: source.height) self.leftMargin = source.leftMargin self.rightMargin = source.rightMargin self.topMargin = source.topMargin self.bottomMargin = source.bottomMargin } public func setMargins(left: Int, top: Int, right: Int, bottom: Int) { leftMargin = left; topMargin = top; rightMargin = right; bottomMargin = bottom; } }
421faf876ce5f93d2ab0c974e33071ab
32.397727
85
0.679823
false
false
false
false
alessandrostone/TKSwarmAlert
refs/heads/master
TKSwarmAlert/Classes/TKSwarmAlert.swift
mit
9
// // SWAlert.swift // SWAlertView // // Created by Takuya Okamoto on 2015/08/18. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit public typealias Closure=()->Void public class TKSwarmAlert { public var didDissmissAllViews: Closure? private var staticViews: [UIView] = [] var animationView: FallingAnimationView? var blurView: TKSWBackgroundView? public init() { } public func addNextViews(views:[UIView]) { self.animationView?.nextViewsList.append(views) } public func addSubStaticView(view:UIView) { view.tag = -1 self.staticViews.append(view) } public func show(#type:TKSWBackgroundType ,views:[UIView]) { let window:UIWindow? = UIApplication.sharedApplication().keyWindow if window != nil { let frame:CGRect = window!.bounds blurView = TKSWBackgroundView(frame: frame) animationView = FallingAnimationView(frame: frame) let showDuration:NSTimeInterval = 0.2 for staticView in staticViews { let originalAlpha = staticView.alpha staticView.alpha = 0 animationView?.addSubview(staticView) UIView.animateWithDuration(showDuration) { staticView.alpha = originalAlpha } } window!.addSubview(blurView!) window!.addSubview(animationView!) blurView?.show(type: type, duration:showDuration) { self.spawn(views) } animationView?.willDissmissAllViews = { let fadeOutDuration:NSTimeInterval = 0.2 for v in self.staticViews { UIView.animateWithDuration(fadeOutDuration) { v.alpha = 0 } } UIView.animateWithDuration(fadeOutDuration) { blurView?.alpha = 0 } } animationView?.didDissmissAllViews = { self.blurView?.removeFromSuperview() self.animationView?.removeFromSuperview() self.didDissmissAllViews?() for staticView in self.staticViews { staticView.alpha = 1 } } } } public func spawn(views:[UIView]) { self.animationView?.spawn(views) } }
7c668f10ef10c2c7fc971447b97a581f
28.939759
74
0.552113
false
false
false
false
sdhzwm/BaiSI-Swift-
refs/heads/master
BaiSi/BaiSi/Classes/Main(主要)/Controller/WMNavigationController.swift
apache-2.0
1
// // WMNavigationController.swift // WMMatchbox // // Created by 王蒙 on 15/7/21. // Copyright © 2015年 wm. All rights reserved. // import UIKit class WMNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() UINavigationBar.appearance().setBackgroundImage(UIImage(named: "navigationbarBackgroundWhite"), forBarMetrics: UIBarMetrics.Default) } override func pushViewController(viewController: UIViewController, animated: Bool) { if (self.childViewControllers.count>0) { let btn = UIButton(type: UIButtonType.Custom) btn.setTitle("返回", forState: UIControlState.Normal) btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) btn.setTitleColor(UIColor.redColor(), forState: UIControlState.Highlighted) btn.setImage(UIImage(named: "navigationButtonReturn"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "navigationButtonReturnClick"), forState: UIControlState.Highlighted) btn.sizeToFit() btn.contentEdgeInsets = UIEdgeInsetsMake(0, -35, 0, 0); // btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; // btn.size = CGSizeMake(60, 35); // btn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0); btn.addTarget(self, action: "onClick", forControlEvents: UIControlEvents.TouchUpInside) btn.titleLabel?.font = UIFont.systemFontOfSize(14) viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn) viewController.hidesBottomBarWhenPushed = true; } super.pushViewController(viewController, animated: true) } func onClick(){ self.popViewControllerAnimated(true) } }
c883356aaa708ee0c9557647266d7cca
36.692308
140
0.647449
false
false
false
false
r14r-work/fork_swift_intro-playgrounds
refs/heads/master
08-Functions (Part 2).playground/section-1.swift
mit
2
// Functions - Part 2 import Foundation // ************************************************************************* // Simple "void" function - takes no parameters, returns nothing func sayHi() { println("Hi") } sayHi() // ************************************************************************* // Function taking two parameters, printing result of adding parameters. func printAplusB(a: Int, b: Int) { println("\(a) + \(b) = \(a+b)") } printAplusB(10, 20) // ************************************************************************* // Function returning the answer as a string. // -> is called the "return arrow" func resultOfAplusB(a: Int, b: Int) -> String { return "\(a) + \(b) = \(a+b)" } // Try option+click on "result". Xcode shows you the type info! let result = resultOfAplusB(30, 40) // ************************************************************************* // Returning a tuple func doHTTPGet(urlString: String) -> (statusCode: Int, statusMessage: String) { // Imagine we are doing an actual HTTP request here. return (200, "OK") } let getResult = doHTTPGet("http://twitter.com") println("Code - \(getResult.statusCode)") println("Message - \(getResult.statusMessage)") // ************************************************************************* // You must return a value from each control path in a function! func missingReturn(flag: Bool) -> Int { if flag == true { return 1 } else { // Comment out to see error. return 0 // error: missing return in a function expected to return 'Int' } } // ********************* // START HERE FOR PART 2 // ********************* // ************************************************************************* // External parameter names (named parameters). If provided, external // parameter names must always be used when calling function. func distanceBetweenPoints(X1 x1: Double, Y1 y1: Double, X2 x2:Double, Y2 y2:Double) -> Double { let dx = x2 - x1 let dy = y2 - y1 return sqrt(dx * dx + dy * dy) } let distance = distanceBetweenPoints(X1: 0.0, Y1: 0.0, X2: 10.0, Y2: 0.0) // ************************************************************************* // Short-hand for external names (use when internal name is suitable for use // as external name too. func lineLength(#x1: Double, #y1: Double, #x2: Double, #y2: Double) -> Double { let dx = x2 - x1 let dy = y2 - y1 return sqrt(dx * dx + dy * dy) } let length = lineLength(x1: 0.0, y1: 0.0, x2: 10.0, y2: 0.0) // ************************************************************************* // Default parameter values func concatenateStrings(s1: String, s2: String, separator: String = " ") -> String { return s1 + separator + s2 } concatenateStrings("Bennett", "Smith") // Note: parameter with default value always has external name! concatenateStrings("Hello", "World", separator: ", ") // ************************************************************************* // Variadic paramters (variable length array of parameters, all of same type!) func addNumbers(numbers: Double ...) -> Double { var sum = 0.0 for number in numbers { sum += number } return sum } let total = addNumbers(0.99, 1.21, 0.30, 2.50) // ************************************************************************* // Constant vs. variable parameters. // Variable parameters can be changed within the function, but their // values do not live beyond the scope of the function. func applyOffset_Broken(number: Int, offset: Int) { // Uncomment to see error. // number = number + offset // error: cannot assign to 'let' value 'number' } func applyOffset_Works(var number: Int, offset: Int) { number = number + offset } var n = 10 let o = 2 applyOffset_Broken(n, o) n applyOffset_Works(n, o) n // ************************************************************************* // In-Out Parameters func applyOffset(inout Number n:Int, let Offset o:Int = 5) { n = n + o } applyOffset(Number: &n) n applyOffset(Number: &n, Offset: 25) n // ************************************************************************* // Function Types - Every function is actually a Swift type, made up of the // parameter types and the return type. // A function that takes no parameters and returns nothing. func degenerateCase() { } // Type of this function is "() -> ()" // More interesting case... func add(a: Int, b: Int) -> Int { return a + b } func mul(a: Int, b: Int) -> Int { return a * b } // Type for both functions is "(Int, Int) -> Int" // Can store a function in a variable like so: var mathOp: (Int, Int) -> Int = mul // Can invoke function using function type like so: let r1 = mathOp(2, 3) // And re-assign it, pointing at a different function. mathOp = add let r2 = mathOp(2, 3) // This is very similar to C function pointers! // ************************************************************************* // Passing function type as a parameter func performMathOp(mathOp: (Int, Int) -> Int, a: Int, b: Int) { let result = mathOp(a, b) println("result = \(result)") } performMathOp(add, 3, 2) // ************************************************************************* // Returning function type from a function func randomMathOp() -> (Int, Int) -> Int { let r = arc4random_uniform(1) if r == 0 { return add } else { return mul } } mathOp = randomMathOp() let r3 = mathOp(2, 2) // ************************************************************************* // Nested functions func sortNumbers(numbers: Int[]) -> Int[] { func compare(n1: Int, n2: Int) -> Bool { return n1 < n2 } var result = sort(numbers, compare) return result } let numbers = [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ] let sortedNumbers = sortNumbers(numbers) // *************************************************************************
b93875c6275f42ba7011c9911ba5edeb
23.395918
96
0.503932
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/AvatarView.swift
gpl-3.0
1
// // AvatarView.swift // Habitica // // Created by Phillip Thelen on 07.02.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import UIKit import PinLayout import Kingfisher @objc enum AvatarViewSize: Int { case compact case regular } @IBDesignable class AvatarView: UIView { @objc var avatar: Avatar? { didSet { if let dict = avatar?.getFilenameDictionary(ignoreSleeping: ignoreSleeping) { nameDictionary = dict } updateView() } } @IBInspectable var showBackground: Bool = true @IBInspectable var showMount: Bool = true @IBInspectable var showPet: Bool = true @IBInspectable var isFainted: Bool = false @IBInspectable var ignoreSleeping: Bool = false @objc var size: AvatarViewSize = .regular public var onRenderingFinished: (() -> Void)? private var nameDictionary: [String: String?] = [:] private var viewDictionary: [String: Bool] = [:] private let viewOrder = [ "background", "mount-body", "chair", "back", "skin", "shirt", "head_0", "armor", "body", "hair-bangs", "hair-base", "hair-mustache", "hair-beard", "eyewear", "head", "head-accessory", "hair-flower", "shield", "weapon", "visual-buff", "mount-head", "zzz", "knockout", "pet" ] lazy private var constraintsDictionary = [ "background": backgroundConstraints, "mount-body": mountConstraints, "chair": characterConstraints, "back": characterConstraints, "skin": characterConstraints, "shirt": characterConstraints, "armor": characterConstraints, "body": characterConstraints, "head_0": characterConstraints, "hair-base": characterConstraints, "hair-bangs": characterConstraints, "hair-mustache": characterConstraints, "hair-beard": characterConstraints, "eyewear": characterConstraints, "head": characterConstraints, "head-accessory": characterConstraints, "hair-flower": characterConstraints, "shield": characterConstraints, "weapon": characterConstraints, "visual-buff": characterConstraints, "mount-head": mountConstraints, "zzz": characterConstraints, "knockout": characterConstraints, "pet": petConstraints ] lazy private var specialConstraintsDictionary = [ "weapon_special_0": weaponSpecialConstraints, "weapon_special_1": weaponSpecialConstraints, "weapon_special_critical": weaponSpecialCriticalConstraints, "head_special_0": headSpecialConstraints, "head_special_1": headSpecialConstraints ] func resize(view: UIImageView, image: UIImage, size: AvatarViewSize) { let ratio = image.size.width / image.size.height if size == .regular { view.pin.aspectRatio(ratio).height(image.size.height * (self.bounds.size.height / 147)) } else { view.pin.aspectRatio(ratio).height(image.size.height * (self.bounds.size.height / 90)) } } let backgroundConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in view.pin.all() } let characterConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(17%).top(offset) } else { view.pin.start().top(offset) } } let mountConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in view.pin.start(17.5%).top(12%) } let petConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in view.pin.start().bottom() } let weaponSpecialConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(8%).top(offset) } else { view.pin.start().top(offset) } } let weaponSpecialCriticalConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(8%).top(offset+10) } else { view.pin.start(-10%).top(offset) } } let headSpecialConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(17%).top(offset+3) } else { view.pin.start().top(offset+3) } } var imageViews = [NetworkImageView]() override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } private func setupSubviews() { viewOrder.forEach({ (_) in let imageView = NetworkImageView() addSubview(imageView) imageViews.append(imageView) }) } private func updateView() { guard let avatar = self.avatar else { return } viewDictionary = avatar.getViewDictionary(showsBackground: showBackground, showsMount: showMount, showsPet: showPet, isFainted: isFainted, ignoreSleeping: ignoreSleeping) viewOrder.enumerated().forEach({ (index, type) in if viewDictionary[type] ?? false { let imageView = imageViews[index] imageView.isHidden = false setImage(imageView, type: type) } else { let imageView = imageViews[index] imageView.image = nil imageView.isHidden = true } }) if let action = self.onRenderingFinished { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { action() } } } private func setImage(_ imageView: NetworkImageView, type: String) { guard let name = nameDictionary[type] else { return } imageView.setImagewith(name: name, completion: { image, error in if let image = image, type != "background" { self.resize(view: imageView, image: image, size: self.size) self.setLayout(imageView, type: type) } if error != nil { print(error?.localizedDescription ?? "") } }) } override func layoutSubviews() { super.layoutSubviews() layout() } private func layout() { viewOrder.enumerated().forEach({ (index, type) in if viewDictionary[type] ?? false { let imageView = imageViews[index] imageView.isHidden = false if let image = imageView.image, type != "background" { self.resize(view: imageView, image: image, size: self.size) setLayout(imageView, type: type) } setLayout(imageView, type: type) } else { let imageView = imageViews[index] imageView.image = nil imageView.isHidden = true } }) } private func setLayout(_ imageView: UIImageView, type: String) { var offset: CGFloat = 0 if !(viewDictionary["mount-head"] ?? false) && size == .regular { offset = 28 if viewDictionary["pet"] ?? false { offset -= 3 } } if nameDictionary["mount-head"]??.contains("Kangaroo") == true && size == .regular { offset = 16 } let name = nameDictionary[type] ?? "" if let name = name, specialConstraintsDictionary[name] != nil { specialConstraintsDictionary[name]?(self, imageView, size, offset) } else { constraintsDictionary[type]?(self, imageView, size, offset) } } }
3a196640e241b7ac5e3aa505aed69f31
31.316602
178
0.56822
false
false
false
false
vittoriom/NDHpple
refs/heads/master
NDHpple/NDHpple/NDHppleElement.swift
mit
1
// // NDHppleElement.swift // NDHpple // // Created by Nicolai on 24/06/14. // Copyright (c) 2014 Nicolai Davidsson. All rights reserved. // import Foundation enum NDHppleNodeKey: String { case Content = "nodeContent" case Name = "nodeName" case Children = "nodeChildArray" case AttributeArray = "nodeAttributeArray" case AttributeContent = "attributeContent" case AttributeName = "attributeName" } class NDHppleElement { typealias Node = Dictionary<String, AnyObject> let node: Node weak var parent: NDHppleElement? convenience init(node: Node) { self.init(node: node, parent: nil) } init(node: Node, parent: NDHppleElement?) { self.node = node self.parent = parent } subscript(key: String) -> AnyObject? { return self.node[key] } var description: String { return self.node.description } var hasChildren: Bool { return self[NDHppleNodeKey.Children.rawValue] as? Int != nil } var isTextNode: Bool { return self.tagName == "text" && self.content != nil } var raw: String? { return self["raw"] as? String } var content: String? { return self[NDHppleNodeKey.Content.rawValue] as? String } var tagName: String? { return self[NDHppleNodeKey.Name.rawValue] as? String } var children: Array<NDHppleElement>? { let children = self[NDHppleNodeKey.Children.rawValue] as? Array<Dictionary<String, AnyObject>> return children?.map{ NDHppleElement(node: $0, parent: self) } } var firstChild: NDHppleElement? { return self.children?[0] } func childrenWithTagName(tagName: String) -> Array<NDHppleElement>? { return self.children?.filter{ $0.tagName == tagName } } func firstChildWithTagName(tagName: String) -> NDHppleElement? { return self.childrenWithTagName(tagName)?[0] } func childrenWithClassName(className: String) -> Array<NDHppleElement>? { return self.children?.filter{ $0["class"] as? String == className } } func firstChildWithClassName(className: String) -> NDHppleElement? { return self.childrenWithClassName(className)?[0] } var firstTextChild: NDHppleElement? { return self.firstChildWithTagName("text") } var text: String? { return self.firstTextChild?.content } var attributes: Dictionary<String, AnyObject> { var translatedAttribtues = Dictionary<String, AnyObject>() for attributeDict in self[NDHppleNodeKey.AttributeArray.rawValue] as! Array<Dictionary<String, AnyObject>> { if attributeDict[NDHppleNodeKey.Content.rawValue] != nil && attributeDict[NDHppleNodeKey.AttributeName.rawValue] != nil { let value : AnyObject = attributeDict[NDHppleNodeKey.Content.rawValue]! let key : AnyObject = attributeDict[NDHppleNodeKey.AttributeName.rawValue]! translatedAttribtues.updateValue(value, forKey: key as! String) } } return translatedAttribtues } }
a5cd48a8b6e991d050e7b57d4da18029
33.153846
147
0.656049
false
false
false
false
kyleduo/TinyPNG4Mac
refs/heads/master
source/tinypng4mac/utils/TPConfig.swift
mit
1
// // KeyStore.swift // tinypng // // Created by kyle on 16/7/1. // Copyright © 2016年 kyleduo. All rights reserved. // import Foundation class TPConfig { static let KEY_API = "saved_api_key" static let KEY_OUTPUT_FILE = "output_path" static let KEY_REPLACE = "replace" static func saveKey(_ key: String) { UserDefaults.standard.set(key, forKey: KEY_API) } static func savedkey() -> String? { return UserDefaults.standard.string(forKey: KEY_API) } static func savePath(_ path: String) { UserDefaults.standard.set(path, forKey: KEY_OUTPUT_FILE) } static func savedPath() -> String? { var path = UserDefaults.standard.string(forKey: KEY_OUTPUT_FILE) if path == nil || path == "" { path = IOHeler.getDefaultOutputPath().path TPConfig.savePath(path!) } return path } static func saveReplace(_ replace: Bool) { UserDefaults.standard.set(replace, forKey: KEY_REPLACE); } static func shouldReplace() -> Bool! { return UserDefaults.standard.bool(forKey: KEY_REPLACE) } static func removeKey() { UserDefaults.standard.removeObject(forKey: KEY_API) UserDefaults.standard.removeObject(forKey: KEY_REPLACE) } }
3dd8903d74fb4b6bec4f3252706fb57f
22.734694
66
0.699054
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModelTests/Test Doubles/API/FakeAPI.swift
mit
1
import EurofurenceModel import Foundation class FakeAPI: API { private var feedbackRequests: [EventFeedbackRequest: (Bool) -> Void] = [:] func submitEventFeedback(_ request: EventFeedbackRequest, completionHandler: @escaping (Bool) -> Void) { feedbackRequests[request] = completionHandler } func simulateSuccessfulFeedbackResponse(for request: EventFeedbackRequest) { guard let handler = feedbackRequests[request] else { return } handler(true) feedbackRequests[request] = nil } func simulateUnsuccessfulFeedbackResponse(for request: EventFeedbackRequest) { guard let handler = feedbackRequests[request] else { return } handler(false) feedbackRequests[request] = nil } private(set) var capturedLoginRequest: LoginRequest? private var loginHandler: ((LoginResponse?) -> Void)? func performLogin(request: LoginRequest, completionHandler: @escaping (LoginResponse?) -> Void) { capturedLoginRequest = request loginHandler = completionHandler } private(set) var wasToldToLoadPrivateMessages = false private(set) var capturedAuthToken: String? private var messagesHandler: (([MessageCharacteristics]?) -> Void)? func loadPrivateMessages(authorizationToken: String, completionHandler: @escaping ([MessageCharacteristics]?) -> Void) { wasToldToLoadPrivateMessages = true capturedAuthToken = authorizationToken self.messagesHandler = completionHandler } private(set) var messageIdentifierMarkedAsRead: String? private(set) var capturedAuthTokenForMarkingMessageAsRead: String? func markMessageWithIdentifierAsRead(_ identifier: String, authorizationToken: String) { messageIdentifierMarkedAsRead = identifier capturedAuthTokenForMarkingMessageAsRead = authorizationToken } var requestedFullStoreRefresh: Bool { return capturedLastSyncTime == nil } fileprivate var completionHandler: ((ModelCharacteristics?) -> Void)? private(set) var capturedLastSyncTime: Date? private(set) var didBeginSync = false func fetchLatestData(lastSyncTime: Date?, completionHandler: @escaping (ModelCharacteristics?) -> Void) { didBeginSync = true capturedLastSyncTime = lastSyncTime self.completionHandler = completionHandler } private struct DownloadRequest: Hashable { var identifier: String var contentHashSha1: String } private var stubbedResponses = [DownloadRequest: Data]() private(set) var downloadedImageIdentifiers = [String]() func fetchImage(identifier: String, contentHashSha1: String, completionHandler: @escaping (Data?) -> Void) { downloadedImageIdentifiers.append(identifier) let data = "\(identifier)_\(contentHashSha1)".data(using: .utf8) let request = DownloadRequest(identifier: identifier, contentHashSha1: contentHashSha1) stubbedResponses[request] = data completionHandler(data) } } extension FakeAPI { func stubbedImage(for identifier: String?, availableImages: [ImageCharacteristics]) -> Data? { return stubbedResponses.first(where: { $0.key.identifier == identifier })?.value } func simulateSuccessfulSync(_ response: ModelCharacteristics) { completionHandler?(response) } func simulateUnsuccessfulSync() { completionHandler?(nil) } func simulateLoginResponse(_ response: LoginResponse) { loginHandler?(response) } func simulateLoginFailure() { loginHandler?(nil) } func simulateMessagesResponse(response: [MessageCharacteristics] = []) { messagesHandler?(response) } func simulateMessagesFailure() { messagesHandler?(nil) } } class SlowFakeImageAPI: FakeAPI { fileprivate var pendingFetches = [() -> Void]() var numberOfPendingFetches: Int { return pendingFetches.count } override func fetchImage(identifier: String, contentHashSha1: String, completionHandler: @escaping (Data?) -> Void) { pendingFetches.append { super.fetchImage(identifier: identifier, contentHashSha1: contentHashSha1, completionHandler: completionHandler) } } } extension SlowFakeImageAPI { func resolvePendingFetches() { pendingFetches.forEach({ $0() }) pendingFetches.removeAll() } func resolveNextFetch() { guard pendingFetches.isEmpty == false else { return } let next = pendingFetches.remove(at: 0) next() } } class OnlyToldToRefreshOnceMockAPI: FakeAPI { private var refreshCount = 0 var toldToRefreshOnlyOnce: Bool { return refreshCount == 1 } override func fetchLatestData(lastSyncTime: Date?, completionHandler: @escaping (ModelCharacteristics?) -> Void) { refreshCount += 1 super.fetchLatestData(lastSyncTime: lastSyncTime, completionHandler: completionHandler) } }
393dbd481bb91ca5947218f968c2920a
31.018868
124
0.687684
false
false
false
false
ksco/swift-algorithm-club-cn
refs/heads/master
Two-Sum Problem/Solution 1/2Sum.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play func twoSumProblem(a: [Int], k: Int) -> ((Int, Int))? { var map = [Int: Int]() for i in 0 ..< a.count { if let newK = map[a[i]] { return (newK, i) } else { map[k - a[i]] = i } } return nil } let a = [7, 100, 2, 21, 12, 10, 22, 14, 3, 4, 8, 4, 9] if let (i, j) = twoSumProblem(a, k: 33) { i // 3 a[i] // 21 j // 4 a[j] // 12 a[i] + a[j] // 33 } twoSumProblem(a, k: 37) // nil
ec8a9266df59c9316aec5c7b6ff4a9f8
19.68
55
0.435203
false
false
false
false
awind/Pixel
refs/heads/master
Pixel/UserInfoViewController.swift
apache-2.0
1
// // UserInfoViewController.swift // Pixel // // Created by SongFei on 15/12/14. // Copyright © 2015年 SongFei. All rights reserved. // import UIKit import PureLayout import Alamofire class UserInfoViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var coverImageView: UIImageView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var numberOfPhotosLabel: UILabel! @IBOutlet weak var numberOfFriendsLabel: UILabel! @IBOutlet weak var numberOfFollowersLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var birthdayLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var domainLabel: UILabel! var isSelf = false var rightButton: UIBarButtonItem? var userId: Int? override func viewDidLoad() { super.viewDidLoad() self.title = "User" if isSelf { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "ic_settings"), style: .Plain, target: self, action: #selector(settings)) } else { rightButton = UIBarButtonItem(title: "Follow", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(updateFollowStatus)) self.navigationItem.rightBarButtonItem = rightButton } self.navigationController?.navigationBar.barTintColor = UIColor(red: 46.0/255.0, green: 123.0/255.0, blue: 213.0/255.0, alpha: 1.0) self.navigationController?.navigationBar.barStyle = UIBarStyle.Black self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() avatarImageView.layer.masksToBounds = true avatarImageView.layer.cornerRadius = (avatarImageView.frame.size.height) / 2 avatarImageView.clipsToBounds = true scrollView.delegate = self if Account.checkIsLogin() && isSelf{ requestSelfInfo() } else if self.userId != nil { requestUserInfo() } else { // not login, add avatar avatarImageView.image = UIImage(named: "user_placeholder") let userSingleTap = UITapGestureRecognizer(target: self, action: #selector(userAvatarTapped)) userSingleTap.numberOfTapsRequired = 1 avatarImageView.addGestureRecognizer(userSingleTap) usernameLabel.text = "点击头像登录" } } func requestSelfInfo() { Alamofire.request(Router.Users()) .responseSwiftyJSON { response in if let json = response.result.value { if let username = json["user"]["username"].string, avatar = json["user"]["userpic_https_url"].string,id = json["user"]["id"].int, photosCount = json["user"]["photos_count"].int, friendsCount = json["user"]["friends_count"].int, followersCount = json["user"]["followers_count"].int { self.userId = id let user = User(id: id, username: username, avatar: avatar) user.email = json["user"]["email"].string var city = "" var country = "" if let cityString = json["user"]["city"].string { city = cityString } if let countryString = json["user"]["country"].string { country = countryString } user.location = "\(city) \(country)" user.domain = json["user"]["domain"].string user.coverURL = json["user"]["cover_url"].string user.followersCount = followersCount user.friendsCount = friendsCount user.photosCount = photosCount self.updateUserInfo(user) } } } } func requestUserInfo() { Alamofire.request(Router.UsersShow(self.userId!)) .responseSwiftyJSON { response in if let json = response.result.value { if let username = json["user"]["username"].string, avatar = json["user"]["userpic_https_url"].string, id = json["user"]["id"].int, photosCount = json["user"]["photos_count"].int, friendsCount = json["user"]["friends_count"].int, followersCount = json["user"]["followers_count"].int { self.userId = id let user = User(id: id, username: username, avatar: avatar) user.email = json["user"]["email"].string var city = "" var country = "" if let cityString = json["user"]["city"].string { city = cityString } if let countryString = json["user"]["country"].string { country = countryString } user.location = "\(city) \(country)" user.domain = json["user"]["domain"].string user.coverURL = json["user"]["cover_url"].string user.followersCount = followersCount user.friendsCount = friendsCount user.photosCount = photosCount if !self.isSelf && Account.checkIsLogin() { user.following = json["user"]["following"].bool! } self.updateUserInfo(user) } } } } func updateUserInfo(user: User) { if let coverUrl = user.coverURL { self.coverImageView.sd_setImageWithURL(NSURL(string: coverUrl), placeholderImage: UIImage(named: "ic_user_header")) } self.avatarImageView.sd_setImageWithURL(NSURL(string: user.avatar), placeholderImage: UIImage(named: "user_placeholder")) self.usernameLabel.text = user.username self.numberOfFollowersLabel.text = "\(user.followersCount!)" self.numberOfPhotosLabel.text = "\(user.photosCount!)" self.numberOfFriendsLabel.text = "\(user.friendsCount!)" if let email = user.email { self.birthdayLabel.text = email } if let location = user.location { self.locationLabel.text = location } if let domain = user.domain { self.domainLabel.text = domain } if !isSelf { if user.following { self.rightButton?.title = "Following" } else { self.rightButton?.title = "Follow" } } } func updateFollowStatus() { if !Account.checkIsLogin() { let alert = UIAlertController(title: nil, message: "未登录无法赞这张照片,现在去登录吗?", preferredStyle: UIAlertControllerStyle.Alert) let alertConfirm = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default) { alertConfirm in self.presentViewController(UINavigationController(rootViewController: AuthViewController()), animated: true, completion: nil) } let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel) { (cancle) -> Void in } alert.addAction(alertConfirm) alert.addAction(cancel) self.presentViewController(alert, animated: true, completion: nil) return } if self.rightButton?.title == "Follow" { Alamofire.request(Router.FollowUser(self.userId!)) .responseSwiftyJSON { response in self.rightButton?.title = "Following" } } else { Alamofire.request(Router.UnFollowUser(self.userId!)) .responseSwiftyJSON { response in self.rightButton?.title = "Follow" } } } // MARK: UIBarButtonItem func settings() { let settingsVC = UINavigationController(rootViewController: SettingViewController()) self.presentViewController(settingsVC, animated: true, completion: nil) } @IBAction func photoButtonTapped(sender: UIButton) { if let id = self.userId { let galleryVC = ImageCollectionViewController() galleryVC.requestType = 4 galleryVC.userId = id galleryVC.title = "Photos" galleryVC.parentNavigationController = self.navigationController self.navigationController?.pushViewController(galleryVC, animated: true) } } @IBAction func friendButtonTapped(sender: UIButton) { if let id = self.userId { let friendVC = FriendsViewController() friendVC.userId = id self.navigationController?.pushViewController(friendVC, animated: true) } } @IBAction func followerButtonTapped(sender: UIButton) { if let id = self.userId { let friendVC = FriendsViewController() friendVC.userId = id friendVC.requestType = 1 self.navigationController?.pushViewController(friendVC, animated: true) } } func userAvatarTapped() { let signInVC = AuthViewController() self.presentViewController(UINavigationController(rootViewController: signInVC), animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
649ac27eb550702c3ab338fdf3aea9e4
40.308333
303
0.567985
false
false
false
false
LKY769215561/KYHandMade
refs/heads/master
KYHandMade/Pods/DynamicColor/Sources/DynamicColor+RGBA.swift
apache-2.0
2
/* * DynamicColor * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.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. * */ #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(OSX) import AppKit #endif // MARK: RGBA Color Space public extension DynamicColor { /** Initializes and returns a color object using the specified opacity and RGB component values. Notes that values out of range are clipped. - Parameter r: The red component of the color object, specified as a value from 0.0 to 255.0. - Parameter g: The green component of the color object, specified as a value from 0.0 to 255.0. - Parameter b: The blue component of the color object, specified as a value from 0.0 to 255.0. - Parameter a: The opacity value of the color object, specified as a value from 0.0 to 255.0. The default value is 255. */ public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 255) { self.init(red: clip(r, 0, 255) / 255, green: clip(g, 0, 255) / 255, blue: clip(b, 0, 255) / 255, alpha: clip(a, 0, 255) / 255) } // MARK: - Getting the RGBA Components /** Returns the RGBA (red, green, blue, alpha) components. - returns: The RGBA components as a tuple (r, g, b, a). */ public final func toRGBAComponents() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 #if os(iOS) || os(tvOS) || os(watchOS) getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) #elseif os(OSX) if isEqual(DynamicColor.black) { return (0, 0, 0, 0) } else if isEqual(DynamicColor.white) { return (1, 1, 1, 1) } getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) #endif } #if os(iOS) || os(tvOS) || os(watchOS) /** The red component as CGFloat between 0.0 to 1.0. */ public final var redComponent: CGFloat { return toRGBAComponents().r } /** The green component as CGFloat between 0.0 to 1.0. */ public final var greenComponent: CGFloat { return toRGBAComponents().g } /** The blue component as CGFloat between 0.0 to 1.0. */ public final var blueComponent: CGFloat { return toRGBAComponents().b } /** The alpha component as CGFloat between 0.0 to 1.0. */ public final var alphaComponent: CGFloat { return toRGBAComponents().a } #endif // MARK: - Setting the RGBA Components /** Creates and returns a color object with the alpha increased by the given amount. - parameter amount: CGFloat between 0.0 and 1.0. - returns: A color object with its alpha channel modified. */ public final func adjustedAlpha(amount: CGFloat) -> DynamicColor { let components = toRGBAComponents() let normalizedAlpha = clip(components.a + amount, 0, 1) return DynamicColor(red: components.r, green: components.g, blue: components.b, alpha: normalizedAlpha) } }
0e1c3854a5155fda33715587110b3ead
31.967213
130
0.676778
false
false
false
false
cleexiang/CLRouter
refs/heads/master
CLRouter/ViewController3.swift
apache-2.0
1
// // ViewController3.swift // CLRouter // // Created by clee on 15/9/5. // Copyright © 2015年 cleexiang. All rights reserved. // import UIKit @objc(ViewController3) class ViewController3: UIViewController, CLRouteNodeProtocol { @IBOutlet weak var label1:UILabel? @IBOutlet weak var label2:UILabel? @IBOutlet weak var value1:UILabel? @IBOutlet weak var value2:UILabel? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.navigationItem.title = "VC3" self.value1?.text = param1 self.value2?.text = param2 } var param1:String? var param2:String? override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } static func customerController() -> UIViewController { let sb:UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let vc = sb.instantiateViewControllerWithIdentifier("ViewController3") return vc } }
729d1685aaf87e8c99e2055b8044e4fd
24.785714
87
0.67867
false
false
false
false
gguuss/gplus-ios-swift
refs/heads/master
basic-signin/swiftsignin/ViewController.swift
apache-2.0
1
// // ViewController.swift // swiftsignin // // Created by Gus Class on 12/12/14. // // 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 class ViewController: UIViewController, GPPSignInDelegate { var kClientId = "REPLACE_CLIENT_ID"; // Get this from https://console.developers.google.com @IBOutlet weak var toggleFetchEmail: UISwitch! @IBOutlet weak var toggleFetchUserID: UISwitch! @IBOutlet weak var signinButton: UIButton! @IBOutlet weak var signOutButton: UIButton! @IBOutlet weak var disconnectButton: UIButton! @IBOutlet weak var emailDataField: UITextView! @IBOutlet weak var userData: UITextView! override func viewDidLoad() { super.viewDidLoad(); // Configure the sign in object. var signIn = GPPSignIn.sharedInstance(); signIn.shouldFetchGooglePlusUser = true; signIn.clientID = kClientId; signIn.shouldFetchGoogleUserEmail = toggleFetchEmail.on; signIn.shouldFetchGoogleUserID = toggleFetchUserID.on; signIn.scopes = [kGTLAuthScopePlusLogin]; signIn.trySilentAuthentication(); signIn.delegate = self; // Update the buttons and text. updateUI(); } @IBAction func signInClicked(sender: AnyObject) { var signIn = GPPSignIn.sharedInstance(); signIn.authenticate(); } func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) { updateUI(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func toggleFetchEmailClick(sender: AnyObject) { GPPSignIn.sharedInstance().shouldFetchGoogleUserEmail = toggleFetchEmail.on; } @IBAction func toggleUserId(sender: AnyObject) { GPPSignIn.sharedInstance().shouldFetchGoogleUserID = toggleFetchUserID.on; } @IBAction func disconnect(sender: AnyObject) { GPPSignIn.sharedInstance().disconnect(); updateUI(); } @IBAction func signOut(sender: AnyObject) { GPPSignIn.sharedInstance().signOut(); updateUI(); } func updateUI() { // TODO: Toggle buttons here. if (GPPSignIn.sharedInstance().userID != nil){ // Signed in? var user = GPPSignIn.sharedInstance().googlePlusUser; userData.text = user.name.JSONString(); if (user.emails != nil){ emailDataField.text = user.emails.first?.JSONString() ?? "no email"; } else { emailDataField.text = "no email"; } signOutButton.enabled = true; disconnectButton.enabled = true; signinButton.enabled = true; } else { userData.text = "Signed out."; emailDataField.text = "Signed out."; signOutButton.enabled = false; disconnectButton.enabled = false; signinButton.enabled = true; } } }
089789594be640f27317d15b1b4ade82
28.534483
95
0.671337
false
false
false
false
blitzagency/events
refs/heads/master
Events/Models/Event.swift
mit
1
// // Event.swift // Events // // Created by Adam Venturella on 12/2/15. // Copyright © 2015 BLITZ. All rights reserved. // import Foundation public protocol Event{ var name: String { get } } public protocol PublisherAssociated{ associatedtype Publisher var publisher: Publisher { get } } public protocol DataAssociated{ associatedtype Data var data: Data { get } } public struct EventPublisher<Publisher>: Event, PublisherAssociated{ public let name: String public let publisher: Publisher public init(name: String, publisher: Publisher){ self.name = name self.publisher = publisher } } public struct EventPublisherData<Publisher, Data>: Event, PublisherAssociated, DataAssociated{ public let name: String public let publisher: Publisher public let data: Data public init(name: String, publisher: Publisher, data: Data){ self.name = name self.publisher = publisher self.data = data } }
d31055e20a88c8b2a9262f63303bf159
18.346154
94
0.680915
false
false
false
false
JaSpa/swift
refs/heads/master
test/Constraints/bridging.swift
apache-2.0
6
// RUN: %target-swift-frontend -typecheck -verify %s // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a non-whitelisted type from another module. extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterIterator { let result: LazyFilterIterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { var hashValue: Int { return 0 } func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { var hashValue: Int { return 0 } } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { var hashValue: Int { return 0 } } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' does not conform to 'AnyObject'}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt as Any] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // FIXME: Another awful diagnostic. return d == d // expected-error{{binary operator '==' cannot be applied to two 'Dictionary<Int, NotEquatable>' operands}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 var inferDouble2 = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: Use truncatingRemainder instead}} let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T: Hashable>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K: Hashable, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[Any]'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} // FIXME: there should be a fixit appending "as String?" to the line; for now // it's sufficient that it doesn't suggest appending "as String" // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{cannot convert value of type 'NSString?' to expected argument type 'String?'}} var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}} var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{20-20=(}}{{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } func rdar28856049(_ nsma: NSMutableArray) { _ = nsma as? [BridgedClass] _ = nsma as? [BridgedStruct] _ = nsma as? [BridgedClassSub] } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{11-11= as String}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass!' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}{{13-13= as BridgedStruct}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{does not conform to 'AnyObject'}} z = b z = c // expected-error{{does not conform to 'AnyObject'}} z = d // expected-error{{does not conform to 'AnyObject'}} z = e z = f z = g z = h // expected-error{{does not conform to 'AnyObject'}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y }
62d5ab80da682c54a7cff8d3ca3c5900
46.303279
305
0.694218
false
false
false
false
luzefeng/SwiftTask
refs/heads/swift/2.0
SwiftTaskTests/AlamofireTests.swift
mit
3
// // AlamofireTests.swift // SwiftTaskTests // // Created by Yasuhiro Inami on 2014/08/21. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import SwiftTask import Alamofire import XCTest class AlamofireTests: _TestCase { typealias Progress = (bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) func testFulfill() { let expect = self.expectationWithDescription(__FUNCTION__) let task = Task<Progress, String, NSError> { progress, fulfill, reject, configure in request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") } return } task.success { (value: String) -> Void in XCTAssertEqual(value, "OK") expect.fulfill() } self.wait() } func testReject() { let expect = self.expectationWithDescription(__FUNCTION__) let task = Task<Progress, String?, NSError> { progress, fulfill, reject, configure in let dummyURLString = "http://xxx-swift-task.org/get" request(.GET, dummyURLString, parameters: ["foo": "bar"]) .response { (request, response, data, error) in if let error = error { reject(error) // pass non-nil error return } if response?.statusCode >= 300 { reject(NSError(domain: "", code: 0, userInfo: nil)) } fulfill("OK") } } task.success { (value: String?) -> Void in XCTFail("Should never reach here.") }.failure { (error: NSError?, isCancelled: Bool) -> Void in XCTAssertTrue(error != nil, "Should receive non-nil error.") expect.fulfill() } self.wait() } func testProgress() { let expect = self.expectationWithDescription(__FUNCTION__) // define task let task = Task<Progress, String, NSError> { progress, fulfill, reject, configure in download(.GET, "http://httpbin.org/stream/100", destination: Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)) .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in progress((bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) as Progress) }.response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") // return nil anyway } return } // set progress & then task.progress { _, progress in print("bytesWritten = \(progress.bytesWritten)") print("totalBytesWritten = \(progress.totalBytesWritten)") print("totalBytesExpectedToWrite = \(progress.totalBytesExpectedToWrite)") print("") }.then { value, errorInfo -> Void in expect.fulfill() } self.wait() } func testNSProgress() { let expect = self.expectationWithDescription(__FUNCTION__) let nsProgress = NSProgress(totalUnitCount: 100) // define task let task = Task<Progress, String, NSError> { progress, fulfill, reject, configure in nsProgress.becomeCurrentWithPendingUnitCount(50) // NOTE: test with url which returns totalBytesExpectedToWrite != -1 download(.GET, "http://httpbin.org/bytes/1024", destination: Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)) .response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") // return nil anyway } nsProgress.resignCurrent() } task.then { value, errorInfo -> Void in XCTAssertTrue(nsProgress.completedUnitCount == 50) expect.fulfill() } self.wait() } // // NOTE: temporarily ignored Alamofire-cancelling test due to NSURLSessionDownloadTaskResumeData issue. // // Error log: // Property list invalid for format: 100 (property lists cannot contain NULL) // Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: NSURLSessionDownloadTaskResumeData)' // // Ref: // nsurlsession - (NSURLSessionDownloadTask cancelByProducingResumeData) crashes nsnetwork daemon iOS 7.0 - Stack Overflow // http://stackoverflow.com/questions/25297750/nsurlsessiondownloadtask-cancelbyproducingresumedata-crashes-nsnetwork-daemon // func testCancel() { let expect = self.expectationWithDescription(__FUNCTION__) let task = Task<Progress, String?, NSError> { progress, fulfill, reject, configure in let downloadRequst = download(.GET, "http://httpbin.org/stream/100", destination: Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)) .response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") } // configure cancel for cleanup after reject or task.cancel() // NOTE: use weak to let task NOT CAPTURE downloadRequst via configure configure.cancel = { [weak downloadRequst] in if let downloadRequst = downloadRequst { downloadRequst.cancel() } } } // end of 1st task definition (NOTE: don't chain with `then` or `failure` for 1st task cancellation) task.success { (value: String?) -> Void in XCTFail("Should never reach here because task is cancelled.") }.failure { (error: NSError?, isCancelled: Bool) -> Void in XCTAssertTrue(error == nil, "Should receive nil error via task.cancel().") XCTAssertTrue(isCancelled) expect.fulfill() } // cancel after 1ms dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1_000_000), dispatch_get_main_queue()) { task.cancel() // sends no error XCTAssertEqual(task.state, TaskState.Cancelled) } self.wait() } // TODO: func __testPauseResume() { } }
0de4ecaaf764cdf3c5f26cd9eacee8cb
31.644068
187
0.511293
false
true
false
false
sodascourse/swift-introduction
refs/heads/master
Swift-Introduction.playground/Pages/Struct and Class.xcplaygroundpage/Contents.swift
apache-2.0
1
/*: # Struct and Class */ /*: ## Struct ### Point example */ struct Point { let x: Double let y: Double static let origin = Point(x: 0, y: 0) func distance(to another: Point) -> Double { let deltaX = self.x - another.x let deltaY = self.y - another.y return (deltaX*deltaX + deltaY*deltaY).squareRoot() } var distanceToOrigin: Double { return self.distance(to: Point.origin) } } let point1 = Point(x: 3, y: 4) let point2 = Point(x: 15, y: 9) let origin = Point.origin point1.distanceToOrigin point1.distance(to: point2) /*: ### Tour example */ struct Tour { var origin: String var destination: String } let tour1 = Tour(origin: "Taipei", destination: "Tokyo") //tour1.destination = "Osaka" // Try to uncomment above line to see what Xcode yields. var tour2 = Tour(origin: "Tokyo", destination: "San Francisco") tour2.destination = "Sapporo" /*: ### Back Account example */ struct BankAccount { var deposit: Int { willSet { print(">>> Deposit value will change from \(self.deposit) to \(newValue).") } didSet { print(">>> Deposit value did change from \(oldValue) to \(self.deposit).") } } } var account = BankAccount(deposit: 1000) account.deposit += 10 /*: ### Rectangle example */ struct Rect { struct Point { var x, y: Double } struct Size { var width, height: Double mutating func scale(by times: Double) { self.width *= times self.height *= times } } var origin: Point, size: Size var center: Point { get { return Point(x: self.origin.x + self.size.width/2, y: self.origin.y + self.size.height/2) } set(newCenter) { self.origin.x = newCenter.x - self.size.width/2 self.origin.y = newCenter.y - self.size.height/2 } } mutating func move(toX x: Double, y: Double) { self.origin.x = x self.origin.y = y } mutating func scaleSize(by times: Double) { self.size.scale(by: times) } } var rect = Rect(origin: Rect.Point(x: 5, y: 5), size: Rect.Size(width: 20, height: 40)) rect.origin rect.center rect.center = Rect.Point(x: 40, y: 40) rect.origin /*: ### Book example */ import Foundation struct Book { var title: String let author: String var price = 10.0 let publishDate = Date() init(title: String, author: String, price: Double) { self.title = title self.author = author self.price = price } init(title: String, author: String) { self.init(title: title, author: author, price: 10.0) } } let book1 = Book(title: "Harry Potter 1", author: "J.K. Rowling") let book2 = Book(title: "Harry Potter 2", author: "J.K. Rowling") book1.publishDate == book2.publishDate /*: ### Fraction and Complex example */ struct Fraction { var numerator: Int var denominator: Int init?(numerator: Int, denominator: Int) { guard denominator != 0 else { return nil } self.numerator = numerator self.denominator = denominator } init(_ integer: Int) { self.init(numerator: integer, denominator: 1)! } } let half = Fraction(numerator: 1, denominator: 2) let nilFraction = Fraction(numerator: 2, denominator: 0) struct Complex { var real: Double var imaginary: Double var isReal: Bool { return self.imaginary == 0 } } let someComplexNumber = Complex(real: 1, imaginary: 2) // 1+2i /*: ### Audio channel example */ struct AudioChannel { static let thresholdLevel = 10 // Use as constants static var maxLevelOfAllChannels = 0 // Use as shared variables var currentLevel: Int = 0 { didSet { if (self.currentLevel > AudioChannel.thresholdLevel) { self.currentLevel = AudioChannel.thresholdLevel } if (self.currentLevel > AudioChannel.maxLevelOfAllChannels) { AudioChannel.maxLevelOfAllChannels = self.currentLevel } } } } //: -------------------------------------------------------------------------------------------------------------------- /*: ## Class ### Animal example */ class Animal { var name: String? func makeNoise() {} init(name: String) { self.name = name } } class Cat: Animal { override func makeNoise() { print("meow~") } } class Dog: Animal { override func makeNoise() { print("wof!") } } let kitty = Cat(name: "Kitty") let puppy = Dog(name: "Puppy") print("\n\n---") kitty.makeNoise() // meow~ kitty.name // Kitty puppy.makeNoise() // wof! /*: ### View example */ struct Frame { var x, y, width, height: Double } class View { var frame: Frame init(frame: Frame) { self.frame = frame } func draw() { print("Start to draw a view at (x=\(self.frame.x), y=\(self.frame.y)).") print("The size of this view is \(self.frame.width)*\(self.frame.height).") } } class BorderedView: View { override func draw() { super.draw() print("Draw a stroke for this view.") } } print("\n\n---") let borderedView = BorderedView(frame: Frame(x: 10.0, y: 10.0, width: 200.0, height: 300.0)) borderedView.draw() /*: ### Student example */ class Person { var name: String init(name: String) { self.name = name } static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name } } class Student: Person { var school: String var department: String? init(name: String, school: String, department: String?) { self.school = school self.department = department super.init(name: name) } convenience init(name: String, school: String) { self.init(name: name, school: school, department: nil) } } /*: ### Reference example */ let person1 = Person(name: "Peter") let person2 = person1 let person3 = Person(name: "Peter") person1 == person2 person1 == person3 person1 === person2 // Check identity: Memory block person1 === person3 // Check identity: Memory block person1.name = "Annie" person2.name // Also changed, because `person1` and `person2` are the same memory block. person3.name // Still "Peter". var fraction1 = Fraction(numerator: 1, denominator: 2)! var fraction2 = fraction1 fraction1.denominator = 3 fraction2.denominator // Still 2, because Fraction is a struct, value type. //: -------------------------------------------------------------------------------------------------------------------- //: # Advanced Example //: -------------------------------------------------------------------------------------------------------------------- class LinkedListNode<Element> { // LinkedList should be reference based ... use `class` // And in Swift, we ususally use `Element` as name for generic type of content // Optional is actually made by enum, `cmd+click` on `.none` to see it var nextNode: LinkedListNode? = .none var content: Element init(content: Element) { self.content = content } var isLastNode: Bool { return self.nextNode == nil } var lastNode: LinkedListNode { var lastNode = self while !lastNode.isLastNode { lastNode = lastNode.nextNode! } return lastNode } func toArray() -> [Element] { var result = [Element]() var node: LinkedListNode<Element>? = self repeat { result.append(node!.content) node = node!.nextNode } while node != nil return result } // Override operators static func +=(left: inout LinkedListNode, right: LinkedListNode) { left.lastNode.nextNode = right } // `subscript` is the method of `[]` operator subscript(steps: Int) -> LinkedListNode? { guard steps >= 0 else { print("Steps should equals to or be greater than 0") return nil } var resultNode: LinkedListNode? = self for _ in 0..<steps { resultNode = resultNode?.nextNode } return resultNode } subscript(indexes: Int...) -> [Element?] { var result = [Element?]() for index in indexes { result.append(self[index]?.content) } return result } // A static func is usually used as factory. static func createLinkedList(items: Element...) -> LinkedListNode<Element>? { guard !items.isEmpty else { return nil } let resultNode = LinkedListNode(content: items.first!) var lastNode = resultNode for item in items[1..<items.count] { lastNode.nextNode = LinkedListNode(content: item) lastNode = lastNode.nextNode! // Step forward } return resultNode } } var linkedList1 = LinkedListNode.createLinkedList(items: 1, 2, 3, 4)! linkedList1[0]?.content linkedList1[1]?.content linkedList1[2]?.content linkedList1[3]?.content linkedList1[4]?.content linkedList1[0]!.isLastNode linkedList1.lastNode.isLastNode linkedList1.lastNode.content linkedList1[0, 1, 5] linkedList1.toArray() let linkedList2 = LinkedListNode.createLinkedList(items: 5, 6, 7)! linkedList1 += linkedList2 linkedList1.toArray() //: --- //: //: [<- Previous](@previous) | [Next ->](@next) //:
e80f56ae8176c8407ed058622843b9d0
22.704261
120
0.582364
false
false
false
false
samodom/TestableUIKit
refs/heads/master
TestableUIKit/UIResponder/UIView/UITableView/UITableViewInsertSectionsSpy.swift
mit
1
// // UITableViewInsertSectionsSpy.swift // TestableUIKit // // Created by Sam Odom on 2/21/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import UIKit import TestSwagger import FoundationSwagger public extension UITableView { private static let insertSectionsCalledKeyString = UUIDKeyString() private static let insertSectionsCalledKey = ObjectAssociationKey(insertSectionsCalledKeyString) private static let insertSectionsCalledReference = SpyEvidenceReference(key: insertSectionsCalledKey) private static let insertSectionsSectionsKeyString = UUIDKeyString() private static let insertSectionsSectionsKey = ObjectAssociationKey(insertSectionsSectionsKeyString) private static let insertSectionsSectionsReference = SpyEvidenceReference(key: insertSectionsSectionsKey) private static let insertSectionsAnimationKeyString = UUIDKeyString() private static let insertSectionsAnimationKey = ObjectAssociationKey(insertSectionsAnimationKeyString) private static let insertSectionsAnimationReference = SpyEvidenceReference(key: insertSectionsAnimationKey) private static let insertSectionsCoselectors = SpyCoselectors( methodType: .instance, original: #selector(UITableView.insertSections(_:with:)), spy: #selector(UITableView.spy_insertSections(_:with:)) ) /// Spy controller for ensuring that a table view has had `insertSections(_:with:)` called on it. public enum InsertSectionsSpyController: SpyController { public static let rootSpyableClass: AnyClass = UITableView.self public static let vector = SpyVector.direct public static let coselectors: Set = [insertSectionsCoselectors] public static let evidence: Set = [ insertSectionsCalledReference, insertSectionsSectionsReference, insertSectionsAnimationReference ] public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `insertSections(_:with:)` dynamic public func spy_insertSections( _ sections: IndexSet, with animation: UITableViewRowAnimation ) { insertSectionsCalled = true insertSectionsSections = sections insertSectionsAnimation = animation spy_insertSections(sections, with: animation) } /// Indicates whether the `insertSections(_:with:)` method has been called on this object. public final var insertSectionsCalled: Bool { get { return loadEvidence(with: UITableView.insertSectionsCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: UITableView.insertSectionsCalledReference) } } /// Provides the sections passed to `insertSections(_:with:)` if called. public final var insertSectionsSections: IndexSet? { get { return loadEvidence(with: UITableView.insertSectionsSectionsReference) as? IndexSet } set { let reference = UITableView.insertSectionsSectionsReference guard let sections = newValue else { return removeEvidence(with: reference) } saveEvidence(sections, with: reference) } } /// Provides the animation type passed to `insertSections(_:with:)` if called. public final var insertSectionsAnimation: UITableViewRowAnimation? { get { return loadEvidence(with: UITableView.insertSectionsAnimationReference) as? UITableViewRowAnimation } set { let reference = UITableView.insertSectionsAnimationReference guard let animation = newValue else { return removeEvidence(with: reference) } saveEvidence(animation, with: reference) } } }
c582d20ba490027957e591d700083ca4
33.919643
111
0.694707
false
false
false
false
VladiMihaylenko/omim
refs/heads/master
iphone/Maps/Classes/CarPlay/Template Builders/SettingsTemplateBuilder.swift
apache-2.0
1
import CarPlay @available(iOS 12.0, *) final class SettingsTemplateBuilder { // MARK: - CPGridTemplate builder class func buildGridTemplate() -> CPGridTemplate { let actions = SettingsTemplateBuilder.buildGridButtons() let gridTemplate = CPGridTemplate(title: L("settings"), gridButtons: actions) return gridTemplate } private class func buildGridButtons() -> [CPGridButton] { let options = RoutingOptions() return [createUnpavedButton(options: options), createTollButton(options: options), createFerryButton(options: options), createTrafficButton(), createSpeedcamButton()] } // MARK: - CPGridButton builders private class func createTollButton(options: RoutingOptions) -> CPGridButton { var tollIconName = "ic_carplay_toll" if options.avoidToll { tollIconName += "_active" } let tollButton = CPGridButton(titleVariants: [L("avoid_tolls")], image: UIImage(named: tollIconName)!) { _ in options.avoidToll = !options.avoidToll options.save() CarPlayService.shared.updateRouteAfterChangingSettings() CarPlayService.shared.popTemplate(animated: true) } return tollButton } private class func createUnpavedButton(options: RoutingOptions) -> CPGridButton { var unpavedIconName = "ic_carplay_unpaved" if options.avoidDirty { unpavedIconName += "_active" } let unpavedButton = CPGridButton(titleVariants: [L("avoid_unpaved")], image: UIImage(named: unpavedIconName)!) { _ in options.avoidDirty = !options.avoidDirty options.save() CarPlayService.shared.updateRouteAfterChangingSettings() CarPlayService.shared.popTemplate(animated: true) } return unpavedButton } private class func createFerryButton(options: RoutingOptions) -> CPGridButton { var ferryIconName = "ic_carplay_ferry" if options.avoidFerry { ferryIconName += "_active" } let ferryButton = CPGridButton(titleVariants: [L("avoid_ferry")], image: UIImage(named: ferryIconName)!) { _ in options.avoidFerry = !options.avoidFerry options.save() CarPlayService.shared.updateRouteAfterChangingSettings() CarPlayService.shared.popTemplate(animated: true) } return ferryButton } private class func createTrafficButton() -> CPGridButton { var trafficIconName = "ic_carplay_trafficlight" let isTrafficEnabled = MWMTrafficManager.trafficEnabled() if isTrafficEnabled { trafficIconName += "_active" } let trafficButton = CPGridButton(titleVariants: [L("button_layer_traffic")], image: UIImage(named: trafficIconName)!) { _ in MWMTrafficManager.setTrafficEnabled(!isTrafficEnabled) CarPlayService.shared.popTemplate(animated: true) } return trafficButton } private class func createSpeedcamButton() -> CPGridButton { var speedcamIconName = "ic_carplay_speedcam" let isSpeedCamActivated = CarPlayService.shared.isSpeedCamActivated if isSpeedCamActivated { speedcamIconName += "_active" } let speedButton = CPGridButton(titleVariants: [L("speedcams_alert_title")], image: UIImage(named: speedcamIconName)!) { _ in CarPlayService.shared.isSpeedCamActivated = !isSpeedCamActivated CarPlayService.shared.popTemplate(animated: true) } return speedButton } }
9eb889bde80282fadba064c9be415515
45.860465
100
0.5933
false
false
false
false
niunaruto/DeDaoAppSwift
refs/heads/master
DeDaoSwift/DeDaoSwift/Home/View/DDHomeFreeAudioCell.swift
mit
1
// // DDHomeFreeAudioCell.swift // DeDaoSwift // // Created by niuting on 2017/3/13. // Copyright © 2017年 niuNaruto. All rights reserved. // import UIKit class DDHomeFreeAudioCell: DDBaseTableViewCell { override func setCellsViewModel(_ model: Any?) { if let modelT = model as? DDHomeFreeAudioModel { guard modelT.list?.count ?? 0 >= 4 && labelArray.count >= 4 else { return } if let list = modelT.list{ for i in 0...(list.count - 1) { let indef = "▶ " let cont = list[i].title labelArray[i].attributedText = DDTool.setLabelAttributedString(indef, cont, UIColor.init("#999999"), UIColor.init("#666666"), UIFont.systemFont(ofSize: 8), UIFont.systemFont(ofSize: 13)) } } } } let playBtnW : CGFloat = 100 lazy var playButton : UIButton = { let playButton = UIButton() playButton.setImage(UIImage.init(named: "new_main_audio_play_icon"), for: .normal) return playButton }() lazy var labelArray = Array<UILabel> () override func setUI() { contentView.addSubview(playButton) for i in 0...4 { let contentLable = UILabel() let height : CGFloat = 14 let starY : CGFloat = 18 contentLable.frame = CGRect(x: 10, y: starY + CGFloat(i) * height + CGFloat(10 * i), width: UIView.screenWidth - playBtnW , height: height) contentLable.font = UIFont.systemFont(ofSize: 13) contentLable.textColor = UIColor.init("#666666") contentView.addSubview(contentLable) labelArray.append(contentLable) } } override func setLayout() { playButton.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-20) make.bottom.equalToSuperview().offset(-30) } } }
f584d57a1ed0f5d8185b3e3f5976c3eb
26.463415
206
0.513321
false
false
false
false
cpuu/OTT
refs/heads/master
OTT/Utils/BeaconStore.swift
mit
1
// // BeaconStore.swift // BlueCap // // Created by Troy Stribling on 9/16/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation import BlueCapKit class BeaconStore { class func getBeacons() -> [String: NSUUID] { if let storedBeacons = NSUserDefaults.standardUserDefaults().dictionaryForKey("beacons") { var beacons = [String: NSUUID]() for (name, uuid) in storedBeacons { if let uuid = uuid as? String { beacons[name] = NSUUID(UUIDString: uuid) } } return beacons } else { return [:] } } class func setBeacons(beacons: [String: NSUUID]) { var storedBeacons = [String: String]() for (name, uuid) in beacons { storedBeacons[name] = uuid.UUIDString } NSUserDefaults.standardUserDefaults().setObject(storedBeacons, forKey: "beacons") } class func getBeaconNames() -> [String] { return Array(self.getBeacons().keys) } class func addBeacon(name: String, uuid: NSUUID) { var beacons = self.getBeacons() beacons[name] = uuid self.setBeacons(beacons) } class func removeBeacon(name: String) { var beacons = self.getBeacons() beacons.removeValueForKey(name) self.setBeacons(beacons) } }
3bbaa75393c2eaea8a7f0dff23e747ea
26.705882
98
0.57932
false
false
false
false
xmartlabs/Swift-Project-Template
refs/heads/master
Project-iOS/XLProjectName/XLProjectName/Helpers/Extensions/AppDelegate+XLProjectName.swift
mit
1
// // AppDelegate+XLProjectName.swift // XLProjectName // // Created by XLAuthorName ( XLAuthorWebsite ) // Copyright © 2016 'XLOrganizationName'. All rights reserved. // import Foundation import Fabric import Alamofire import Eureka import Crashlytics extension AppDelegate { func setupCrashlytics() { Fabric.with([Crashlytics.self]) Fabric.sharedSDK().debug = Constants.Debug.crashlytics } // MARK: Alamofire notifications func setupNetworking() { NotificationCenter.default.addObserver( self, selector: #selector(AppDelegate.requestDidComplete(_:)), name: Alamofire.Request.didCompleteTaskNotification, object: nil) } @objc func requestDidComplete(_ notification: Notification) { guard let request = notification.request, let response = request.response else { DEBUGLog("Request object not a task") return } if Constants.Network.successRange ~= response.statusCode { if let token = response.allHeaderFields["Set-Cookie"] as? String { SessionController.sharedInstance.token = token } } else if response.statusCode == Constants.Network.Unauthorized && SessionController.sharedInstance.isLoggedIn() { SessionController.sharedInstance.clearSession() // here you should implement AutoLogout: Transition to login screen and show an appropiate message } } /** Set up your Eureka default row customization here */ func stylizeEurekaRows() { let genericHorizontalMargin = CGFloat(50) BaseRow.estimatedRowHeight = 58 EmailRow.defaultRowInitializer = { $0.placeholder = NSLocalizedString("E-mail Address", comment: "") $0.placeholderColor = .gray } EmailRow.defaultCellSetup = { cell, _ in cell.layoutMargins = .zero cell.contentView.layoutMargins.left = genericHorizontalMargin cell.height = { 58 } } } }
ffa4aac88ebd8b42b5cb08495807e54c
30.846154
122
0.647343
false
false
false
false
gregomni/swift
refs/heads/main
test/Sanitizers/tsan/racy_async_let_fibonacci.swift
apache-2.0
2
// RUN: %target-swiftc_driver %s -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch -target %sanitizers-target-triple -g -sanitize=thread -o %t // RUN: %target-codesign %t // RUN: env %env-TSAN_OPTIONS="abort_on_error=0" not %target-run %t 2>&1 | %swift-demangle --simplified | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // REQUIRES: tsan_runtime // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime // rdar://75365575 (Failing to start atos external symbolizer) // UNSUPPORTED: OS=watchos // rdar://86825277 // SR-15805 // UNSUPPORTED: CPU=arm64 || CPU=arm64e // Disabled because this test is flaky rdar://76542113 // REQUIRES: rdar76542113 func fib(_ n: Int) -> Int { var first = 0 var second = 1 for _ in 0..<n { let temp = first first = second second = temp + first } return first } var racyCounter = 0 @available(SwiftStdlib 5.1, *) func asyncFib(_ n: Int) async -> Int { racyCounter += 1 if n == 0 || n == 1 { return n } async let first = await asyncFib(n-2) async let second = await asyncFib(n-1) // Sleep a random amount of time waiting on the result producing a result. await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000) let result = await first + second // Sleep a random amount of time before producing a result. await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000) return result } @available(SwiftStdlib 5.1, *) func runFibonacci(_ n: Int) async { let result = await asyncFib(n) print() print("Async fib = \(result), sequential fib = \(fib(n))") assert(result == fib(n)) } @available(SwiftStdlib 5.1, *) @main struct Main { static func main() async { await runFibonacci(10) } } // CHECK: ThreadSanitizer: Swift access race // CHECK: Location is global 'racyCounter'
f5a632d393bffd0fba8ea202e363d18f
24.16
172
0.677266
false
false
false
false
terflogag/GBHFacebookImagePicker
refs/heads/master
GBHFacebookImagePicker/Classes/Utils/UICollectionView+Extensions.swift
mit
1
// // UICollectionView+Extensions.swift // Bolts // // Created by Florian Gabach on 11/05/2018. // import UIKit extension UICollectionView { func selectAllCell(toPosition position: UICollectionView.ScrollPosition = []) { for section in 0..<self.numberOfSections { for item in 0..<self.numberOfItems(inSection: section) { let index = IndexPath(row: item, section: section) self.selectItem(at: index, animated: false, scrollPosition: position) } } } func register<T: UICollectionViewCell>(cellType: T.Type) where T: Reusable { self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier) } func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T where T: Reusable { let bareCell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath) guard let cell = bareCell as? T else { fatalError( "Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). " + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + "and that you registered the cell beforehand" ) } return cell } }
cdad696e8f8ad907d6e20bd142d96aee
36.447368
123
0.619817
false
false
false
false
jeffreybergier/Hipstapaper
refs/heads/main
Hipstapaper/Packages/V3Errors/Sources/V3Errors/Errors/DeleteError+CodableError.swift
mit
1
// // Created by Jeffrey Bergier on 2022/06/29. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import Umbrella import V3Model // MARK: DeleteTagError extension DeleteTagError { internal init?(_ error: CodableError, onConfirm: OnConfirmation?) { guard error.errorDomain == type(of: self).errorDomain, error.errorCode == self.errorCode, let data = error.arbitraryData, let identifiers = try? PropertyListDecoder().decode(Tag.Selection.self, from: data) else { return nil } self.identifiers = identifiers self.onConfirm = onConfirm } public var codableValue: CodableError { var error = CodableError(self) error.arbitraryData = try? PropertyListEncoder().encode(self.identifiers) return error } } // MARK: DeleteWebsiteError extension DeleteWebsiteError { internal init?(_ error: CodableError, onConfirm: OnConfirmation?) { guard error.errorDomain == type(of: self).errorDomain, error.errorCode == self.errorCode, let data = error.arbitraryData, let identifiers = try? PropertyListDecoder().decode(Website.Selection.self, from: data) else { return nil } self.identifiers = identifiers self.onConfirm = onConfirm } public var codableValue: CodableError { var error = CodableError(self) error.arbitraryData = try? PropertyListEncoder().encode(self.identifiers) return error } }
7b0ccafb73de6a3668ef4039d5b27ba6
36.366197
99
0.692801
false
false
false
false
kingka/SwiftWeiBo
refs/heads/master
SwiftWeiBo/SwiftWeiBo/Classes/Main/BaseViewController.swift
mit
1
// // BaseViewController.swift // SwiftWeiBo // // Created by Imanol on 16/1/13. // Copyright © 2016年 imanol. All rights reserved. // import UIKit class BaseViewController: UITableViewController ,VisitViewDelegate{ let isLogin:Bool = UserAccount.userLogin() var visitView:VisitView? override func loadView() { isLogin ? super.loadView() : setupCustomView() } func setupCustomView(){ //初始化visitView visitView = VisitView() visitView?.delegate = self view = visitView // 添加 导航按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "registerDidClick") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "loginDidClick") } func registerDidClick() { print(__FUNCTION__) print(UserAccount.loadAccount()) } func loginDidClick() { print(__FUNCTION__) let oauthVC = OAuthViewController() let nav = UINavigationController(rootViewController: oauthVC) presentViewController(nav, animated: true) { () -> Void in } } }
ec72dc28349f7de0342efa1bd0143767
26.282609
148
0.641434
false
false
false
false
JGiola/swift
refs/heads/main
test/Generics/rdar80503090.swift
apache-2.0
6
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s protocol P { associatedtype T where T == Self } protocol Q : P {} extension P { func missing() {} } extension P where T : Q { // CHECK-LABEL: Generic signature: <Self where Self : Q> func test() { missing() } } class C : P {} // expected-warning@-1 {{non-final class 'C' cannot safely conform to protocol 'P', which requires that 'Self.T' is exactly equal to 'Self'; this is an error in Swift 6}} extension P where T : C { // CHECK-LABEL: Generic signature: <Self where Self : C> func test() { missing() } } struct S : P {} extension P where T == S { // CHECK-LABEL: Generic signature: <Self where Self == S> func test() { missing() } }
403b7c9a25a251c955746dbaad9fc463
23.410256
170
0.656151
false
true
false
false
filipealva/WWDC15-Scholarship
refs/heads/master
Filipe Alvarenga/Model/Story.swift
mit
1
// // Story.swift // Filipe Alvarenga // // Created by Filipe Alvarenga on 19/04/15. // Copyright (c) 2015 Filipe Alvarenga. All rights reserved. // import Foundation /** Story model class. - parameter title: The story title. - parameter description: The story description. */ class Story { var title: String! var description: String! var date: String! init(dict: [String: AnyObject]) { self.title = dict["title"] as? String ?? "No title" self.description = dict["description"] as? String ?? "No description" if let date = dict["date"] as? String { self.date = date } else { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMMM yyyy" self.date = dateFormatter.stringFromDate(NSDate()).capitalizedString } } }
2c44f764f9aa08c0e991c1927d610910
22.891892
80
0.594564
false
false
false
false
materik/iapcontroller
refs/heads/master
Swift/IAPController.swift
mit
1
// // IAPController.swift // XWorkout // // Created by materik on 19/07/15. // Copyright (c) 2015 materik. All rights reserved. // import Foundation import StoreKit public let IAPControllerFetchedNotification = "IAPControllerFetchedNotification" public let IAPControllerPurchasedNotification = "IAPControllerPurchasedNotification" public let IAPControllerFailedNotification = "IAPControllerFailedNotification" public let IAPControllerRestoredNotification = "IAPControllerRestoredNotification" open class IAPController: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver { // MARK: Properties open var products: [SKProduct]? var productIds: [String] = [] // MARK: Singleton open static var sharedInstance: IAPController = { return IAPController() }() // MARK: Init public override init() { super.init() self.retrieveProductIdsFromPlist() SKPaymentQueue.default().add(self) } private func retrieveProductIdsFromPlist() { let url = Bundle.main.url(forResource: "IAPControllerProductIds", withExtension: "plist")! self.productIds = NSArray(contentsOf: url) as! [String] } // MARK: Action open func fetchProducts() { let request = SKProductsRequest(productIdentifiers: Set(self.productIds)) request.delegate = self request.start() } open func restore() { SKPaymentQueue.default().restoreCompletedTransactions() } // MARK: SKPaymentTransactionObserver open func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { self.products = response.products NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerFetchedNotification), object: nil) } open func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .purchased: self.purchasedTransaction(transaction: transaction) break case .failed: self.failedTransaction(transaction: transaction) break case .restored: self.restoreTransaction(transaction: transaction) break default: break } } } open func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { self.failedTransaction(transaction: nil, error: error) } open func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerRestoredNotification), object: nil) } // MARK: Transaction func finishTransaction(transaction: SKPaymentTransaction? = nil) { if let transaction = transaction { SKPaymentQueue.default().finishTransaction(transaction) } } func restoreTransaction(transaction: SKPaymentTransaction? = nil) { self.finishTransaction(transaction: transaction) NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerPurchasedNotification), object: nil) } func failedTransaction(transaction: SKPaymentTransaction? = nil, error: Error? = nil) { self.finishTransaction(transaction: transaction) if let error = error ?? transaction?.error { if error._code != SKError.paymentCancelled.rawValue { NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerFailedNotification), object: error) } } } func purchasedTransaction(transaction: SKPaymentTransaction? = nil) { self.finishTransaction(transaction: transaction) NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerPurchasedNotification), object: nil) } }
0a81cee5dfcaa73190b4830f20b90d4c
34.258621
130
0.681174
false
false
false
false
Mqhong/IMSingularity_Swift
refs/heads/master
Example/Pods/SwiftR/SwiftR/SwiftR.swift
mit
1
// // SwiftR.swift // SwiftR // // Created by Adam Hartford on 4/13/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import Foundation import WebKit public enum ConnectionType { case Hub case Persistent } public enum State { case Connecting case Connected case Disconnected } public enum Transport { case Auto case WebSockets case ForeverFrame case ServerSentEvents case LongPolling var stringValue: String { switch self { case .WebSockets: return "webSockets" case .ForeverFrame: return "foreverFrame" case .ServerSentEvents: return "serverSentEvents" case .LongPolling: return "longPolling" default: return "auto" } } } public final class SwiftR: NSObject { static var connections = [SignalR]() public static var signalRVersion: SignalRVersion = .v2_2_0 public static var useWKWebView = false public static var transport: Transport = .Auto public class func connect(url: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) -> SignalR? { let signalR = SignalR(baseUrl: url, connectionType: connectionType, readyHandler: readyHandler) connections.append(signalR) return signalR } public class func startAll() { checkConnections() for connection in connections { connection.start() } } public class func stopAll() { checkConnections() for connection in connections { connection.stop() } } #if os(iOS) public class func cleanup() { let temp = NSURL(fileURLWithPath: NSTemporaryDirectory()) let jqueryTempURL = temp.URLByAppendingPathComponent("jquery-2.1.3.min.js") let signalRTempURL = temp.URLByAppendingPathComponent("jquery.signalR-\(signalRVersion).min") let jsTempURL = temp.URLByAppendingPathComponent("SwiftR.js") let fileManager = NSFileManager.defaultManager() do { if let path = jqueryTempURL.path where fileManager.fileExistsAtPath(path) { try fileManager.removeItemAtURL(jqueryTempURL) } if let path = signalRTempURL.path where fileManager.fileExistsAtPath(path) { try fileManager.removeItemAtURL(signalRTempURL) } if let path = jsTempURL.path where fileManager.fileExistsAtPath(path) { try fileManager.removeItemAtURL(jsTempURL) } } catch { print("Failed to remove temp JavaScript") } } #endif class func checkConnections() { if connections.count == 0 { print("No active SignalR connections. Use SwiftR.connect(...) first.") } } } public class SignalR: NSObject, SwiftRWebDelegate { var webView: SwiftRWebView! var wkWebView: WKWebView! var baseUrl: String var connectionType: ConnectionType var readyHandler: SignalR -> () var hubs = [String: Hub]() public var state: State = .Disconnected public var connectionID: String? public var received: (AnyObject? -> ())? public var starting: (() -> ())? public var connected: (() -> ())? public var disconnected: (() -> ())? public var connectionSlow: (() -> ())? public var connectionFailed: (() -> ())? public var reconnecting: (() -> ())? public var reconnected: (() -> ())? public var error: (AnyObject? -> ())? public var queryString: AnyObject? { didSet { if let qs: AnyObject = queryString { if let jsonData = try? NSJSONSerialization.dataWithJSONObject(qs, options: NSJSONWritingOptions()) { let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String runJavaScript("swiftR.connection.qs = \(json)") } } else { runJavaScript("swiftR.connection.qs = {}") } } } public var headers: [String: String]? { didSet { if let h = headers { if let jsonData = try? NSJSONSerialization.dataWithJSONObject(h, options: NSJSONWritingOptions()) { let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String runJavaScript("swiftR.headers = \(json)") } } else { runJavaScript("swiftR.headers = {}") } } } init(baseUrl: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) { self.baseUrl = baseUrl self.readyHandler = readyHandler self.connectionType = connectionType super.init() #if COCOAPODS let bundle = NSBundle(identifier: "org.cocoapods.SwiftR")! #elseif SWIFTR_FRAMEWORK let bundle = NSBundle(identifier: "com.adamhartford.SwiftR")! #else let bundle = NSBundle.mainBundle() #endif let jqueryURL = bundle.URLForResource("jquery-2.1.3.min", withExtension: "js")! let signalRURL = bundle.URLForResource("jquery.signalR-\(SwiftR.signalRVersion).min", withExtension: "js")! let jsURL = bundle.URLForResource("SwiftR", withExtension: "js")! if SwiftR.useWKWebView { var jqueryInclude = "<script src='\(jqueryURL.absoluteString)'></script>" var signalRInclude = "<script src='\(signalRURL.absoluteString)'></script>" var jsInclude = "<script src='\(jsURL.absoluteString)'></script>" // Loading file:// URLs from NSTemporaryDirectory() works on iOS, not OS X. // Workaround on OS X is to include the script directly. #if os(iOS) if !NSProcessInfo().isOperatingSystemAtLeastVersion(NSOperatingSystemVersion(majorVersion: 9, minorVersion: 0, patchVersion: 0)) { let temp = NSURL(fileURLWithPath: NSTemporaryDirectory()) let jqueryTempURL = temp.URLByAppendingPathComponent("jquery-2.1.3.min.js") let signalRTempURL = temp.URLByAppendingPathComponent("jquery.signalR-\(SwiftR.signalRVersion).min") let jsTempURL = temp.URLByAppendingPathComponent("SwiftR.js") let fileManager = NSFileManager.defaultManager() do { if fileManager.fileExistsAtPath(jqueryTempURL.path!) { try fileManager.removeItemAtURL(jqueryTempURL) } if fileManager.fileExistsAtPath(signalRTempURL.path!) { try fileManager.removeItemAtURL(signalRTempURL) } if fileManager.fileExistsAtPath(jsTempURL.path!) { try fileManager.removeItemAtURL(jsTempURL) } } catch { print("Failed to remove existing temp JavaScript") } do { try fileManager.copyItemAtURL(jqueryURL, toURL: jqueryTempURL) try fileManager.copyItemAtURL(signalRURL, toURL: signalRTempURL) try fileManager.copyItemAtURL(jsURL, toURL: jsTempURL) } catch { print("Failed to copy JavaScript to temp dir") } jqueryInclude = "<script src='\(jqueryTempURL.absoluteString)'></script>" signalRInclude = "<script src='\(signalRTempURL.absoluteString)'></script>" jsInclude = "<script src='\(jsTempURL.absoluteString)'></script>" } #else let jqueryString = try! NSString(contentsOfURL: jqueryURL, encoding: NSUTF8StringEncoding) let signalRString = try! NSString(contentsOfURL: signalRURL, encoding: NSUTF8StringEncoding) let jsString = try! NSString(contentsOfURL: jsURL, encoding: NSUTF8StringEncoding) jqueryInclude = "<script>\(jqueryString)</script>" signalRInclude = "<script>\(signalRString)</script>" jsInclude = "<script>\(jsString)</script>" #endif let config = WKWebViewConfiguration() config.userContentController.addScriptMessageHandler(self, name: "interOp") #if !os(iOS) //config.preferences.setValue(true, forKey: "developerExtrasEnabled") #endif wkWebView = WKWebView(frame: CGRectZero, configuration: config) wkWebView.navigationDelegate = self let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude)" + "</body></html>" wkWebView.loadHTMLString(html, baseURL: bundle.bundleURL) return } else { let jqueryInclude = "<script src='\(jqueryURL.absoluteString)'></script>" let signalRInclude = "<script src='\(signalRURL.absoluteString)'></script>" let jsInclude = "<script src='\(jsURL.absoluteString)'></script>" let html = "<!doctype html><html><head></head><body>" + "\(jqueryInclude)\(signalRInclude)\(jsInclude)" + "</body></html>" webView = SwiftRWebView() #if os(iOS) webView.delegate = self webView.loadHTMLString(html, baseURL: bundle.bundleURL) #else webView.policyDelegate = self webView.mainFrame.loadHTMLString(html, baseURL: bundle.bundleURL) #endif } } deinit { if let view = wkWebView { view.removeFromSuperview() } } public func createHubProxy(name: String) -> Hub { let hub = Hub(name: name, connection: self) hubs[name.lowercaseString] = hub return hub } public func send(data: AnyObject?) { var json = "null" if let d: AnyObject = data { if d is String { json = "'\(d)'" } else if d is NSNumber { json = "\(d)" } else if let jsonData = try? NSJSONSerialization.dataWithJSONObject(d, options: NSJSONWritingOptions()) { json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String } } runJavaScript("swiftR.connection.send(\(json))") } public func start() { runJavaScript("start()") } public func stop() { runJavaScript("swiftR.connection.stop()") } func shouldHandleRequest(request: NSURLRequest) -> Bool { if request.URL!.absoluteString.hasPrefix("swiftr://") { let id = (request.URL!.absoluteString as NSString).substringFromIndex(9) let msg = webView.stringByEvaluatingJavaScriptFromString("readMessage('\(id)')")! let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: []) processMessage(json) return false } return true } func processMessage(json: AnyObject) { if let message = json["message"] as? String { switch message { case "ready": let isHub = connectionType == .Hub ? "true" : "false" runJavaScript("swiftR.transport = '\(SwiftR.transport.stringValue)'") runJavaScript("initialize('\(baseUrl)', \(isHub))") readyHandler(self) runJavaScript("start()") case "starting": state = .Connecting starting?() case "connected": state = .Connected connectionID = json["connectionId"] as? String connected?() case "disconnected": state = .Disconnected disconnected?() case "connectionSlow": connectionSlow?() case "connectionFailed": connectionFailed?() case "reconnecting": state = .Connecting reconnecting?() case "reconnected": state = .Connected reconnected?() case "invokeHandler": let hubName = json["hub"] as! String if let hub = hubs[hubName] { let uuid = json["id"] as! String let result = json["result"] let error = json["error"] if let callback = hub.invokeHandlers[uuid] { callback(result: result, error: error) hub.invokeHandlers.removeValueForKey(uuid) } } case "error": if let err: AnyObject = json["error"] { error?(err) } else { error?(nil) } default: break } } else if let data: AnyObject = json["data"] { received?(data) } else if let hubName = json["hub"] as? String { let callbackID = json["id"] as? String let method = json["method"] as? String let arguments = json["arguments"] as? [AnyObject] let hub = hubs[hubName] if let method = method, callbackID = callbackID, handlers = hub?.handlers[method], handler = handlers[callbackID] { handler(arguments) } } } func runJavaScript(script: String, callback: (AnyObject! -> ())? = nil) { if SwiftR.useWKWebView { wkWebView.evaluateJavaScript(script, completionHandler: { (result, _) in callback?(result) }) } else { let result = webView.stringByEvaluatingJavaScriptFromString(script) callback?(result) } } // MARK: - WKNavigationDelegate // http://stackoverflow.com/questions/26514090/wkwebview-does-not-run-javascriptxml-http-request-with-out-adding-a-parent-vie#answer-26575892 public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { #if os(iOS) UIApplication.sharedApplication().keyWindow?.addSubview(wkWebView) #endif } // MARK: - WKScriptMessageHandler public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let id = message.body as? String { wkWebView.evaluateJavaScript("readMessage('\(id)')", completionHandler: { [weak self] (msg, _) in if let m = msg { self?.processMessage(m) } }) } } // MARK: - Web delegate methods #if os(iOS) public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { return shouldHandleRequest(request) } #else public func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) { if shouldHandleRequest(request) { listener.use() } } #endif } // MARK: - Hub public class Hub { let name: String var handlers: [String: [String: [AnyObject]? -> ()]] = [:] var invokeHandlers: [String: (result: AnyObject?, error: AnyObject?) -> ()] = [:] public let connection: SignalR! init(name: String, connection: SignalR) { self.name = name self.connection = connection } public func on(method: String, callback: [AnyObject]? -> ()) { let callbackID = NSUUID().UUIDString if handlers[method] == nil { handlers[method] = [:] } handlers[method]?[callbackID] = callback connection.runJavaScript("addHandler('\(callbackID)', '\(name)', '\(method)')") } public func invoke(method: String, arguments: [AnyObject]?, callback: ((result: AnyObject?, error: AnyObject?) -> ())? = nil) { var jsonArguments = [String]() if let args = arguments { for arg in args { // Using an array to start with a valid top level type for NSJSONSerialization let arr = [arg] if let data = try? NSJSONSerialization.dataWithJSONObject(arr, options: NSJSONWritingOptions()) { if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { // Strip the array brackets to be left with the desired value let range = str.startIndex.advancedBy(1) ..< str.endIndex.advancedBy(-1) jsonArguments.append(str.substringWithRange(range)) } } } } let args = jsonArguments.joinWithSeparator(", ") let uuid = NSUUID().UUIDString if let handler = callback { invokeHandlers[uuid] = handler } let doneJS = "function() { postMessage({ message: 'invokeHandler', hub: '\(name.lowercaseString)', id: '\(uuid)', result: arguments[0] }); }" let failJS = "function() { postMessage({ message: 'invokeHandler', hub: '\(name.lowercaseString)', id: '\(uuid)', error: processError(arguments[0]) }); }" let js = args.isEmpty ? "ensureHub('\(name)').invoke('\(method)').done(\(doneJS)).fail(\(failJS))" : "ensureHub('\(name)').invoke('\(method)', \(args)).done(\(doneJS)).fail(\(failJS))" connection.runJavaScript(js) } } public enum SignalRVersion : CustomStringConvertible { case v2_2_0 case v2_1_2 case v2_1_1 case v2_1_0 case v2_0_3 case v2_0_2 case v2_0_1 case v2_0_0 public var description: String { switch self { case .v2_2_0: return "2.2.0" case .v2_1_2: return "2.1.2" case .v2_1_1: return "2.1.1" case .v2_1_0: return "2.1.0" case .v2_0_3: return "2.0.3" case .v2_0_2: return "2.0.2" case .v2_0_1: return "2.0.1" case .v2_0_0: return "2.0.0" } } } #if os(iOS) typealias SwiftRWebView = UIWebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, UIWebViewDelegate {} #else typealias SwiftRWebView = WebView public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, WebPolicyDelegate {} #endif
cc4dfbab9e6809bc01b59e271248ad2c
36.890838
162
0.554378
false
false
false
false
Ben21hao/edx-app-ios-new
refs/heads/master
Source/TDCourseCatalogDetailViewController/Views/TDCourseCatalogDetailView.swift
apache-2.0
1
// // TDCourseCatalogDetailView.swift // edX // // Created by Ben on 2017/5/3. // Copyright © 2017年 edX. All rights reserved. // import UIKit class TDCourseCatalogDetailView: UIView,UITableViewDataSource { typealias Environment = protocol<OEXAnalyticsProvider, DataManagerProvider, NetworkManagerProvider, OEXRouterProvider> private let environment : Environment internal let tableView = UITableView() internal let courseCardView = CourseCardView() internal let playButton = UIButton() internal var playButtonHandle : (() -> ())? internal var submitButtonHandle : (() -> ())? internal var showAllTextHandle : ((Bool) -> ())? var showAllText = false var submitTitle : String? var courseModel = OEXCourse() private var _loaded = Sink<()>() var loaded : Stream<()> { return _loaded } init(frame: CGRect, environment: Environment) { self.environment = environment super.init(frame: frame) self.backgroundColor = OEXStyles.sharedStyles().baseColor5() setViewConstraint() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: 加载课程详情信息函数 func applyCourse(course : OEXCourse) { CourseCardViewModel.onCourseCatalog(course).apply(courseCardView, networkManager: self.environment.networkManager,type:1)//头部图片 self.playButton.hidden = course.intro_video_3rd_url!.isEmpty ?? true self.courseModel = course self.tableView.reloadData() } //MARK: 全文 - 收起 func moreButtonAction(sender: UIButton) { self.showAllText = !self.showAllText if (self.showAllTextHandle != nil) { self.showAllTextHandle?(self.showAllText) } } func submitButtonAction() { //提交 if (self.submitButtonHandle != nil) { self.submitButtonHandle!() } } func playButtonAction() { if self.playButtonHandle != nil { self.playButtonHandle?() } } //MARK: tableview Delegate func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 3 } else { return 5 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { if indexPath.row == 0 { let cell = TDCourseIntroduceCell.init(style: .Default, reuseIdentifier: "TDCourseIntroduceCell") cell.selectionStyle = .None cell.moreButton.tag = 8 if self.showAllText == true { cell.introduceLabel.text = "\(self.courseModel.short_description!)\n\(self.courseModel.moreDescription!)" cell.moreButton.setTitle(Strings.stopUp, forState: .Normal) } else { cell.introduceLabel.text = self.courseModel.short_description cell.moreButton.setTitle(Strings.allText, forState: .Normal) } cell.moreButton.addTarget(self, action: #selector(moreButtonAction(_:)), forControlEvents: .TouchUpInside) if self.courseModel.moreDescription?.characters.count == 0 && self.courseModel.short_description?.characters.count == 0 { cell.moreButton.hidden = true } return cell } else if indexPath.row == 1 { let cell = TDCourseMessageCell.init(style: .Default, reuseIdentifier: "TDCourseMessageCell") cell.selectionStyle = .None cell.timeLabel.text = self.courseModel.effort?.stringByAppendingString(Strings.studyHour) if ((self.courseModel.effort?.containsString("约")) != nil) { let timeStr = NSMutableString.init(string: self.courseModel.effort!) let time = timeStr.stringByReplacingOccurrencesOfString("约", withString:"\(Strings.aboutTime) ") cell.timeLabel.text = String(time.stringByAppendingString(" \(Strings.studyHour)")) } if self.courseModel.listen_count != nil { let timeStr : String = self.courseModel.listen_count!.stringValue cell.numberLabel.text = "\(timeStr) \(Strings.numberStudent)" } else { cell.numberLabel.text = "0\(Strings.numberStudent)" } return cell } else { let cell = TDCourseButtonsCell.init(style: .Default, reuseIdentifier: "TDCourseButtonsCell") cell.selectionStyle = .None switch self.courseModel.submitType { case 0: cell.submitButton.setTitle(Strings.CourseDetail.viewCourse, forState: .Normal) case 1: cell.submitButton.setAttributedTitle(setSubmitTitle(), forState: .Normal) case 2: cell.submitButton.setTitle(Strings.viewPrepareOrder, forState: .Normal) default: cell.submitButton.setTitle(Strings.willBeginCourse, forState: .Normal) } cell.submitButton.addTarget(self, action: #selector(submitButtonAction), forControlEvents: .TouchUpInside) return cell } } else { let cell = TDCourseDataCell.init(style: .Default, reuseIdentifier: "TDCourseDataCell") cell.selectionStyle = .None cell.accessoryType = .DisclosureIndicator switch indexPath.row { case 0: cell.leftLabel.text = "\u{f19c}" cell.titleLabel.text = Strings.mainProfessor case 1: cell.leftLabel.text = "\u{f0ca}" cell.titleLabel.text = Strings.courseOutline case 2: cell.leftLabel.text = "\u{f040}" cell.titleLabel.text = Strings.studentComment case 3: cell.leftLabel.text = "\u{f0c0}" cell.titleLabel.text = Strings.classTitle default: cell.leftLabel.text = "\u{f0c0}" cell.titleLabel.text = "助教" } return cell } } func setSubmitTitle() -> NSAttributedString { let baseTool = TDBaseToolModel.init() let priceStr = baseTool.setDetailString("\(Strings.CourseDetail.enrollNow)¥\(String(format: "%.2f",(self.courseModel.course_price?.doubleValue)!))", withFont: 16, withColorStr: "#ffffff") return priceStr //马上加入 } //MARK: UI func setViewConstraint() { let headerView = UIView.init(frame: CGRectMake(0, 0, TDScreenWidth, (TDScreenWidth - 36) / 1.7 + 21)) headerView.addSubview(courseCardView) courseCardView.snp_makeConstraints { (make) in make.left.equalTo(headerView.snp_left).offset(18) make.right.equalTo(headerView.snp_right).offset(-18) make.top.equalTo(headerView.snp_top).offset(16) make.height.equalTo((TDScreenWidth - 36) / 1.77) } playButton.setImage(Icon.CourseVideoPlay.imageWithFontSize(60), forState: .Normal) playButton.tintColor = OEXStyles.sharedStyles().neutralWhite() playButton.layer.shadowOpacity = 0.5 playButton.layer.shadowRadius = 3 playButton.layer.shadowOffset = CGSizeZero playButton.addTarget(self, action: #selector(playButtonAction), forControlEvents: .TouchUpInside) courseCardView.addCenteredOverlay(playButton) tableView.dataSource = self tableView.separatorStyle = .None self.addSubview(tableView) tableView.snp_makeConstraints { (make) in make.left.right.top.bottom.equalTo(self) } tableView.tableFooterView = UIView() tableView.tableHeaderView = headerView headerView.backgroundColor = UIColor.whiteColor() tableView.backgroundColor = OEXStyles.sharedStyles().baseColor5() } }
6348868aaf367dc36a3dd5e289cd0904
37.855204
195
0.583673
false
false
false
false
aulas-lab/ads-mobile
refs/heads/master
swift/ClasseDemo/ClasseDemo/Aluno.swift
mit
1
// // Aluno.swift // ClasseDemo // // Created by Mobitec on 26/04/16. // Copyright (c) 2016 Unopar. All rights reserved. // import Foundation class Aluno { private let id: Int private var nome: String private var cpf: String private var endereco: String // private static var idSeed = 0 init() { id = 0 // ++Aluno.idSeed nome = "Sem Nome" cpf = "" endereco = "" } init(id: Int, nome: String, cpf: String) { self.id = id self.nome = nome self.cpf = cpf endereco = "" } var Nome: String { get { return nome } set(novoNome) { nome = novoNome } } var Endereco: String { get { return endereco; } set(novoEndereco) { endereco = novoEndereco; } } // Propriedade somente leitura var Id: Int { get { return id } } var Turma: String = "" { willSet(novoNome) { println("A nova turma sera \(novoNome)") } didSet { println("Turma = Anterior: \(oldValue), Atual: \(Turma)") } } func descricao() -> String { return "Id: \(id), Nome: \(nome), Endereco: \(endereco), Turma: \(Turma)"; } }
0862e8e08ff6491e177e1d8a6553392b
19.901639
82
0.502745
false
false
false
false
carambalabs/UnsplashKit
refs/heads/master
UnsplashKit/Classes/UnsplashAPI/Models/Response.swift
mit
1
import Foundation /// API response that includes the pagination links. public struct Response<A> { // MARK: - Attributes /// Response object. public let object: A /// Pagination first link. public let firstLink: Link? /// Pagination previous link. public let prevLink: Link? /// Pagination next link. public let nextLink: Link? /// Pagination last link. public let lastLink: Link? /// Limit of requests. public let limitRequests: Int? /// Number of remaining requests. public let remainingRequests: Int? // MARK: - Init /// Initializes the response with the object and the http response. /// /// - Parameters: /// - object: object included in the response. /// - response: http url response. internal init(object: A, response: HTTPURLResponse) { self.object = object self.firstLink = response.findLink(relation: "first") self.prevLink = response.findLink(relation: "prev") self.nextLink = response.findLink(relation: "next") self.lastLink = response.findLink(relation: "last") self.limitRequests = response.allHeaderFields["X-Ratelimit-Limit"] as? Int self.remainingRequests = response.allHeaderFields["X-Ratelimit-Remaining"] as? Int } }
156cd902e951dbe91b8c5ae6ea94faeb
27.369565
91
0.65364
false
false
false
false
Reedyuk/Charts
refs/heads/Swift-3.0
Charts/Classes/Charts/HorizontalBarChartView.swift
apache-2.0
6
// // HorizontalBarChartView.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/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched. open class HorizontalBarChartView: BarChartView { internal override func initialize() { super.initialize() _leftAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler) _rightAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler) renderer = HorizontalBarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler) _leftYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer) _rightYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer) _xAxisRenderer = ChartXAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self) self.highlighter = HorizontalBarChartHighlighter(chart: self) } internal override func calculateOffsets() { var offsetLeft: CGFloat = 0.0, offsetRight: CGFloat = 0.0, offsetTop: CGFloat = 0.0, offsetBottom: CGFloat = 0.0 calculateLegendOffsets(offsetLeft: &offsetLeft, offsetTop: &offsetTop, offsetRight: &offsetRight, offsetBottom: &offsetBottom) // offsets for y-labels if (_leftAxis.needsOffset) { offsetTop += _leftAxis.getRequiredHeightSpace() } if (_rightAxis.needsOffset) { offsetBottom += _rightAxis.getRequiredHeightSpace() } let xlabelwidth = _xAxis.labelRotatedWidth if (_xAxis.enabled) { // offsets for x-labels if (_xAxis.labelPosition == .bottom) { offsetLeft += xlabelwidth } else if (_xAxis.labelPosition == .top) { offsetRight += xlabelwidth } else if (_xAxis.labelPosition == .bothSided) { offsetLeft += xlabelwidth offsetRight += xlabelwidth } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset _viewPortHandler.restrainViewPort( offsetLeft: max(self.minOffset, offsetLeft), offsetTop: max(self.minOffset, offsetTop), offsetRight: max(self.minOffset, offsetRight), offsetBottom: max(self.minOffset, offsetBottom)) prepareOffsetMatrix() prepareValuePxMatrix() } internal override func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _rightAxis._axisMinimum, deltaX: CGFloat(_rightAxis.axisRange), deltaY: CGFloat(_xAxis.axisRange), chartYMin: _xAxis._axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _leftAxis._axisMinimum, deltaX: CGFloat(_leftAxis.axisRange), deltaY: CGFloat(_xAxis.axisRange), chartYMin: _xAxis._axisMinimum) } internal override func calcModulus() { if let data = _data { _xAxis.axisLabelModulus = Int(ceil((CGFloat(data.xValCount) * _xAxis.labelRotatedHeight) / (_viewPortHandler.contentHeight * viewPortHandler.touchMatrix.d))) } else { _xAxis.axisLabelModulus = 1 } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1 } } open override func getBarBounds(_ e: BarChartDataEntry) -> CGRect { guard let set = _data?.getDataSetForEntry(e) as? IBarChartDataSet else { return CGRect.null } let barspace = set.barSpace let y = CGFloat(e.value) let x = CGFloat(e.xIndex) let spaceHalf = barspace / 2.0 let top = x - 0.5 + spaceHalf let bottom = x + 0.5 - spaceHalf let left = y >= 0.0 ? y : 0.0 let right = y <= 0.0 ? y : 0.0 var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top) getTransformer(set.axisDependency).rectValueToPixel(&bounds) return bounds } open override func getPosition(_ e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.value), y: CGFloat(e.xIndex)) getTransformer(axis).pointValueToPixel(&vals) return vals } open override func getHighlightByTouchPoint(_ pt: CGPoint) -> ChartHighlight? { if _data === nil { Swift.print("Can't select by touch. No data set.", terminator: "\n") return nil } return self.highlighter?.getHighlight(x: pt.y, y: pt.x) } open override var lowestVisibleXIndex: Int { let step = CGFloat(_data?.dataSetCount ?? 0) let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom) getTransformer(ChartYAxis.AxisDependency.left).pixelToValue(&pt) return Int(((pt.y <= 0.0) ? 0.0 : pt.y / div) + 1.0) } open override var highestVisibleXIndex: Int { let step = CGFloat(_data?.dataSetCount ?? 0) let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentTop) getTransformer(ChartYAxis.AxisDependency.left).pixelToValue(&pt) return Int((pt.y >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.y / div)) } }
ee2c527b241dac9cfa3e010ace16224c
34.125
192
0.605446
false
false
false
false
Steveaxelrod007/UtilitiesInSwift
refs/heads/master
UtilitiesInSwift/Classes/CancelableClosure.swift
mit
1
// axee.com by Steve Axelrod import Foundation public class CancelableClosure { public var cancelled = false public var closure: () -> () = {} public func run() { if cancelled == false { cancelled = true // axe in case they also did a runAfterDelayOf closure() } } public func runAfterDelayOf(delayTime: Double = 0.5) { if cancelled == false { Queues.delayThenRunMainQueue(delay: delayTime) { [weak self] () -> Void in if self?.cancelled == false { self?.run() } } } } public init() { } }
3fa552138cb2a020f4ccceb5702a2dbc
13.341463
68
0.576531
false
false
false
false
VincentPuget/vigenere
refs/heads/master
vigenere/class/AppDelegate.swift
mit
1
// // AppDelegate.swift // Vigenere // // Created by Vincent PUGET on 05/08/2015. // Copyright (c) 2015 Vincent PUGET. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } //qui l'app si la dernière fenetre active est fermée func applicationShouldTerminateAfterLastWindowClosed(_ theApplication: NSApplication) -> Bool { return true; } // // MARK: - Core Data stack // // lazy var applicationDocumentsDirectory: NSURL = { // // The directory the application uses to store the Core Data store file. This code uses a directory named "mao.macos.vigenere.test" in the user's Application Support directory. // let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask) // let appSupportURL = urls[urls.count - 1] as! NSURL // return appSupportURL.URLByAppendingPathComponent("mao.macos.vigenere.test") // }() // // lazy var managedObjectModel: NSManagedObjectModel = { // // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. // let modelURL = NSBundle.mainBundle().URLForResource("test", withExtension: "momd")! // return NSManagedObjectModel(contentsOfURL: modelURL)! // }() // // lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // let fileManager = NSFileManager.defaultManager() // var shouldFail = false // var error: NSError? = nil // var failureReason = "There was an error creating or loading the application's saved data." // // // Make sure the application files directory is there // let propertiesOpt = self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error) // if let properties = propertiesOpt { // if !properties[NSURLIsDirectoryKey]!.boolValue { // failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)." // shouldFail = true // } // } else if error!.code == NSFileReadNoSuchFileError { // error = nil // fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error) // } // // // Create the coordinator and store // var coordinator: NSPersistentStoreCoordinator? // if !shouldFail && (error == nil) { // coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) // let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("test.storedata") // if coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { // coordinator = nil // } // } // // if shouldFail || (error != nil) { // // Report any error we got. // var dict = [String: AnyObject]() // dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" // dict[NSLocalizedFailureReasonErrorKey] = failureReason // if error != nil { // dict[NSUnderlyingErrorKey] = error // } // error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // NSApplication.sharedApplication().presentError(error!) // return nil // } else { // return coordinator // } // }() // // lazy var managedObjectContext: NSManagedObjectContext? = { // // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. // let coordinator = self.persistentStoreCoordinator // if coordinator == nil { // return nil // } // var managedObjectContext = NSManagedObjectContext() // managedObjectContext.persistentStoreCoordinator = coordinator // return managedObjectContext // }() // // // MARK: - Core Data Saving and Undo support // // @IBAction func saveAction(sender: AnyObject!) { // // Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user. // if let moc = self.managedObjectContext { // if !moc.commitEditing() { // NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving") // } // var error: NSError? = nil // if moc.hasChanges && !moc.save(&error) { // NSApplication.sharedApplication().presentError(error!) // } // } // } // // func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? { // // Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application. // if let moc = self.managedObjectContext { // return moc.undoManager // } else { // return nil // } // } // // func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { // // Save changes in the application's managed object context before the application terminates. // // if let moc = managedObjectContext { // if !moc.commitEditing() { // NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate") // return .TerminateCancel // } // // if !moc.hasChanges { // return .TerminateNow // } // // var error: NSError? = nil // if !moc.save(&error) { // // Customize this code block to include application-specific recovery steps. // let result = sender.presentError(error!) // if (result) { // return .TerminateCancel // } // // let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message") // let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info"); // let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title") // let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title") // let alert = NSAlert() // alert.messageText = question // alert.informativeText = info // alert.addButtonWithTitle(quitButton) // alert.addButtonWithTitle(cancelButton) // // let answer = alert.runModal() // if answer == NSAlertFirstButtonReturn { // return .TerminateCancel // } // } // } // // If we got here, it is time to quit. // return .TerminateNow // } }
d68fb4ff5f72cf0190b5d213de7f279f
48.719512
348
0.624847
false
false
false
false
SlackKit/SlackKit
refs/heads/main
SKCore/Sources/DoNotDisturbStatus.swift
mit
2
// // DoNotDisturbStatus.swift // // Copyright © 2017 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct DoNotDisturbStatus { fileprivate enum CodingKeys: String { case enabled = "dnd_enabled" case nextDoNotDisturbStart = "next_dnd_start_ts" case nextDoNotDisturbEnd = "next_dnd_end_ts" case snoozeEnabled = "snooze_enabled" case snoozeEndtime = "snooze_endtime" } public var enabled: Bool? public var nextDoNotDisturbStart: Int? public var nextDoNotDisturbEnd: Int? public var snoozeEnabled: Bool? public var snoozeEndtime: Int? public init(status: [String: Any]?) { enabled = status?[CodingKeys.enabled] as? Bool nextDoNotDisturbStart = status?[CodingKeys.nextDoNotDisturbStart] as? Int nextDoNotDisturbEnd = status?[CodingKeys.nextDoNotDisturbEnd] as? Int snoozeEnabled = status?[CodingKeys.snoozeEnabled] as? Bool snoozeEndtime = status?[CodingKeys.snoozeEndtime] as? Int } } extension DoNotDisturbStatus: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) enabled = try values.decodeIfPresent(Bool.self, forKey: .enabled) nextDoNotDisturbStart = try values.decodeIfPresent(Int.self, forKey: .nextDoNotDisturbStart) nextDoNotDisturbEnd = try values.decodeIfPresent(Int.self, forKey: .nextDoNotDisturbEnd) snoozeEnabled = try values.decodeIfPresent(Bool.self, forKey: .snoozeEnabled) snoozeEndtime = try values.decodeIfPresent(Int.self, forKey: .snoozeEndtime) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(enabled, forKey: .enabled) try container.encode(nextDoNotDisturbStart, forKey: .nextDoNotDisturbStart) try container.encode(nextDoNotDisturbEnd, forKey: .nextDoNotDisturbEnd) try container.encode(snoozeEnabled, forKey: .snoozeEnabled) try container.encode(snoozeEndtime, forKey: .snoozeEndtime) } } extension DoNotDisturbStatus.CodingKeys: CodingKey { }
013434fcc4b50f6c096373c174bff911
46.5
100
0.733437
false
false
false
false
leosimas/ios_KerbalCampaigns
refs/heads/master
Kerbal Campaigns/Colors.swift
apache-2.0
1
// // Colors.swift // Kerbal Campaigns // // Created by SoSucesso on 08/10/17. // Copyright © 2017 Simas Team. All rights reserved. // import UIKit struct Colors { static let primary = Colors.hexStringToUIColor(hex: "283593") static let secondary = Colors.hexStringToUIColor(hex: "3f51b5") static let progressBar = Colors.hexStringToUIColor(hex: "33ff00") static func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.characters.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
808a0f39a3adc11a93390eac5dd62de0
27.564103
93
0.587971
false
false
false
false
entaku19890818/weather
refs/heads/master
weather/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // weather // // Created by 遠藤拓弥 on 2019/04/07. // Copyright © 2019 遠藤拓弥. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let weatherAreaViewController:WeatherAreaViewController = UIStoryboard(name: "WeatherAreaViewController", bundle: nil).instantiateInitialViewController() as! WeatherAreaViewController let navigationController:UINavigationController = UINavigationController.init(rootViewController: weatherAreaViewController) self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "weather") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
06863cfe56a435c1eae5309e51fc156c
49.71
285
0.695721
false
false
false
false
sgr-ksmt/PullToDismiss
refs/heads/master
Demo/Demo/SampleTableViewController.swift
mit
1
// // SampleTableViewController.swift // PullToDismiss // // Created by Suguru Kishimoto on 11/13/16. // Copyright © 2016 Suguru Kishimoto. All rights reserved. // import UIKit import PullToDismiss class SampleTableViewController: UITableViewController { private lazy var dataSource: [String] = { () -> [String] in return (0..<100).map { "Item : \($0)" } }() private var pullToDismiss: PullToDismiss? override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") let button = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(dismiss(_:))) navigationItem.rightBarButtonItem = button navigationItem.title = "Sample Table View" navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.barTintColor = .orange navigationController?.navigationBar.setValue(UIBarPosition.topAttached.rawValue, forKey: "barPosition") pullToDismiss = PullToDismiss(scrollView: tableView) Config.shared.adaptSetting(pullToDismiss: pullToDismiss) pullToDismiss?.dismissAction = { [weak self] in self?.dismiss(nil) } pullToDismiss?.delegate = self } var disissBlock: (() -> Void)? // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = dataSource[indexPath.row] return cell } @objc func dismiss(_: AnyObject?) { dismiss(animated: true) { [weak self] in self?.disissBlock?() } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let alert = UIAlertController(title: "test", message: "\(indexPath.section)-\(indexPath.row) touch!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { print("\(scrollView.contentOffset.y)") } }
086ab7008634f4413e7a2ce3dff40a2a
37.984615
133
0.672849
false
false
false
false
GoodMorningCody/EverybodySwift
refs/heads/master
WeeklyToDo/WeeklyToDo/WeeklyToDoTableViewController.swift
mit
1
// // WeeklyToDoTableViewController.swift // WeeklyToDo // // Created by Cody on 2015. 1. 22.. // Copyright (c) 2015년 TIEKLE. All rights reserved. // import UIKit class WeeklyToDoTableViewController: UITableViewController, TaskTableViewCellProtocol, TaskViewProtocol { var taskViewController : UIViewController? var timer : NSTimer? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = Color.getNavigationBackgroundColor() self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:Color.getPointColor(), NSFontAttributeName : Font.getHightlightFont()] // self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "add"), style: UIBarButtonItemStyle.Plain, target: self, action: "addNewTask") self.navigationItem.rightBarButtonItem?.tintColor = Color.getPointColor() WeeklyToDoDB.sharedInstance.needUpdate() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("orientationChanged"), name: UIDeviceOrientationDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("willEnterForrground"), name: UIApplicationWillEnterForegroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didEnterBackground"), name: UIApplicationDidEnterBackgroundNotification, object: nil) setUpdateScheduler() } func didEnterBackground() { if timer != nil { timer?.invalidate() timer = nil } NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil) } func willEnterForrground() { setUpdateScheduler() } func setUpdateScheduler() { let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond, fromDate: NSDate()) if timer != nil { timer?.invalidate() timer = nil } var afterSeconds = Double(((24-components.hour)*60*60)-(components.minute*60)-(components.second)) timer = NSTimer.scheduledTimerWithTimeInterval(afterSeconds, target: self, selector: Selector("needUpdate"), userInfo: nil, repeats: false) } func needUpdate() { println("needUpdate") WeeklyToDoDB.sharedInstance.needUpdate() tableView?.reloadData() setUpdateScheduler() } func orientationChanged() { if let viewController = taskViewController { viewController.view.center = CGPointMake(UIScreen.mainScreen().bounds.size.width/2, UIScreen.mainScreen().bounds.size.height/2) viewController.view.bounds = UIScreen.mainScreen().bounds } } func addNewTask() { if taskViewController == nil { taskViewController = self.storyboard?.instantiateViewControllerWithIdentifier("TaskViewIdentifier") as? UIViewController } if let rootView = self.navigationController?.view { if let taskView = taskViewController!.view as? TaskView { taskView.delegate = self taskView.show(rootView) } } } func didAddingToDo() { tableView.reloadData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "TaskSegueIdentifier" { println("Create or Edit Task") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 7 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return WeeklyToDoDB.sharedInstance.countOfTaskInWeekend(section) + 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cellIdentifier : String? if indexPath.row==0 { cellIdentifier = "WeekendTableViewCellIdentifier" } else { cellIdentifier = "TaskTableViewCellIdentifier" } let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier!, forIndexPath: indexPath) as UITableViewCell if indexPath.row == 0 { return updateWeekendCell(cell, withIndexPath: indexPath) } return updateTaskCell(cell, withIndexPath: indexPath) } private func updateTaskCell(cell: UITableViewCell, withIndexPath indexPath : NSIndexPath) -> TaskTableViewCell { // 업데이트 로직을 cell 객체로 이동 var taskCell = cell as TaskTableViewCell taskCell.delegate = self taskCell.tableView = self.tableView if let task = WeeklyToDoDB.sharedInstance.taskInWeekend(indexPath.section, atIndex: indexPath.row-1) { taskCell.todo = task.todo taskCell.done = task.done.boolValue taskCell.repeat = task.repeat.boolValue } return taskCell } private func updateWeekendCell(cell: UITableViewCell, withIndexPath indexPath : NSIndexPath) -> WeekendTableViewCell { // 업데이트 로직을 cell 객체로 이동 var weekendCell = cell as WeekendTableViewCell if WeeklyToDoDB.sharedInstance.countOfTaskInWeekend(indexPath.section) > 0 { weekendCell.depthImageView?.hidden = false } else { weekendCell.depthImageView?.hidden = true } weekendCell.todayMarkView?.hidden = (indexPath.section != 0) weekendCell.weekendLabel?.text = Weekly.weekdayFromNow(indexPath.section, useStandardFormat: false) var countOfTask = WeeklyToDoDB.sharedInstance.countOfTaskInWeekend(indexPath.section) var countOfDoneTask = WeeklyToDoDB.sharedInstance.countOfDoneTaskInWeekend(indexPath.section) if countOfTask>0 { weekendCell.countLabel?.hidden = false weekendCell.countLabel?.text = String(countOfDoneTask)+"/"+String(countOfTask) } else { weekendCell.countLabel?.hidden = true } return weekendCell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row==0 { return 58.0 } return 44.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row==0 { return } if taskViewController == nil { taskViewController = self.storyboard?.instantiateViewControllerWithIdentifier("TaskViewIdentifier") as? UIViewController } if let rootView = self.navigationController?.view { if let taskView = taskViewController!.view as? TaskView { taskView.delegate = self taskView.show(rootView, weekend: indexPath.section, index: indexPath.row-1) } } } func taskTableViewCell(#done: Bool, trash: Bool, repeat: Bool, indexPath:NSIndexPath) { if done==true { WeeklyToDoDB.sharedInstance.switchDoneTaskInWeekend(indexPath.section, atIndex: indexPath.row-1) } else if trash==true { WeeklyToDoDB.sharedInstance.removeTaskInWeekend(indexPath.section, atIndex: indexPath.row-1) } else if repeat==true { WeeklyToDoDB.sharedInstance.switchRepeatOptionInWeekend(indexPath.section, atIndex: indexPath.row-1) } self.tableView.reloadData() } }
1d3e48d729566aa7bf2011874f4f917e
38.275362
189
0.6631
false
false
false
false
BellAppLab/Defines
refs/heads/master
Sources/Defines/Defines.swift
mit
1
/* Copyright (c) 2018 Bell App Lab <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation //MARK: - Main /** The main point of interaction with `Defines`. All the flags in this module are namespaced under the `Defines` struct to avoid collisions. Structure: ``` Defines.Device Defines.Device.Model Defines.Screen Defines.OS Defines.App Defines.Version ``` ## See Also - [List of iOS Devices](https://en.wikipedia.org/wiki/List_of_iOS_devices) */ public struct Defines { //MARK: - Device public struct Device { //MARK: - Model /** An enumeration of model identifiers for all the relevant Apple products since 2008. Roughly speaking, these devices have been listed according to their ability to run the minimum OS versions supported by `Defines`. ## See Also - [Models - The iPhone Wiki](https://www.theiphonewiki.com/wiki/Models) - [Watch](https://support.apple.com/en-us/HT204507#link2) - [iPad](https://support.apple.com/en-us/HT201471#ipad) - [iPhone](https://support.apple.com/en-us/HT201296) - [iPod Touch](https://support.apple.com/en-us/HT204217#ipodtouch) - [MacBook air](https://support.apple.com/en-us/HT201862) - [MacBook](https://support.apple.com/en-us/HT201608) - [MacBook Pro](https://support.apple.com/en-us/HT201300) - [Mac mini](https://support.apple.com/en-us/HT201894) - [iMac](https://support.apple.com/en-us/HT201634) - [Mac Pro](https://support.apple.com/en-us/HT202888) - [What does 'MM' mean?](//https://apple.stackexchange.com/a/101066) */ public enum Model: String { //MARK: Default /// If `Defines.Device.Model` cannot find the current device's model, this is the enum case it returns. case unknown = "" //MARK: AirPods /// AirPods model identifier. case airPods = "AirPods1,1" //MARK: - Apple TV /// TV (2nd Generation) model identifier. case appleTV_2ndGeneration = "AppleTV2,1" /// TV (3rd Generation) model identifier. case appleTV_3rdGeneration = "AppleTV3,1" /// TV (3rd Generation - revision 2) model identifier. case appleTV_3rdGeneration_2 = "AppleTV3,2" /// TV (4th Generation) model identifier. case appleTV_4thGeneration = "AppleTV5,3" /// TV 4K model identifier. case appleTV_4K = "AppleTV6,2" //MARK: Apple Watch /// Watch (1st Generation) 38mm model identifier. case appleWatch_1stGeneration_38mm = "Watch1,1" /// Watch (1st Generation) 42mm model identifier. case appleWatch_1stGeneration_42mm = "Watch1,2" /// Watch Series 1 38mm model identifier. case appleWatchSeries1_38mm = "Watch2,6" /// Watch Series 1 42mm model identifier. case appleWatchSeries1_42mm = "Watch2,7" /// Watch Series 2 38mm model identifier. case appleWatchSeries2_38mm = "Watch2,3" /// Watch Series 2 42mm model identifier. case appleWatchSeries2_42mm = "Watch2,4" /// Watch Series 3 38mm (GPS+Cellular) model identifier. case appleWatchSeries3_38mm_GPS_Cellular = "Watch3,1" /// Watch Series 3 42mm (GPS+Cellular) model identifier. case appleWatchSeries3_42mm_GPS_Cellular = "Watch3,2" /// Watch Series 3 38mm (GPS) model identifier. case appleWatchSeries3_38mm_GPS = "Watch3,3" /// Watch Series 3 42mm (GPS) model identifier. case appleWatchSeries3_42mm_GPS = "Watch3,4" /// Watch Series 4 40mm (GPS) model identifier. case appleWatchSeries4_40mm_GPS = "Watch4,1" /// Watch Series 4 42mm (GPS) model identifier. case appleWatchSeries4_44mm_GPS = "Watch4,2" /// Watch Series 4 40mm (GPS+Cellular) model identifier. case appleWatchSeries4_40mm_GPS_Cellular = "Watch4,3" /// Watch Series 4 42mm (GPS+Cellular) model identifier. case appleWatchSeries4_44mm_GPS_Cellular = "Watch4,4" //MARK: Home Pod /// HomePod model identifier. case homePod_1 = "AudioAccessory1,1" /// HomePod (`¯\_(ツ)_/¯`) model identifier. case homePod_2 = "AudioAccessory1,2" //MARK: iPad /// iPad 2 WiFi model identifier. case iPad_2 = "iPad2,1" /// iPad 2 GSM model identifier. case iPad_2_GSM = "iPad2,2" /// iPad 2 CDMA model identifier. case iPad_2_CDMA = "iPad2,3" /// iPad 2 WiFi (revision 2) model identifier. case iPad_2_2 = "iPad2,4" /// iPad (3rd Generation) WiFi model identifier. case iPad_3rdGeneration = "iPad3,1" /// iPad (3rd Generation) Verizon model identifier. case iPad_3rdGeneration_Verizon = "iPad3,2" /// iPad (3rd Generation) GSM model identifier. case iPad_3rdGeneration_GSM = "iPad3,3" /// iPad (4th Generation) WiFi model identifier. case iPad_4thGeneration = "iPad3,4" /// iPad (4th Generation) CDMA model identifier. case iPad_4thGeneration_CDMA = "iPad3,5" /// iPad (4th Generation) Multi-Modal model identifier. case iPad_4thGeneration_MM = "iPad3,6" /// iPad air WiFi model identifier. case iPadAir = "iPad4,1" /// iPad air GSM model identifier. case iPadAir_GSM = "iPad4,2" /// iPad air LTE model identifier. case iPadAir_TD_LTE = "iPad4,3" /// iPad air 2 WiFi model identifier. case iPadAir_2 = "iPad5,3" /// iPad air 2 Cellular model identifier. case iPadAir_2_Cellular = "iPad5,4" /// iPad Pro 12.9" WiFi model identifier. case iPadPro_12_9_Inch = "iPad6,7" /// iPad Pro 12.9" Cellular model identifier. case iPadPro_12_9_Inch_Cellular = "iPad6,8" /// iPad Pro 9.7" WiFi model identifier. case iPadPro_9_7_Inch = "iPad6,3" /// iPad Pro 9.7" Cellular model identifier. case iPadPro_9_7_Inch_Cellular = "iPad6,4" /// iPad (5th Generation) WiFi model identifier. case iPad_5thGeneration = "iPad6,11" /// iPad (5th Generation) Cellular model identifier. case iPad_5thGeneration_Cellular = "iPad6,12" /// iPad Pro 12.9" (2nd Generation) WiFi model identifier. case iPadPro_12_9_Inch_2ndGeneration = "iPad7,1" /// iPad Pro 12.9" (2nd Generation) Cellular model identifier. case iPadPro_12_9_Inch_2ndGeneration_Cellular = "iPad7,2" /// iPad Pro 10.5" WiFi model identifier. case iPadPro_10_5_Inch = "iPad7,3" /// iPad Pro 10.5" Cellular model identifier. case iPadPro_10_5_Inch_Cellular = "iPad7,4" /// iPad (6th Generation) WiFi model identifier. case iPad_6thGeneration = "iPad7,5" /// iPad (6th Generation) Cellular model identifier. case iPad_6thGeneration_Cellular = "iPad7,6" /// iPad Pro 11" WiFi model identifier. case iPadPro_11_Inch = "iPad8,1" /// iPad Pro 11" WiFi with 1TB model identifier. case iPadPro_11_Inch_1TB = "iPad8,2" /// iPad Pro 11" Cellular model identifier. case iPadPro_11_Inch_Cellular = "iPad8,3" /// iPad Pro 11" Cellular with 1TB model identifier. case iPadPro_11_Inch_1TB_Cellular = "iPad8,4" /// iPad Pro 12.9" (3rd Generation) WiFi model identifier. case iPadPro_12_9_Inch_3rdGeneration = "iPad8,5" /// iPad Pro 12.9" (3rd Generation) WiFi with 1TB model identifier. case iPadPro_12_9_Inch_3rdGeneration_1TB = "iPad8,6" /// iPad Pro 12.9" (3rd Generation) Cellular model identifier. case iPadPro_12_9_Inch_3rdGeneration_Cellular = "iPad8,7" /// iPad Pro 12.9" (3rd Generation) Cellular with 1TB model identifier. case iPadPro_12_9_Inch_3rdGeneration_1TB_Cellular = "iPad8,8" /// iPad mini WiFi model identifier. case iPad_Mini = "iPad2,5" /// iPad mini CDMA model identifier. case iPad_Mini_CDMA = "iPad2,6" /// iPad mini Multi-Modal model identifier. case iPad_Mini_MM = "iPad2,7" /// iPad mini 2 WiFi model identifier. case iPad_Mini_2 = "iPad4,4" /// iPad mini 2 GSM model identifier. case iPad_Mini_2_GSM = "iPad4,5" /// iPad mini 2 LTE model identifier. case iPad_Mini_2_TD_LTE = "iPad4,6" /// iPad mini 3 WiFi model identifier. case iPad_Mini_3 = "iPad4,7" /// iPad mini 3 GSM model identifier. case iPad_Mini_3_GSM = "iPad4,8" /// iPad mini 3 (China) model identifier. case iPad_Mini_3_China = "iPad4,9" /// iPad mini 4 WiFi model identifier. case iPad_Mini_4 = "iPad5,1" /// iPad mini 4 GSM model identifier. case iPad_Mini_4_GSM = "iPad5,2" //MARK: iPhone /// iPhone 4s model identifier. case iPhone4s = "iPhone4,1" /// iPhone 5 model identifier. case iPhone5 = "iPhone5,1" /// iPhone 5 (revision 2) model identifier. case iPhone5_2 = "iPhone5,2" /// iPhone 5c (North America and Japan) model identifier. case iPhone5c_NorthAmerica_Japan = "iPhone5,3" /// iPhone 5c (Europe and Asia) model identifier. case iPhone5c_Europe_Asia = "iPhone5,4" /// iPhone 5s (North America and Japan) model identifier. case iPhone5s_NorthAmerica_Japan = "iPhone6,1" /// iPhone 5s (Europe and Asia) model identifier. case iPhone5s_Europe_Asia = "iPhone6,2" /// iPhone 6 model identifier. case iPhone6 = "iPhone7,2" /// iPhone 6 Plus model identifier. case iPhone6Plus = "iPhone7,1" /// iPhone 6s model identifier. case iPhone6s = "iPhone8,1" /// iPhone 6s Plus model identifier. case iPhone6sPlus = "iPhone8,2" /// iPhone SE model identifier. case iPhoneSE = "iPhone8,4" /// iPhone 7 CDMA model identifier. case iPhone7_CDMA = "iPhone9,1" /// iPhone 7 Global model identifier. case iPhone7_Global = "iPhone9,3" /// iPhone 7 Plust CDMA model identifier. case iPhone7Plus_CDMA = "iPhone9,2" /// iPhone 7 Plus Global model identifier. case iPhone7Plus_Global = "iPhone9,4" /// iPhone 8 model identifier. case iPhone8 = "iPhone10,1" /// iPhone 8 (revision 2) model identifier. case iPhone8_2 = "iPhone10,4" /// iPhone 8 Plus model identifier. case iPhone8Plus = "iPhone10,2" /// iPhone 8 Plus (revision 2) model identifier. case iPhone8Plus_2 = "iPhone10,5" /// iPhone X model identifier. case iPhoneX = "iPhone10,3" /// iPhone X (revision 2) model identifier. case iPhoneX_2 = "iPhone10,6" /// iPhone XR model identifier. case iPhoneXR = "iPhone11,8" /// iPhone XR model identifier. case iPhoneXS = "iPhone11,2" /// iPhone XS Max model identifier. case iPhoneXS_Max = "iPhone11,6" /// iPhone XS Max (China) model identifier. case iPhoneXS_Max_China = "iPhone11,4" //MARK: iPod touch /// iPod touch (5th Generation) model identifier. case iPodTouch_5thGeneration = "iPod5,1" /// iPod touch (6th Generation) model identifier. case iPodTouch_6thGeneration = "iPod7,1" //MARK: MacBook air /// MacBook air 2009 model identifier. case macBookAir_2009 = "MacBookAir2,1" /// MacBook air 11" 2010 model identifier. case macBookAir_11_Inch_2010 = "MacBookAir3,1" /// MacBook air 13" 2010 model identifier. case macBookAir_13_Inch_2010 = "MacBookAir3,2" /// MacBook air 11" 2011 model identifier. case macBookAir_11_Inch_2011 = "MacBookAir4,1" /// MacBook air 13" 2011 model identifier. case macBookAir_13_Inch_2011 = "MacBookAir4,2" /// MacBook air 11" 2012 model identifier. case macBookAir_11_Inch_2012 = "MacBookAir5,1" /// MacBook air 13" 2012 model identifier. case macBookAir_13_Inch_2012 = "MacBookAir5,2" /// MacBook air 11" 2013 model identifier. case macBookAir_11_Inch_2013 = "MacBookAir6,1" /// MacBook air 13" 2013 model identifier. case macBookAir_13_Inch_2013 = "MacBookAir6,2" /// MacBook air 11" 2015 model identifier. case macBookAir_11_Inch_2015 = "MacBookAir7,1" /// MacBook air 13" 2015 model identifier. case macBookAir_13_Inch_2015 = "MacBookAir7,2" //MARK: MacBook /// MacBook (Early 2009) model identifier. case macBook_Early_2009 = "MacBook5,2" /// MacBook (Late 2009) model identifier. case macBook_Late_2009 = "MacBook6,1" /// MacBook 2010 model identifier. case macBook_2010 = "MacBook7,1" /// MacBook 2015 model identifier. case macBook_2015 = "MacBook8,1" /// MacBook 2016 model identifier. case macBook_2016 = "MacBook9,1" /// MacBook 2017 model identifier. case macBook_2017 = "MacBook10,1" //MARK: MacBook Pro /// MacBook Pro (Early 2008) model identifier. case macBookPro_Early_2008 = "MacBookPro4,1" /// MacBook Pro (Late 2008) model identifier. case macBookPro_Late_2008 = "MacBookPro5,1" /// MacBook Pro 13" 2009 model identifier. case macBookPro_13_Inch_2009 = "MacBookPro5,5" /// MacBook Pro 15" 2009 model identifier. case macBookPro_15_Inch_2009 = "MacBookPro5,3" /// MacBook Pro 17" 2009 model identifier. case macBookPro_17_Inch_2009 = "MacBookPro5,2" /// MacBook Pro 13" 2010 model identifier. case macBookPro_13_Inch_2010 = "MacBookPro7,1" /// MacBook Pro 15" 2010 model identifier. case macBookPro_15_Inch_2010 = "MacBookPro6,2" /// MacBook Pro 17" 2010 model identifier. case macBookPro_17_Inch_2010 = "MacBookPro6,1" /// MacBook Pro 13" 2011 model identifier. case macBookPro_13_Inch_2011 = "MacBookPro8,1" /// MacBook Pro 15" 2011 model identifier. case macBookPro_15_Inch_2011 = "MacBookPro8,2" /// MacBook Pro 17" 2011 model identifier. case macBookPro_17_Inch_2011 = "MacBookPro8,3" /// MacBook Pro 13" 2012 model identifier. case macBookPro_13_Inch_2012 = "MacBookPro9,2" /// MacBook Pro 13" Retina 2012 model identifier. case macBookPro_13_Inch_Retina_2012 = "MacBookPro10,2" /// MacBook Pro 15" 2012 model identifier. case macBookPro_15_Inch_2012 = "MacBookPro9,1" /// MacBook Pro 15" Retina 2012 model identifier. case macBookPro_15_Inch_Retina_2012 = "MacBookPro10,1" /// MacBook Pro 13" 2013 model identifier. case macBookPro_13_Inch_2013 = "MacBookPro11,1" /// MacBook Pro 15" 2013 model identifier. case macBookPro_15_Inch_2013 = "MacBookPro11,2" /// MacBook Pro 15" 2013 (revision 2) model identifier. case macBookPro_15_Inch_2013_2 = "MacBookPro11,3" /// MacBook Pro 13" 2015 model identifier. case macBookPro_13_Inch_2015 = "MacBookPro12,1" /// MacBook Pro 15" 2015 model identifier. case macBookPro_15_Inch_2015 = "MacBookPro11,4" /// MacBook Pro 15" 2015 (revision 2) model identifier. case macBookPro_15_Inch_2015_2 = "MacBookPro11,5" /// MacBook Pro 13" (Two Thunderbolt ports) 2016 model identifier. case macBookPro_13_Inch_2_Thunderbolt_2016 = "MacBookPro13,1" /// MacBook Pro 13" (Four Thunderbolt ports) 2016 model identifier. case macBookPro_13_Inch_4_Thunderbolt_2016 = "MacBookPro13,2" /// MacBook Pro 15" 2016 model identifier. case macBookPro_15_Inch_2016 = "MacBookPro13,3" /// MacBook Pro 13" (Two Thunderbolt ports) 2017 model identifier. case macBookPro_13_Inch_2_Thunderbolt_2017 = "MacBookPro14,1" /// MacBook Pro 13" (Four Thunderbolt ports) 2017 model identifier. case macBookPro_13_Inch_4_Thunderbolt_2017 = "MacBookPro14,2" /// MacBook Pro 15" 2017 model identifier. case macBookPro_15_Inch_2017 = "MacBookPro14,3" /// MacBook Pro 13" 2018 model identifier. case macBookPro_13_Inch_2018 = "MacBookPro15,2" /// MacBook Pro 15" 2018 model identifier. case macBookPro_15_Inch_2018 = "MacBookPro15,1" //MARK: Mac mini /// Mac mini 2009 model identifier. case macMini_2009 = "Macmini3,1" /// Mac mini 2010 model identifier. case macMini_2010 = "Macmini4,1" /// Mac mini 2011 model identifier. case macMini_2011 = "Macmini5,1" /// Mac mini 2011 (revision 2) model identifier. case macMini_2011_2 = "Macmini5,2" /// Mac mini 2012 model identifier. case macMini_2012 = "Macmini6,1" /// Mac mini 2012 (revision 2) model identifier. case macMini_2012_2 = "Macmini6,2" /// Mac mini 2014 model identifier. case macMini_2014 = "Macmini7,1" //MARK: iMac /// iMac (Early 2009) model identifier. case iMac_Early_2009 = "iMac9,1" /// iMac (Late 2009) model identifier. case iMac_Late_2009 = "iMac10,1" /// iMac 21.5" 2010 model identifier. case iMac_21_5_Inch_2010 = "iMac11,2" /// iMac 27" 2010 model identifier. case iMac_27_Inch_2010 = "iMac11,3" /// iMac 21.5" 2011 model identifier. case iMac_21_5_Inch_2011 = "iMac12,1" /// iMac 27" 2011 model identifier. case iMac_27_Inch_2011 = "iMac12,2" /// iMac 21.5" 2012 model identifier. case iMac_21_5_Inch_2012 = "iMac13,1" /// iMac 27" 2012 model identifier. case iMac_27_Inch_2012 = "iMac13,2" /// iMac 21.5" 2013 model identifier. case iMac_21_5_Inch_2013 = "iMac14,1" /// iMac 27" 2013 model identifier. case iMac_27_Inch_2013 = "iMac14,2" /// iMac 21.5" 2014 model identifier. case iMac_21_5_Inch_2014 = "iMac14,4" /// iMac 27" 5K 2014 model identifier. case iMac_27_Inch_5K_2014 = "iMac15,1" /// iMac 21.5" 2015 model identifier. case iMac_21_5_Inch_2015 = "iMac16,1" /// iMac 21.5" 4K 2015 model identifier. case iMac_21_5_4K_Inch_2015 = "iMac16,2" /// iMac 27" 5K 2015 model identifier. case iMac_27_Inch_5K_2015 = "iMac17,1" /// iMac 21.5" 2017 model identifier. case iMac_21_5_Inch_2017 = "iMac18,1" /// iMac 21.5" 4K 2017 model identifier. case iMac_21_5_4K_Inch_2017 = "iMac18,2" /// iMac 27" 5K 2017 model identifier. case iMac_27_Inch_5K_2017 = "iMac18,3" //MARK: Mac Pro /// Mac Pro 2009 model identifier. case macPro_2009 = "MacPro4,1" /// Mac Pro 2010 model identifier. case macPro_2010 = "MacPro5,1" /// Mac Pro 2013 model identifier. case macPro_2013 = "MacPro6,1" } } /** Contains information about the current screen available to your app. */ public struct Screen {} /** Contains information about the OS running your app. */ public struct OS {} /** Meta information about your app, mainly reading from Info.plist. */ public struct App {} /** The `Version` struct defines a software version in the format **major.minor.patch (build)**. `Defines` uses it to describe either the OS version or your app's version, according to your Info.plist file. It is particularly useful to compare versions of your app. For example: ```swift let currentVersion = Defines.App.version(forClass: AppDelegate.self) let oldVersion = Defines.Version(versionString: "1.0.0") if currentVersion == oldVersion { //your user is still running an old version of the app //perhaps you want to let them know there's a new one available //or let them know their version will be deprecated soon } ``` */ public struct Version: Equatable, Comparable, CustomStringConvertible { /// The version's major number: **major**.minor.patch (build) public let major: Int /// The version's minor number: major.**minor**.patch (build) public let minor: Int /// The version's patch number: major.minor.**patch** (build) public let patch: Int /// The version's build string: major.minor.patch (**build**) public let build: String /** Creates a new `Version` from a major, a minor and a patch `Int`s and a build `String`. Example: ``` let version = Defines.Version(major: 1, minor: 0, patch: 0, build: "3") print(version) //prints 'Version: 1.0.0 (3)' ``` - parameters: - major: The version's major number. Must be greater than or equal to 0. Defaults to 0. - minor: The version's minor number. Must be greater than or equal to 0. Defaults to 0. - patch: The version's patch number. Must be greater than or equal to 0. Defaults to 0. - build: The version's build string. Defaults to an empty string. */ public init(major: Int = 0, minor: Int = 0, patch: Int = 0, build: String = "") { if major < 0 { self.major = 0 } else { self.major = major } if minor < 0 { self.minor = 0 } else { self.minor = minor } if patch < 0 { self.patch = 0 } else { self.patch = patch } self.build = build } } }
122ef5c798f95804c5f92ce5044153fe
45.779693
139
0.576314
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleVideoCell.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit import VBFPopFlatButton import AVFoundation import YYImage public class AABubbleVideoCell: AABubbleBaseFileCell { // Views let preview = UIImageView() let progress = AAProgressView(size: CGSizeMake(64, 64)) let timeBg = UIImageView() let timeLabel = UILabel() let statusView = UIImageView() let playView = UIImageView(image: UIImage.bundled("aa_playbutton")) // Binded data var bindedLayout: VideoCellLayout! var thumbLoaded = false var contentLoaded = false // Constructors public init(frame: CGRect) { super.init(frame: frame, isFullSize: false) timeBg.image = ActorSDK.sharedActor().style.statusBackgroundImage timeLabel.font = UIFont.italicSystemFontOfSize(11) timeLabel.textColor = appStyle.chatMediaDateColor statusView.contentMode = UIViewContentMode.Center contentView.addSubview(preview) contentView.addSubview(progress) contentView.addSubview(timeBg) contentView.addSubview(timeLabel) contentView.addSubview(statusView) contentView.addSubview(playView) preview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleVideoCell.mediaDidTap))) preview.userInteractionEnabled = true playView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleVideoCell.mediaDidTap))) playView.userInteractionEnabled = true contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Binding public override func bind(message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) { self.bindedLayout = cellLayout as! VideoCellLayout bubbleInsets = UIEdgeInsets( top: setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop, left: 10 + (AADevice.isiPad ? 16 : 0), bottom: setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom, right: 10 + (AADevice.isiPad ? 16 : 0)) if (!reuse) { // Bind bubble if (self.isOut) { bindBubbleType(BubbleType.MediaOut, isCompact: false) } else { bindBubbleType(BubbleType.MediaIn, isCompact: false) } // Reset content state self.preview.image = nil contentLoaded = false thumbLoaded = false // Reset progress self.progress.hideButton() //UIView.animateWithDuration(0, animations: { () -> Void in self.progress.hidden = true self.preview.hidden = true //}) // Bind file fileBind(message, autoDownload: bindedLayout.autoDownload) } // Update time timeLabel.text = cellLayout.date // Update status if (isOut) { statusView.hidden = false switch(message.messageState.toNSEnum()) { case .SENT: if message.sortDate <= readDate { self.statusView.image = appStyle.chatIconCheck2 self.statusView.tintColor = appStyle.chatStatusMediaRead } else if message.sortDate <= receiveDate { self.statusView.image = appStyle.chatIconCheck2 self.statusView.tintColor = appStyle.chatStatusMediaReceived } else { self.statusView.image = appStyle.chatIconCheck1 self.statusView.tintColor = appStyle.chatStatusMediaSent } case .ERROR: self.statusView.image = appStyle.chatIconError self.statusView.tintColor = appStyle.chatStatusMediaError break default: self.statusView.image = appStyle.chatIconClock self.statusView.tintColor = appStyle.chatStatusMediaSending break } } else { statusView.hidden = true } } // File state binding public override func fileUploadPaused(reference: String, selfGeneration: Int) { bgLoadThumb(selfGeneration) bgLoadReference(reference, selfGeneration: selfGeneration) runOnUiThread(selfGeneration) { () -> () in self.progress.showView() self.playView.hideView() self.progress.setButtonType(FlatButtonType.buttonUpBasicType, animated: true) self.progress.hideProgress() } } public override func fileUploading(reference: String, progress: Double, selfGeneration: Int) { bgLoadThumb(selfGeneration) bgLoadReference(reference, selfGeneration: selfGeneration) runOnUiThread(selfGeneration) { () -> () in self.progress.showView() self.playView.hideView() self.progress.setButtonType(FlatButtonType.buttonPausedType, animated: true) self.progress.setProgress(progress) } } public override func fileDownloadPaused(selfGeneration: Int) { bgLoadThumb(selfGeneration) runOnUiThread(selfGeneration) { () -> () in self.progress.showView() self.playView.hideView() self.progress.setButtonType(FlatButtonType.buttonDownloadType, animated: true) self.progress.hideProgress() } } public override func fileDownloading(progress: Double, selfGeneration: Int) { bgLoadThumb(selfGeneration) runOnUiThread(selfGeneration) { () -> () in self.progress.showView() self.playView.hideView() self.progress.setButtonType(FlatButtonType.buttonPausedType, animated: true) self.progress.setProgress(progress) } } public override func fileReady(reference: String, selfGeneration: Int) { bgLoadThumb(selfGeneration) self.bgLoadReference(reference, selfGeneration: selfGeneration) runOnUiThread(selfGeneration) { () -> () in self.progress.setProgress(1) self.progress.hideView() self.playView.showView() } } public func bgLoadThumb(selfGeneration: Int) { if (thumbLoaded) { return } thumbLoaded = true if (bindedLayout.fastThumb != nil) { let loadedThumb = UIImage(data: bindedLayout.fastThumb!)? .imageByBlurLight()! .roundCorners(bindedLayout.screenSize.width, h: bindedLayout.screenSize.height, roundSize: 14) runOnUiThread(selfGeneration,closure: { ()->() in self.setPreviewImage(loadedThumb!, fast: true) }); } } public func bgLoadReference(reference: String, selfGeneration: Int) { let movieAsset = AVAsset(URL: NSURL(fileURLWithPath: CocoaFiles.pathFromDescriptor(reference))) // video asset let imageGenerator = AVAssetImageGenerator(asset: movieAsset) var thumbnailTime = movieAsset.duration thumbnailTime.value = 25 do { let imageRef = try imageGenerator.copyCGImageAtTime(thumbnailTime, actualTime: nil) var thumbnail = UIImage(CGImage: imageRef) let orientation = movieAsset.videoOrientation() if (orientation.orientation.isPortrait) == true { thumbnail = thumbnail.imageRotatedByDegrees(90, flip: false) } let loadedContent = thumbnail.roundCorners(self.bindedLayout.screenSize.width, h: self.bindedLayout.screenSize.height, roundSize: 14) runOnUiThread(selfGeneration, closure: { () -> () in self.setPreviewImage(loadedContent, fast: false) self.contentLoaded = true }) } catch { } } public func setPreviewImage(img: UIImage, fast: Bool){ if ((fast && self.preview.image == nil) || !fast) { self.preview.image = img self.preview.showView() } } // Media Action public func mediaDidTap() { let content = bindedMessage!.content as! ACDocumentContent if let fileSource = content.getSource() as? ACFileRemoteSource { Actor.requestStateWithFileId(fileSource.getFileReference().getFileId(), withCallback: AAFileCallback( notDownloaded: { () -> () in Actor.startDownloadingWithReference(fileSource.getFileReference()) }, onDownloading: { (progress) -> () in Actor.cancelDownloadingWithFileId(fileSource.getFileReference().getFileId()) }, onDownloaded: { (reference) -> () in self.controller.playVideoFromPath(CocoaFiles.pathFromDescriptor(reference)) })) } else if let fileSource = content.getSource() as? ACFileLocalSource { let rid = bindedMessage!.rid Actor.requestUploadStateWithRid(rid, withCallback: AAUploadFileCallback( notUploaded: { () -> () in Actor.resumeUploadWithRid(rid) }, onUploading: { (progress) -> () in Actor.pauseUploadWithRid(rid) }, onUploadedClosure: { () -> () in self.controller.playVideoFromPath(CocoaFiles.pathFromDescriptor(CocoaFiles.pathFromDescriptor(fileSource.getFileDescriptor()))) })) } } // Layouting public override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { let insets = fullContentInsets let contentWidth = self.contentView.frame.width _ = self.contentView.frame.height let bubbleWidth = self.bindedLayout.screenSize.width let bubbleHeight = self.bindedLayout.screenSize.height layoutBubble(bubbleWidth, contentHeight: bubbleHeight) if (isOut) { preview.frame = CGRectMake(contentWidth - insets.left - bubbleWidth, insets.top, bubbleWidth, bubbleHeight) } else { preview.frame = CGRectMake(insets.left, insets.top, bubbleWidth, bubbleHeight) } progress.frame = CGRectMake(preview.frame.origin.x + preview.frame.width/2 - 32, preview.frame.origin.y + preview.frame.height/2 - 32, 64, 64) playView.frame = progress.frame timeLabel.frame = CGRectMake(0, 0, 1000, 1000) timeLabel.sizeToFit() let timeWidth = (isOut ? 23 : 0) + timeLabel.bounds.width let timeHeight: CGFloat = 20 timeLabel.frame = CGRectMake(preview.frame.maxX - timeWidth - 18, preview.frame.maxY - timeHeight - 6, timeLabel.frame.width, timeHeight) if (isOut) { statusView.frame = CGRectMake(timeLabel.frame.maxX, timeLabel.frame.minY, 23, timeHeight) } timeBg.frame = CGRectMake(timeLabel.frame.minX - 4, timeLabel.frame.minY - 1, timeWidth + 8, timeHeight + 2) } } public class VideoCellLayout: AACellLayout { public let fastThumb: NSData? public let contentSize: CGSize public let screenSize: CGSize public let autoDownload: Bool /** Creting layout for media bubble */ public init(id: Int64, width: CGFloat, height:CGFloat, date: Int64, fastThumb: ACFastThumb?, autoDownload: Bool, layouter: AABubbleLayouter) { // Saving content size self.contentSize = CGSizeMake(width, height) // Saving autodownload flag self.autoDownload = autoDownload // Calculating bubble screen size let scaleW = 240 / width let scaleH = 240 / height let scale = min(scaleW, scaleH) self.screenSize = CGSize(width: scale * width, height: scale * height) // Prepare fast thumb print("video thumb === \(fastThumb?.getImage().toNSData())") self.fastThumb = fastThumb?.getImage().toNSData() // Creating layout super.init(height: self.screenSize.height + 2, date: date, key: "media", layouter: layouter) } /** Creating layout for video content */ public convenience init(id: Int64, videoContent: ACVideoContent, date: Int64, layouter: AABubbleLayouter) { self.init(id: id, width: CGFloat(videoContent.getW()), height: CGFloat(videoContent.getH()), date: date, fastThumb: videoContent.getFastThumb(), autoDownload: false, layouter: layouter) } /** Creating layout for message */ public convenience init(message: ACMessage, layouter: AABubbleLayouter) { if let content = message.content as? ACVideoContent { self.init(id: Int64(message.rid), videoContent: content, date: Int64(message.date), layouter: layouter) } else { fatalError("Unsupported content for media cell") } } } public class AABubbleVideoCellLayouter: AABubbleLayouter { public func isSuitable(message: ACMessage) -> Bool { if message.content is ACVideoContent { return true } return false } public func buildLayout(peer: ACPeer, message: ACMessage) -> AACellLayout { return VideoCellLayout(message: message, layouter: self) } public func cellClass() -> AnyClass { return AABubbleVideoCell.self } }
6c557f07fdd528e8ccb2d2813b90202f
35.715762
193
0.598536
false
false
false
false
thelukester92/swift-engine
refs/heads/master
swift-engine/Engine/Components/LGPhysicsBody.swift
mit
1
// // LGPhysicsBody.swift // swift-engine // // Created by Luke Godfrey on 6/7/14. // Copyright (c) 2014 Luke Godfrey. See LICENSE. // import SpriteKit public final class LGPhysicsBody: LGComponent { public class func type() -> String { return "LGPhysicsBody" } public func type() -> String { return LGPhysicsBody.type() } public var velocity = LGVector() public var width: Double public var height: Double public var dynamic: Bool public var trigger = false // TODO: allow other kinds of directional collisions public var onlyCollidesVertically = false public var collidedTop = false public var collidedBottom = false public var collidedLeft = false public var collidedRight = false public var collidedWith = [Int:LGEntity]() public init(width: Double, height: Double, dynamic: Bool = true) { self.width = width self.height = height self.dynamic = dynamic } public convenience init(size: LGVector, dynamic: Bool = true) { self.init(width: size.x, height: size.y, dynamic: dynamic) } public convenience init() { self.init(width: 0, height: 0) } } extension LGPhysicsBody: LGDeserializable { public class var requiredProps: [String] { return [ "width", "height" ] } public class var optionalProps: [String] { return [ "dynamic", "onlyCollidesVertically", "trigger", "velocity" ] } public class func instantiate() -> LGDeserializable { return LGPhysicsBody() } public func setValue(value: LGJSON, forKey key: String) -> Bool { switch key { case "width": width = value.doubleValue! return true case "height": height = value.doubleValue! return true case "dynamic": dynamic = value.boolValue! return true case "onlyCollidesVertically": onlyCollidesVertically = value.boolValue! return true case "trigger": trigger = value.boolValue! return true case "velocity": if let x = value["x"]?.doubleValue { velocity.x = x } if let y = value["y"]?.doubleValue { velocity.y = y } return true default: break } return false } public func valueForKey(key: String) -> LGJSON { return LGJSON(value: nil) } }
3ab2b13999780e8c8a9620ef77aba662
17.203252
71
0.660116
false
false
false
false
adrianomazucato/CoreStore
refs/heads/master
CoreStore/Convenience Helpers/NSProgress+Convenience.swift
mit
2
// // NSProgress+Convenience.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import GCDKit // MARK: - NSProgress public extension NSProgress { // MARK: Public /** Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO. - parameter closure: the closure to execute on progress change */ public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) { self.progressObserver.progressHandler = closure } // MARK: Private private struct PropertyKeys { static var progressObserver: Void? } private var progressObserver: ProgressObserver { get { let object: ProgressObserver? = getAssociatedObjectForKey(&PropertyKeys.progressObserver, inObject: self) if let observer = object { return observer } let observer = ProgressObserver(self) setAssociatedRetainedObject( observer, forKey: &PropertyKeys.progressObserver, inObject: self ) return observer } } } @objc private final class ProgressObserver: NSObject { private unowned let progress: NSProgress private var progressHandler: ((progress: NSProgress) -> Void)? { didSet { let progressHandler = self.progressHandler if (progressHandler == nil) == (oldValue == nil) { return } if let _ = progressHandler { self.progress.addObserver( self, forKeyPath: "fractionCompleted", options: [.Initial, .New], context: nil ) } else { self.progress.removeObserver(self, forKeyPath: "fractionCompleted") } } } private init(_ progress: NSProgress) { self.progress = progress super.init() } deinit { if let _ = self.progressHandler { self.progressHandler = nil self.progress.removeObserver(self, forKeyPath: "fractionCompleted") } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard let progress = object as? NSProgress where progress == self.progress && keyPath == "fractionCompleted" else { return } GCDQueue.Main.async { [weak self] () -> Void in self?.progressHandler?(progress: progress) } } }
baa4e3e64e208050af9d08c2039cb657
29.848485
157
0.589145
false
false
false
false
pkrawat1/TravelApp-ios
refs/heads/master
TravelApp/Helpers/Extensions.swift
mit
1
// // Extensions .swift // YoutubeClone // // Created by Pankaj Rawat on 20/01/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit import SwiftDate extension UIColor { static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha) } static func appBaseColor() -> UIColor { return rgb(red: 44, green: 62, blue: 80) } static func appCallToActionColor() -> UIColor { return rgb(red: 231, green: 76, blue: 60) } static func appMainBGColor() -> UIColor { return rgb(red: 236, green: 240, blue: 241) } static func appLightBlue() -> UIColor { return rgb(red: 52, green: 152, blue: 219) } static func appDarkBlue() -> UIColor { return rgb(red: 41, green: 128, blue: 185) } } extension UIView { func addConstraintsWithFormat(format: String, views: UIView...){ var viewsDictionary = [String: UIView]() for(index, view) in views.enumerated() { let key = "v\(index)" view.translatesAutoresizingMaskIntoConstraints = false viewsDictionary[key] = view } addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary)) } func addBackground(imageName: String) { // screen width and height: let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height)) imageViewBackground.image = UIImage(named: imageName) // you can change the content mode: imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.addSubview(imageViewBackground) self.sendSubview(toBack: imageViewBackground) } } let imageCache = NSCache<AnyObject, AnyObject>() class CustomImageView: UIImageView { var imageUrlString: String? func loadImageUsingUrlString(urlString: String, width: Float) { // Change width of image var urlString = urlString let regex = try! NSRegularExpression(pattern: "upload", options: NSRegularExpression.Options.caseInsensitive) let range = NSMakeRange(0, urlString.characters.count) urlString = regex.stringByReplacingMatches(in: urlString, options: [], range: range, withTemplate: "upload/w_\(Int(width * 1.5))") imageUrlString = urlString image = nil backgroundColor = UIColor.gray let url = NSURL(string: urlString) let configuration = URLSessionConfiguration.default let urlRequest = URLRequest(url: url as! URL) let session = URLSession(configuration: configuration) if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage { self.image = imageFromCache return } session.dataTask(with: urlRequest) { (data, response, error) -> Void in if (error != nil) { print(error!) return } else { DispatchQueue.main.async { let imageToCache = UIImage(data: data!) if self.imageUrlString == urlString { self.image = imageToCache } if imageToCache != nil { imageCache.setObject(imageToCache!, forKey: urlString as AnyObject) } } return } }.resume() } } //MARK: - UITextView extension UITextView{ func numberOfLines() -> Int{ if let fontUnwrapped = self.font{ return Int(self.contentSize.height / fontUnwrapped.lineHeight) } return 0 } } extension String { func humanizeDate(format: String = "MM-dd-yyyy HH:mm:ss") -> String { //"yyyy-MM-dd'T'HH:mm:ss.SSSZ" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" dateFormatter.locale = Locale.init(identifier: "en_GB") let dateObj = dateFormatter.date(from: self) dateFormatter.dateFormat = format return dateFormatter.string(from: dateObj!) } func relativeDate() -> String { let date = try! DateInRegion(string: humanizeDate(), format: .custom("MM-dd-yyyy HH:mm:ss")) let relevantTime = try! date.colloquialSinceNow().colloquial return relevantTime } } extension CreateTripController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func handleSelectTripImage() { let picker = UIImagePickerController() picker.delegate = self present(picker, animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let imagePicked = info["UIImagePickerControllerOriginalImage"] as? UIImage { self.tripEditForm.thumbnailImageView.image = imagePicked statusBarBackgroundView.alpha = 0 } dismiss(animated: true, completion: nil) } }
4c96149561fb73d18dffa0aecba1640a
32.20904
152
0.585403
false
false
false
false
gmilos/swift
refs/heads/master
test/stdlib/TestIndexPath.swift
apache-2.0
2
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation #if FOUNDATION_XCTEST import XCTest class TestIndexPathSuper : XCTestCase { } #else import StdlibUnittest class TestIndexPathSuper { } #endif class TestIndexPath : TestIndexPathSuper { func testBasics() { let ip = IndexPath(index: 1) expectEqual(ip.count, 1) } func testAppending() { var ip : IndexPath = [1, 2, 3, 4] let ip2 = IndexPath(indexes: [5, 6, 7]) ip.append(ip2) expectEqual(ip.count, 7) expectEqual(ip[0], 1) expectEqual(ip[6], 7) } func testRanges() { let ip1 = IndexPath(indexes: [1, 2, 3]) let ip2 = IndexPath(indexes: [6, 7, 8]) // Replace the whole range var mutateMe = ip1 mutateMe[0..<3] = ip2 expectEqual(mutateMe, ip2) // Insert at the beginning mutateMe = ip1 mutateMe[0..<0] = ip2 expectEqual(mutateMe, IndexPath(indexes: [6, 7, 8, 1, 2, 3])) // Insert at the end mutateMe = ip1 mutateMe[3..<3] = ip2 expectEqual(mutateMe, IndexPath(indexes: [1, 2, 3, 6, 7, 8])) // Insert in middle mutateMe = ip1 mutateMe[2..<2] = ip2 expectEqual(mutateMe, IndexPath(indexes: [1, 2, 6, 7, 8, 3])) } func testMoreRanges() { var ip = IndexPath(indexes: [1, 2, 3]) let ip2 = IndexPath(indexes: [5, 6, 7, 8, 9, 10]) ip[1..<2] = ip2 expectEqual(ip, IndexPath(indexes: [1, 5, 6, 7, 8, 9, 10, 3])) } func testIteration() { let ip = IndexPath(indexes: [1, 2, 3]) var count = 0 for _ in ip { count += 1 } expectEqual(3, count) } func test_AnyHashableContainingIndexPath() { let values: [IndexPath] = [ IndexPath(indexes: [1, 2]), IndexPath(indexes: [1, 2, 3]), IndexPath(indexes: [1, 2, 3]), ] let anyHashables = values.map(AnyHashable.init) expectEqual(IndexPath.self, type(of: anyHashables[0].base)) expectEqual(IndexPath.self, type(of: anyHashables[1].base)) expectEqual(IndexPath.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } func test_AnyHashableCreatedFromNSIndexPath() { let values: [NSIndexPath] = [ NSIndexPath(index: 1), NSIndexPath(index: 2), NSIndexPath(index: 2), ] let anyHashables = values.map(AnyHashable.init) expectEqual(IndexPath.self, type(of: anyHashables[0].base)) expectEqual(IndexPath.self, type(of: anyHashables[1].base)) expectEqual(IndexPath.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } // TODO: Test bridging } #if !FOUNDATION_XCTEST var IndexPathTests = TestSuite("TestIndexPath") IndexPathTests.test("testBasics") { TestIndexPath().testBasics() } IndexPathTests.test("testAppending") { TestIndexPath().testAppending() } IndexPathTests.test("testRanges") { TestIndexPath().testRanges() } IndexPathTests.test("testMoreRanges") { TestIndexPath().testMoreRanges() } IndexPathTests.test("testIteration") { TestIndexPath().testIteration() } IndexPathTests.test("test_AnyHashableContainingIndexPath") { TestIndexPath().test_AnyHashableContainingIndexPath() } IndexPathTests.test("test_AnyHashableCreatedFromNSIndexPath") { TestIndexPath().test_AnyHashableCreatedFromNSIndexPath() } runAllTests() #endif
44b184b543bcdedfeca1eefb311bef9d
31.453125
122
0.601348
false
true
false
false
icanzilb/Languages
refs/heads/master
3-Lab/Languages-3/Languages/ViewController.swift
mit
1
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit // MARK: constants let kDeselectedDetailsText = "Managing to fluently transmit your thoughts and have daily conversations" let kSelectedDetailsText = "Excercises: 67%\nConversations: 50%\nDaily streak: 4\nCurrent grade: B" // MARK: - ViewController class ViewController: UIViewController { @IBOutlet var speakingTrailing: NSLayoutConstraint! // MARK: IB outlets @IBOutlet var speakingDetails: UILabel! @IBOutlet var understandingImage: UIImageView! @IBOutlet var readingImage: UIImageView! @IBOutlet var speakingView: UIView! @IBOutlet var understandingView: UIView! @IBOutlet var readingView: UIView! // MARK: class properties var views: [UIView]! var selectedView: UIView? var deselectCurrentView: (()->())? // MARK: - view controller methods override func viewDidLoad() { super.viewDidLoad() views = [speakingView, readingView, understandingView] let speakingTap = UITapGestureRecognizer(target: self, action: Selector("toggleSpeaking:")) speakingView.addGestureRecognizer(speakingTap) let readingTap = UITapGestureRecognizer(target: self, action: Selector("toggleReading:")) readingView.addGestureRecognizer(readingTap) let understandingTap = UITapGestureRecognizer(target: self, action: Selector("toggleView:")) understandingView.addGestureRecognizer(understandingTap) } // MARK: - auto layout animation func adjustHeights(viewToSelect: UIView, shouldSelect: Bool) { println("tapped: \(viewToSelect) select: \(shouldSelect)") var newConstraints: [NSLayoutConstraint] = [] for constraint in viewToSelect.superview!.constraints() as [NSLayoutConstraint] { if contains(views, constraint.firstItem as UIView) && constraint.firstAttribute == .Height { println("height constraint found") NSLayoutConstraint.deactivateConstraints([constraint]) var multiplier: CGFloat = 0.34 if shouldSelect { multiplier = (viewToSelect == constraint.firstItem as UIView) ? 0.55 : 0.23 } let con = NSLayoutConstraint( item: constraint.firstItem, attribute: .Height, relatedBy: .Equal, toItem: (constraint.firstItem as UIView).superview!, attribute: .Height, multiplier: multiplier, constant: 0.0) newConstraints.append(con) } } NSLayoutConstraint.activateConstraints(newConstraints) } // deselects any selected views and selects the tapped view func toggleView(tap: UITapGestureRecognizer) { let wasSelected = selectedView==tap.view! adjustHeights(tap.view!, shouldSelect: !wasSelected) selectedView = wasSelected ? nil : tap.view! if !wasSelected { UIView.animateWithDuration(1.0, delay: 0.00, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .CurveEaseIn | .AllowUserInteraction | .BeginFromCurrentState, animations: { self.deselectCurrentView?() self.deselectCurrentView = nil }, completion: nil) } UIView.animateWithDuration(1.0, delay: 0.00, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .CurveEaseIn | .AllowUserInteraction | .BeginFromCurrentState, animations: { self.view.layoutIfNeeded() }, completion: nil) } //speaking func updateSpeakingDetails(#selected: Bool) { speakingDetails.text = selected ? kSelectedDetailsText : kDeselectedDetailsText for constraint in speakingDetails.superview!.constraints() as [NSLayoutConstraint] { if constraint.firstItem as UIView == speakingDetails && constraint.firstAttribute == .Leading { constraint.constant = -view.frame.size.width/2 speakingView.layoutIfNeeded() UIView.animateWithDuration(0.5, delay: 0.1, options: .CurveEaseOut, animations: { constraint.constant = 0.0 self.speakingView.layoutIfNeeded() }, completion: nil) break } } } func toggleSpeaking(tap: UITapGestureRecognizer) { toggleView(tap) let isSelected = (selectedView==tap.view!) UIView.animateWithDuration(1.0, delay: 0.00, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .CurveEaseIn, animations: { self.speakingTrailing.constant = isSelected ? self.speakingView.frame.size.width/2.0 : 0.0 self.updateSpeakingDetails(selected: isSelected) }, completion: nil) deselectCurrentView = { self.speakingTrailing.constant = 0.0 self.updateSpeakingDetails(selected: false) } } //reading func toggleReading(tap: UITapGestureRecognizer) { toggleView(tap) let isSelected = (selectedView==tap.view!) toggleReadingImageSize(readingImage, isSelected: isSelected) UIView.animateWithDuration(0.5, delay: 0.1, options: .CurveEaseOut, animations: { self.readingView.layoutIfNeeded() }, completion: nil) deselectCurrentView = { self.toggleReadingImageSize(self.readingImage, isSelected: false) } } func toggleReadingImageSize(imageView: UIImageView, isSelected: Bool) { for constraint in imageView.superview!.constraints() as [NSLayoutConstraint] { if constraint.firstItem as UIView == imageView && constraint.firstAttribute == .Height { NSLayoutConstraint.deactivateConstraints([constraint]) let con = NSLayoutConstraint( item: constraint.firstItem, attribute: .Height, relatedBy: .Equal, toItem: (constraint.firstItem as UIView).superview!, attribute: .Height, multiplier: isSelected ? 0.33 : 0.67, constant: 0.0) con.active = true } } } }
e90c806dc9fd27624ce1476b37169302
33.066986
103
0.676404
false
false
false
false
cbguder/CBGPromise
refs/heads/master
Tests/CBGPromiseTests/PromiseTests.swift
mit
1
import Dispatch import XCTest import CBGPromise class PromiseTests: XCTestCase { var subject: Promise<String>! override func setUp() { subject = Promise<String>() } func testCallbackBlockRegisteredBeforeResolution() { var result: String! subject.future.then { r in result = r } subject.resolve("My Special Value") XCTAssertEqual(result, "My Special Value") } func testCallbackBlockRegisteredAfterResolution() { var result: String! subject.resolve("My Special Value") subject.future.then { r in result = r } XCTAssertEqual(result, "My Special Value") } func testValueAccessAfterResolution() { subject.resolve("My Special Value") XCTAssertEqual(subject.future.value, "My Special Value") } func testWaitingForResolution() { let queue = DispatchQueue(label: "test") queue.asyncAfter(deadline: DispatchTime.now() + .milliseconds(100)) { self.subject.resolve("My Special Value") } let receivedValue = subject.future.wait() XCTAssertEqual(subject.future.value, "My Special Value") XCTAssertEqual(receivedValue, subject.future.value) } func testMultipleCallbacks() { var valA: String? var valB: String? subject.future.then { v in valA = v } subject.future.then { v in valB = v } subject.resolve("My Special Value") XCTAssertEqual(valA, "My Special Value") XCTAssertEqual(valB, "My Special Value") } func testMapReturnsNewFuture() { var mappedValue: Int? let mappedFuture = subject.future.map { str -> Int? in return Int(str) } mappedFuture.then { num in mappedValue = num } subject.resolve("123") XCTAssertEqual(mappedValue, 123) } func testMapAllowsChaining() { var mappedValue: Int? let mappedPromise = Promise<Int>() let mappedFuture = subject.future.map { str -> Future<Int> in return mappedPromise.future } mappedFuture.then { num in mappedValue = num } subject.resolve("Irrelevant") mappedPromise.resolve(123) XCTAssertEqual(mappedValue, 123) } func testWhenWaitsUntilResolution() { let firstPromise = Promise<String>() let secondPromise = Promise<String>() let receivedFuture = Promise<String>.when([firstPromise.future, secondPromise.future]) XCTAssertNil(receivedFuture.value) firstPromise.resolve("hello") XCTAssertNil(receivedFuture.value) secondPromise.resolve("goodbye") XCTAssertEqual(receivedFuture.value, ["hello", "goodbye"]) } func testWhenPreservesOrder() { let firstPromise = Promise<String>() let secondPromise = Promise<String>() let receivedFuture = Promise<String>.when([firstPromise.future, secondPromise.future]) secondPromise.resolve("goodbye") firstPromise.resolve("hello") XCTAssertEqual(receivedFuture.value, ["hello", "goodbye"]) } }
dc90a2a534b6071009cc64958cbdba91
23.906977
94
0.619048
false
true
false
false
ByteriX/BxTextField
refs/heads/master
BxTextFieldTests/BxTextFieldPlaceholderTests.swift
mit
1
// // BxTextFieldPlaceholderTests.swift // BxTextFieldTests // // Created by Sergey Balalaev on 16/05/2018. // Copyright © 2018 Byterix. All rights reserved. // import XCTest @testable import BxTextField class BxTextFieldPlaceholderTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testPlaceholderWithPatterns() { let textField = BxTextField(frame: CGRect(x: 0, y: 0, width: 200, height: 40)) textField.leftPatternText = "www." textField.rightPatternText = ".byterix.com" textField.placeholderText = "domain" textField.isPlaceholderPatternShown = true XCTAssertEqual(textField.placeholder!, "www.domain.byterix.com") XCTAssertEqual(textField.enteredText, "") XCTAssertEqual(textField.text!, "") textField.enteredText = "mail" XCTAssertEqual(textField.placeholder!, "www.domain.byterix.com") XCTAssertEqual(textField.enteredText, "mail") XCTAssertEqual(textField.text!, "www.mail.byterix.com") } func testPlaceholderWithoutPatterns() { let textField = BxTextField(frame: CGRect(x: 0, y: 0, width: 200, height: 40)) textField.leftPatternText = "www." textField.rightPatternText = ".byterix.com" textField.placeholderText = "domain" textField.isPlaceholderPatternShown = false XCTAssertEqual(textField.placeholder!, "domain") XCTAssertEqual(textField.enteredText, "") XCTAssertEqual(textField.text!, "") textField.enteredText = "mail" XCTAssertEqual(textField.placeholder!, "domain") XCTAssertEqual(textField.enteredText, "mail") XCTAssertEqual(textField.text!, "www.mail.byterix.com") } }
bdd00925d072a9c096243477a9a2c14d
37.415094
111
0.673379
false
true
false
false
Dhimanswadia/TipCalculator
refs/heads/master
tips/ViewController.swift
apache-2.0
1
// // ViewController.swift // tips // // Created by Dhiman on 12/14/15. // Copyright © 2015 Dhiman. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var billField: UITextField! @IBOutlet var tipControl: UISegmentedControl! @IBOutlet var totalLabel: UILabel! @IBOutlet var tipLabel: UILabel! var DefaultSegments = [20, 22, 25] var tipPercentagese: [Double] = [0.0, 0.0, 0.0] var tip: Double = 0.0 var total: Double = 0.0 override func viewDidLoad() { super.viewDidLoad() let defaults = NSUserDefaults.standardUserDefaults() if((defaults.objectForKey("tipPercentageSE")) != nil) { tipPercentagese = defaults.objectForKey("tipPercentageSE") as! [Double] } else { for var i = 0; i < DefaultSegments.count; ++i { tipPercentagese[i] = Double(DefaultSegments[i]) } } let segments = tipPercentagese for var index = 0; index < tipControl.numberOfSegments; ++index { tipControl.setTitle("\(Int(segments[index]))%", forSegmentAtIndex: index) } billField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func OnEditingChanged (sender: AnyObject) { let tpercentage = tipControl.selectedSegmentIndex let tipPercentages = Double(tipPercentagese[tpercentage]) let billAmount = billField.text!._bridgeToObjectiveC().doubleValue let tip = billAmount * (tipPercentages * 0.01) let total = billAmount + tip tipLabel.text = "$\(tip)" totalLabel.text = "$\(total)" tipLabel.text = String(format: "$%.2f",tip) totalLabel.text = String(format: "$%.2f",total) } @IBAction func OnTap(sender: AnyObject) { view.endEditing(true) } }
c427265b702eca8844eaa80988a5fb59
26.948718
85
0.569725
false
false
false
false
daisysomus/swift-algorithm-club
refs/heads/master
Minimum Spanning Tree/MinimumSpanningTree.playground/Sources/Graph.swift
mit
1
// Undirected edge public struct Edge<T>: CustomStringConvertible { public let vertex1: T public let vertex2: T public let weight: Int public var description: String { return "[\(vertex1)-\(vertex2), \(weight)]" } } // Undirected weighted graph public struct Graph<T: Hashable>: CustomStringConvertible { public private(set) var edgeList: [Edge<T>] public private(set) var vertices: Set<T> public private(set) var adjList: [T: [(vertex: T, weight: Int)]] public init() { edgeList = [Edge<T>]() vertices = Set<T>() adjList = [T: [(vertex: T, weight: Int)]]() } public var description: String { var description = "" for edge in edgeList { description += edge.description + "\n" } return description } public mutating func addEdge(vertex1 v1: T, vertex2 v2: T, weight w: Int) { edgeList.append(Edge(vertex1: v1, vertex2: v2, weight: w)) vertices.insert(v1) vertices.insert(v2) adjList[v1] = adjList[v1] ?? [] adjList[v1]?.append((vertex: v2, weight: w)) adjList[v2] = adjList[v2] ?? [] adjList[v2]?.append((vertex: v1, weight: w)) } public mutating func addEdge(_ edge: Edge<T>) { addEdge(vertex1: edge.vertex1, vertex2: edge.vertex2, weight: edge.weight) } }
ecd1ef7bf43ec891297a41ba3f57ea65
24.4
78
0.641732
false
false
false
false
coderLL/DYTV
refs/heads/master
DYTV/DYTV/Classes/Home/Controller/HomeViewController.swift
mit
1
// // HomeViewController.swift // DYTV // // Created by coderLL on 16/9/16. // Copyright © 2016年 coderLL. All rights reserved. // import UIKit // MARK:- 常量定义 private let kTitleViewH: CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 fileprivate lazy var pageTitleView: PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() fileprivate lazy var pageContentView: PageContentView = {[weak self] in // 1.确定内容的frame let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) // 2.确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) childVcs.append(GameViewController()) childVcs.append(AmuseViewController()) childVcs.append(FunnyViewController()) let pageContentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) pageContentView.delegate = self return pageContentView }() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置UI界面 setupUI() } } // MARK:- 设置UI界面 extension HomeViewController { fileprivate func setupUI() { // 0.不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false // 1.设置导航栏 setupNavigationBar() // 2.添加TitltView view.addSubview(pageTitleView) // 3.添加contentView view.addSubview(pageContentView) } fileprivate func setupNavigationBar() { // 1.设置左侧的Item navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIImageView(image: UIImage(named: "logo"))) // 2.设置右侧的Item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } } // MARK:- 遵守PageTitleViewDelegate协议 extension HomeViewController : PageTitleViewDelegate { func pageTitltView(_ titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(index) } } // MARK:- 遵守PageContentViewDelegate extension HomeViewController : PageContentViewDelegate { func pageContentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
909e8be230599093d4a5fd39608c5227
32.122449
125
0.664202
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Tracks+ShareExtension.swift
gpl-2.0
1
import Foundation /// This extension implements helper tracking methods, meant for Share Extension Usage. /// extension Tracks { // MARK: - Public Methods public func trackExtensionLaunched(_ wpcomAvailable: Bool) { let properties = ["is_configured_dotcom": wpcomAvailable] trackExtensionEvent(.launched, properties: properties as [String: AnyObject]?) } public func trackExtensionPosted(_ status: String) { let properties = ["post_status": status] trackExtensionEvent(.posted, properties: properties as [String: AnyObject]?) } public func trackExtensionError(_ error: NSError) { let properties = ["error_code": String(error.code), "error_domain": error.domain, "error_description": error.description] trackExtensionEvent(.error, properties: properties as [String: AnyObject]?) } public func trackExtensionCancelled() { trackExtensionEvent(.canceled) } public func trackExtensionTagsOpened() { trackExtensionEvent(.tagsOpened) } public func trackExtensionTagsSelected(_ tags: String) { let properties = ["selected_tags": tags] trackExtensionEvent(.tagsSelected, properties: properties as [String: AnyObject]?) } public func trackExtensionCategoriesOpened() { trackExtensionEvent(.categoriesOpened) } public func trackExtensionCategoriesSelected(_ categories: String) { let properties = ["categories_tags": categories] trackExtensionEvent(.categoriesSelected, properties: properties as [String: AnyObject]?) } // MARK: - Private Helpers fileprivate func trackExtensionEvent(_ event: ExtensionEvents, properties: [String: AnyObject]? = nil) { track(event.rawValue, properties: properties) } // MARK: - Private Enums fileprivate enum ExtensionEvents: String { case launched = "wpios_share_extension_launched" case posted = "wpios_share_extension_posted" case tagsOpened = "wpios_share_extension_tags_opened" case tagsSelected = "wpios_share_extension_tags_selected" case canceled = "wpios_share_extension_canceled" case error = "wpios_share_extension_error" case categoriesOpened = "wpios_share_extension_categories_opened" case categoriesSelected = "wpios_share_extension_categories_selected" } }
767827d64593f8d168444964112e39da
36.71875
129
0.68517
false
false
false
false
exponent/exponent
refs/heads/master
ios/vendored/unversioned/@stripe/stripe-react-native/ios/CardFormView.swift
bsd-3-clause
2
import Foundation import UIKit import Stripe class CardFormView: UIView, STPCardFormViewDelegate { public var cardForm: STPCardFormView? public var cardParams: STPPaymentMethodCardParams? = nil @objc var dangerouslyGetFullCardDetails: Bool = false @objc var onFormComplete: RCTDirectEventBlock? @objc var autofocus: Bool = false @objc var isUserInteractionEnabledValue: Bool = true override func didSetProps(_ changedProps: [String]!) { if let cardForm = self.cardForm { cardForm.removeFromSuperview() } let style = self.cardStyle["type"] as? String == "borderless" ? STPCardFormViewStyle.borderless : STPCardFormViewStyle.standard let _cardForm = STPCardFormView(style: style) _cardForm.delegate = self // _cardForm.isUserInteractionEnabled = isUserInteractionEnabledValue if autofocus == true { let _ = _cardForm.becomeFirstResponder() } self.cardForm = _cardForm self.addSubview(_cardForm) setStyles() } @objc var cardStyle: NSDictionary = NSDictionary() { didSet { setStyles() } } func cardFormView(_ form: STPCardFormView, didChangeToStateComplete complete: Bool) { if onFormComplete != nil { let brand = STPCardValidator.brand(forNumber: cardForm?.cardParams?.card?.number ?? "") var cardData: [String: Any?] = [ "expiryMonth": cardForm?.cardParams?.card?.expMonth ?? NSNull(), "expiryYear": cardForm?.cardParams?.card?.expYear ?? NSNull(), "complete": complete, "brand": Mappers.mapCardBrand(brand) ?? NSNull(), "last4": cardForm?.cardParams?.card?.last4 ?? "", "postalCode": cardForm?.cardParams?.billingDetails?.address?.postalCode ?? "", "country": cardForm?.cardParams?.billingDetails?.address?.country ] if (dangerouslyGetFullCardDetails) { cardData["number"] = cardForm?.cardParams?.card?.number ?? "" } if (complete) { self.cardParams = cardForm?.cardParams?.card } else { self.cardParams = nil } onFormComplete!(cardData as [AnyHashable : Any]) } } func focus() { let _ = cardForm?.becomeFirstResponder() } func blur() { let _ = cardForm?.resignFirstResponder() } func setStyles() { if let backgroundColor = cardStyle["backgroundColor"] as? String { cardForm?.backgroundColor = UIColor(hexString: backgroundColor) } // if let disabledBackgroundColor = cardStyle["disabledBackgroundColor"] as? String { // cardForm?.disabledBackgroundColor = UIColor(hexString: disabledBackgroundColor) // } } override init(frame: CGRect) { super.init(frame: frame) } override func layoutSubviews() { cardForm?.frame = self.bounds } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
159484caba8d693d9233c7f3f0e4d49b
33.55914
135
0.59552
false
false
false
false
february29/Learning
refs/heads/master
Pods/RxDataSources/Sources/RxDataSources/RxTableViewSectionedAnimatedDataSource.swift
cc0-1.0
3
// // RxTableViewSectionedAnimatedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 6/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif import Differentiator open class RxTableViewSectionedAnimatedDataSource<S: AnimatableSectionModelType> : TableViewSectionedDataSource<S> , RxTableViewDataSourceType { public typealias Element = [S] public typealias DecideViewTransition = (TableViewSectionedDataSource<S>, UITableView, [Changeset<S>]) -> ViewTransition /// Animation configuration for data source public var animationConfiguration: AnimationConfiguration /// Calculates view transition depending on type of changes public var decideViewTransition: DecideViewTransition #if os(iOS) public init( animationConfiguration: AnimationConfiguration = AnimationConfiguration(), decideViewTransition: @escaping DecideViewTransition = { _, _, _ in .animated }, configureCell: @escaping ConfigureCell, titleForHeaderInSection: @escaping TitleForHeaderInSection = { _, _ in nil }, titleForFooterInSection: @escaping TitleForFooterInSection = { _, _ in nil }, canEditRowAtIndexPath: @escaping CanEditRowAtIndexPath = { _, _ in false }, canMoveRowAtIndexPath: @escaping CanMoveRowAtIndexPath = { _, _ in false }, sectionIndexTitles: @escaping SectionIndexTitles = { _ in nil }, sectionForSectionIndexTitle: @escaping SectionForSectionIndexTitle = { _, _, index in index } ) { self.animationConfiguration = animationConfiguration self.decideViewTransition = decideViewTransition super.init( configureCell: configureCell, titleForHeaderInSection: titleForHeaderInSection, titleForFooterInSection: titleForFooterInSection, canEditRowAtIndexPath: canEditRowAtIndexPath, canMoveRowAtIndexPath: canMoveRowAtIndexPath, sectionIndexTitles: sectionIndexTitles, sectionForSectionIndexTitle: sectionForSectionIndexTitle ) } #else public init( animationConfiguration: AnimationConfiguration = AnimationConfiguration(), decideViewTransition: @escaping DecideViewTransition = { _, _, _ in .animated }, configureCell: @escaping ConfigureCell, titleForHeaderInSection: @escaping TitleForHeaderInSection = { _, _ in nil }, titleForFooterInSection: @escaping TitleForFooterInSection = { _, _ in nil }, canEditRowAtIndexPath: @escaping CanEditRowAtIndexPath = { _, _ in false }, canMoveRowAtIndexPath: @escaping CanMoveRowAtIndexPath = { _, _ in false } ) { self.animationConfiguration = animationConfiguration self.decideViewTransition = decideViewTransition super.init( configureCell: configureCell, titleForHeaderInSection: titleForHeaderInSection, titleForFooterInSection: titleForFooterInSection, canEditRowAtIndexPath: canEditRowAtIndexPath, canMoveRowAtIndexPath: canMoveRowAtIndexPath ) } #endif var dataSet = false open func tableView(_ tableView: UITableView, observedEvent: Event<Element>) { Binder(self) { dataSource, newSections in #if DEBUG self._dataSourceBound = true #endif if !self.dataSet { self.dataSet = true dataSource.setSections(newSections) tableView.reloadData() } else { DispatchQueue.main.async { // if view is not in view hierarchy, performing batch updates will crash the app if tableView.window == nil { dataSource.setSections(newSections) tableView.reloadData() return } let oldSections = dataSource.sectionModels do { let differences = try Diff.differencesForSectionedView(initialSections: oldSections, finalSections: newSections) switch self.decideViewTransition(self, tableView, differences) { case .animated: for difference in differences { dataSource.setSections(difference.finalSections) tableView.performBatchUpdates(difference, animationConfiguration: self.animationConfiguration) } case .reload: self.setSections(newSections) tableView.reloadData() return } } catch let e { rxDebugFatalError(e) self.setSections(newSections) tableView.reloadData() } } } }.on(observedEvent) } } #endif
99481ba1c059dcbb8fa78e34758e06e7
42.99187
136
0.591573
false
true
false
false
warren-gavin/OBehave
refs/heads/master
OBehave/Classes/Tables/EmptyState/OBEmptyStateBehavior.swift
mit
1
// // OBEmptyStateBehavior.swift // OBehave // // Created by Warren on 18/02/16. // Copyright © 2016 Apokrupto. All rights reserved. // import UIKit // MARK: - OBEmptyStateBehaviorDataSource public protocol OBEmptyStateBehaviorDataSource { func viewToDisplayOnEmpty(for behavior: OBEmptyStateBehavior?) -> UIView? } // MARK: - Views that can have empty states enum DataSetView { case table(UITableView) case collection(UICollectionView) } // MARK: - Behavior public final class OBEmptyStateBehavior: OBBehavior { @IBOutlet public var scrollView: UIScrollView! { didSet { switch scrollView { case let view as UITableView: view.tableFooterView = UIView() dataSetView = .table(view) case let view as UICollectionView: dataSetView = .collection(view) default: dataSetView = nil } } } private var dataSetView: DataSetView? { didSet { guard let displayingView = dataSetView?.view as? DataDisplaying else { return } interceptDataLoading() displayingView.emptyStateDataSource = getDataSource() } } } private extension OBEmptyStateBehavior { func interceptDataLoading() { guard let viewClass = dataSetView?.class, let viewClassType = viewClass as? DataDisplaying.Type, !viewClassType.isSwizzled else { return } zip(viewClassType.swizzledMethods, viewClassType.originalMethods).forEach { guard let swizzledMethod = class_getInstanceMethod(viewClass, $0), let originalMethod = class_getInstanceMethod(viewClass, $1) else { return } method_exchangeImplementations(swizzledMethod, originalMethod) } viewClassType.isSwizzled = true } } // MARK: - DataSetView extension extension DataSetView { var view: UIView? { switch self { case .table(let view): return view case .collection(let view): return view } } var `class`: AnyClass? { switch self { case .table(_): return UITableView.self case .collection(_): return UICollectionView.self } } var isEmpty: Bool { switch self { case .table(let table): return table.isEmpty case .collection(let collection): return collection.isEmpty } } } // MARK: - DataDisplaying protocol protocol DataDisplaying: class { var numberOfSections: Int { get } func count(for section: Int) -> Int static var originalMethods: [Selector] { get } static var swizzledMethods: [Selector] { get } } extension DataDisplaying where Self: UIView { var showEmptyState: Bool { get { return isEmpty } set { guard let emptyStateView = emptyStateView else { return } if newValue { addSubview(emptyStateView) emptyStateView.translatesAutoresizingMaskIntoConstraints = false emptyStateView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true emptyStateView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true emptyStateView.topAnchor.constraint(greaterThanOrEqualTo: topAnchor).isActive = true emptyStateView.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor).isActive = true emptyStateView.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor).isActive = true emptyStateView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor).isActive = true layoutIfNeeded() } else { clearEmptyStateView() } emptyStateView.alpha = (newValue ? 1.0 : 0.0) } } } private struct Constants { static var isSwizzledKey = "com.apokrupto.OBEmptyStateBehavior.isSwizzled" static var emptyStateViewKey = "com.apokrupto.OBEmptyDateSetBehavior.emptyStateView" static var emptyStateDataSourceKey = "com.apokrupto.OBEmptyDateSetBehavior.emptyStateDataSource" } private extension DataDisplaying { var isEmpty: Bool { return 0 == (0 ..< numberOfSections).reduce(0) { $0 + count(for: $1) } } var emptyStateView: UIView? { get { if let emptyStateView = objc_getAssociatedObject(self, &Constants.emptyStateViewKey) as? UIView { return emptyStateView } let emptyStateView = emptyStateDataSource?.viewToDisplayOnEmpty(for: nil) objc_setAssociatedObject(self, &Constants.emptyStateViewKey, emptyStateView, .OBJC_ASSOCIATION_ASSIGN) return emptyStateView } set { objc_setAssociatedObject(self, &Constants.emptyStateViewKey, newValue, .OBJC_ASSOCIATION_ASSIGN) } } var emptyStateDataSource: OBEmptyStateBehaviorDataSource? { get { return objc_getAssociatedObject(self, &Constants.emptyStateDataSourceKey) as? OBEmptyStateBehaviorDataSource } set { objc_setAssociatedObject(self, &Constants.emptyStateDataSourceKey, newValue, .OBJC_ASSOCIATION_ASSIGN) } } static var isSwizzled: Bool { get { return objc_getAssociatedObject(self, &Constants.isSwizzledKey) as? Bool ?? false } set { objc_setAssociatedObject(self, &Constants.isSwizzledKey, newValue, .OBJC_ASSOCIATION_COPY) } } func clearEmptyStateView() { emptyStateView?.removeFromSuperview() emptyStateView = nil } } // MARK: - Extending table and collection views to conform to DataDisplaying extension UITableView: DataDisplaying { func count(for section: Int) -> Int { return dataSource?.tableView(self, numberOfRowsInSection: section) ?? 0 } @objc func ob_reloadData() { defer { showEmptyState = isEmpty } clearEmptyStateView() return ob_reloadData() } @objc func ob_endUpdates() { clearEmptyStateView() showEmptyState = isEmpty return ob_endUpdates() } static let originalMethods = [ #selector(UITableView.reloadData), #selector(UITableView.endUpdates) ] static let swizzledMethods = [ #selector(UITableView.ob_reloadData), #selector(UITableView.ob_endUpdates) ] } extension UICollectionView: DataDisplaying { func count(for section: Int) -> Int { return dataSource?.collectionView(self, numberOfItemsInSection: section) ?? 0 } @objc func ob_reloadData() { defer { showEmptyState = isEmpty } clearEmptyStateView() return ob_reloadData() } @objc func ob_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil) { return ob_performBatchUpdates(updates) { [unowned self] ok in completion?(ok) self.clearEmptyStateView() self.showEmptyState = self.isEmpty } } static let originalMethods = [ #selector(UICollectionView.reloadData), #selector(UICollectionView.performBatchUpdates(_:completion:)) ] static let swizzledMethods = [ #selector(UICollectionView.ob_reloadData), #selector(UICollectionView.ob_performBatchUpdates(_:completion:)) ] }
5af6a623ee78fcb3652c0d64dd064011
28.142857
120
0.598793
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Model/CGSSSkill.swift
mit
2
// // CGSSSkill.swift // CGSSFoundation // // Created by zzk on 16/6/14. // Copyright © 2016 zzk. All rights reserved. // import Foundation import SwiftyJSON fileprivate let skillDescriptions = [ 1: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成", comment: "技能描述"), 2: NSLocalizedString("使所有PERFECT/GREAT音符获得 %d%% 的分数加成", comment: "技能描述"), 3: NSLocalizedString("使所有PERFECT/GREAT/NICE音符获得 %d%% 的分数加成", comment: "技能描述"), 4: NSLocalizedString("获得额外的 %d%% 的COMBO加成", comment: "技能描述"), 5: NSLocalizedString("使所有GREAT音符改判为PERFECT", comment: "技能描述"), 6: NSLocalizedString("使所有GREAT/NICE音符改判为PERFECT", comment: "技能描述"), 7: NSLocalizedString("使所有GREAT/NICE/BAD音符改判为PERFECT", comment: "技能描述"), 8: NSLocalizedString("所有音符改判为PERFECT", comment: "技能描述"), 9: NSLocalizedString("使NICE音符不会中断COMBO", comment: "技能描述"), 10: NSLocalizedString("使BAD/NICE音符不会中断COMBO", comment: "技能描述"), 11: NSLocalizedString("使你的COMBO不会中断", comment: "技能描述"), 12: NSLocalizedString("使你的生命不会减少", comment: "技能描述"), 13: NSLocalizedString("使所有音符恢复你 %d 点生命", comment: "技能描述"), 14: NSLocalizedString("消耗 %2$d 生命,PERFECT音符获得 %1$d%% 的分数加成,并且NICE/BAD音符不会中断COMBO", comment: "技能描述"), 15: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,且使PERFECT判定区间的时间范围缩小", comment: ""), 16: NSLocalizedString("重复发动上一个其他偶像发动过的技能", comment: ""), 17: NSLocalizedString("使所有PERFECT音符恢复你 %d 点生命", comment: "技能描述"), 18: NSLocalizedString("使所有PERFECT/GREAT音符恢复你 %d 点生命", comment: "技能描述"), 19: NSLocalizedString("使所有PERFECT/GREAT/NICE音符恢复你 %d 点生命", comment: "技能描述"), 20: NSLocalizedString("使当前发动的分数加成和COMBO加成额外提高 %d%%,生命恢复和护盾额外恢复 1 点生命,改判范围增加一档", comment: ""), 21: NSLocalizedString("当仅有Cute偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""), 22: NSLocalizedString("当仅有Cool偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""), 23: NSLocalizedString("当仅有Passion偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""), 24: NSLocalizedString("获得额外的 %d%% 的COMBO加成,并使所有PERFECT音符恢复你 %d 点生命", comment: ""), 25: NSLocalizedString("获得额外的COMBO加成,当前生命值越高加成越高", comment: ""), 26: NSLocalizedString("当Cute、Cool和Passion偶像存在于队伍时,使所有PERFECT音符获得 %1$d%% 的分数加成/恢复你 %3$d 点生命,并获得额外的 %2$d%% 的COMBO加成", comment: ""), 27: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""), 28: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,如果音符类型是长按则改为提高 %d%%", comment: ""), 29: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,如果音符类型是滑块则改为提高 %d%%", comment: ""), 31: NSLocalizedString("获得额外的 %d%% 的COMBO加成,并使所有GREAT/NICE音符改判为PERFECT", comment: ""), ] fileprivate let intervalClause = NSLocalizedString("每 %d 秒,", comment: "") fileprivate let probabilityClause = NSLocalizedString("有 %@%% 的几率", comment: "") fileprivate let lengthClause = NSLocalizedString(",持续 %@ 秒。", comment: "") extension CGSSSkill { private var effectValue: Int { var effectValue = value! if [1, 2, 3, 4, 14, 15, 21, 22, 23, 24, 26, 27, 28, 29, 31].contains(skillTypeId) { effectValue -= 100 } else if [20].contains(skillTypeId) { // there is only one possibility: 20% up for combo bonus and perfect bonus, using fixed value here instead of reading it from database table skill_boost_type. if more possiblities are added to the game, fix here. effectValue = 20 } return effectValue } private var effectValue2: Int { var effectValue2 = value2! if [21, 22, 23, 26, 27, 28, 29].contains(skillTypeId) { effectValue2 -= 100 } return effectValue2 } private var effectValue3: Int { return value3 } private var effectExpalin: String { if skillTypeId == 14 { return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, skillTriggerValue) } else { return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, effectValue2, effectValue3) } } private var intervalExplain: String { return String.init(format: intervalClause, condition) } @nonobjc func getLocalizedExplainByRange(_ range: CountableClosedRange<Int>) -> String { let probabilityRangeString = String(format: "%.2f ~ %.2f", Double(procChanceOfLevel(range.lowerBound)) / 100, Double(procChanceOfLevel(range.upperBound)) / 100) let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString) let lengthRangeString = String(format: "%.2f ~ %.2f", Double(effectLengthOfLevel(range.lowerBound)) / 100, Double(effectLengthOfLevel(range.upperBound)) / 100) let lengthExplain = String(format: lengthClause, lengthRangeString) return intervalExplain + probabilityExplain + effectExpalin + lengthExplain } @nonobjc func getLocalizedExplainByLevel(_ level: Int) -> String { let probabilityRangeString = String(format: "%@", (Decimal(procChanceOfLevel(level)) / 100).description) let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString) let lengthRangeString = String(format: "%@", (Decimal(effectLengthOfLevel(level)) / 100).description) let lengthExplain = String.init(format: lengthClause, lengthRangeString) return intervalExplain + probabilityExplain + effectExpalin + lengthExplain } var skillFilterType: CGSSSkillTypes { return CGSSSkillTypes(typeID: skillTypeId) } var descriptionShort: String { return "\(condition!)s/\(procTypeShort)/\(skillFilterType.description)" } // 在计算触发几率和持续时间时 要在取每等级增量部分进行一次向下取整 func procChanceOfLevel(_ lv: Int) -> Int { if let p = procChance { let p1 = Float(p[1]) let p0 = Float(p[0]) return wpcap(x :(p1 - p0) / 9 * Float(lv - 1) + p0) } else { return 0 } } func wpcap(x: Float) -> Int { var n = Int(x) let n10 = Int(x * 10) if (n10 % 10 != 0) { n += 1 } return n } func effectLengthOfLevel(_ lv: Int) -> Int { if let e = effectLength { let e1 = Float(e[1]) let e0 = Float(e[0]) return wpcap(x: (e1 - e0) / 9 * Float(lv - 1) + e0) } else { return 0 } } var procTypeShort: String { switch maxChance { case 6000: return NSLocalizedString("高", comment: "技能触发几率的简写") case 5250: return NSLocalizedString("中", comment: "技能触发几率的简写") case 4500: return NSLocalizedString("低", comment: "技能触发几率的简写") default: return NSLocalizedString("其他", comment: "通用, 通常不会出现, 为未知字符预留") } } var procType: CGSSProcTypes { switch maxChance { case 6000: return .high case 5250: return .middle case 4500: return .low default: return .none } } var conditionType: CGSSConditionTypes { switch condition { case 4: return .c4 case 6: return .c6 case 7: return .c7 case 9: return .c9 case 11: return .c11 case 13: return .c13 default: return .other } } } class CGSSSkill: CGSSBaseModel { var condition: Int! var cutinType: Int! var effectLength: [Int]! var explain: String! var explainEn: String! var id: Int! var judgeType: Int! var maxChance: Int! var maxDuration: Int! var procChance: [Int]! var skillName: String! var skillTriggerType: Int! var skillTriggerValue: Int! var skillType: String! var value: Int! var skillTypeId: Int! var value2: Int! var value3: Int! /** * Instantiate the instance using the passed json values to set the properties values */ init(fromJson json: JSON!) { super.init() if json == JSON.null { return } condition = json["condition"].intValue cutinType = json["cutin_type"].intValue effectLength = [Int]() let effectLengthArray = json["effect_length"].arrayValue for effectLengthJson in effectLengthArray { effectLength.append(effectLengthJson.intValue) } explain = json["explain"].stringValue explainEn = json["explain_en"].stringValue id = json["id"].intValue judgeType = json["judge_type"].intValue maxChance = json["max_chance"].intValue maxDuration = json["max_duration"].intValue procChance = [Int]() let procChanceArray = json["proc_chance"].arrayValue for procChanceJson in procChanceArray { procChance.append(procChanceJson.intValue) } skillName = json["skill_name"].stringValue skillTriggerType = json["skill_trigger_type"].intValue skillTriggerValue = json["skill_trigger_value"].intValue skillType = json["skill_type"].stringValue if skillType == "" { skillType = NSLocalizedString("未知", comment: "") } value = json["value"].intValue value2 = json["value_2"].intValue value3 = json["value_3"].intValue skillTypeId = json["skill_type_id"].intValue } /** * NSCoding required initializer. * Fills the data from the passed decoder */ required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) condition = aDecoder.decodeObject(forKey: "condition") as? Int cutinType = aDecoder.decodeObject(forKey: "cutin_type") as? Int effectLength = aDecoder.decodeObject(forKey: "effect_length") as? [Int] explain = aDecoder.decodeObject(forKey: "explain") as? String explainEn = aDecoder.decodeObject(forKey: "explain_en") as? String id = aDecoder.decodeObject(forKey: "id") as? Int judgeType = aDecoder.decodeObject(forKey: "judge_type") as? Int maxChance = aDecoder.decodeObject(forKey: "max_chance") as? Int maxDuration = aDecoder.decodeObject(forKey: "max_duration") as? Int procChance = aDecoder.decodeObject(forKey: "proc_chance") as? [Int] skillName = aDecoder.decodeObject(forKey: "skill_name") as? String skillTriggerType = aDecoder.decodeObject(forKey: "skill_trigger_type") as? Int skillTriggerValue = aDecoder.decodeObject(forKey: "skill_trigger_value") as? Int skillType = aDecoder.decodeObject(forKey: "skill_type") as? String ?? NSLocalizedString("未知", comment: "") value = aDecoder.decodeObject(forKey: "value") as? Int skillTypeId = aDecoder.decodeObject(forKey: "skill_type_id") as? Int value2 = aDecoder.decodeObject(forKey: "value_2") as? Int value3 = aDecoder.decodeObject(forKey: "value_3") as? Int } /** * NSCoding required method. * Encodes mode properties into the decoder */ override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) if condition != nil { aCoder.encode(condition, forKey: "condition") } if cutinType != nil { aCoder.encode(cutinType, forKey: "cutin_type") } if effectLength != nil { aCoder.encode(effectLength, forKey: "effect_length") } if explain != nil { aCoder.encode(explain, forKey: "explain") } if explainEn != nil { aCoder.encode(explainEn, forKey: "explain_en") } if id != nil { aCoder.encode(id, forKey: "id") } if judgeType != nil { aCoder.encode(judgeType, forKey: "judge_type") } if maxChance != nil { aCoder.encode(maxChance, forKey: "max_chance") } if maxDuration != nil { aCoder.encode(maxDuration, forKey: "max_duration") } if procChance != nil { aCoder.encode(procChance, forKey: "proc_chance") } if skillName != nil { aCoder.encode(skillName, forKey: "skill_name") } if skillTriggerType != nil { aCoder.encode(skillTriggerType, forKey: "skill_trigger_type") } if skillTriggerValue != nil { aCoder.encode(skillTriggerValue, forKey: "skill_trigger_value") } if skillType != nil { aCoder.encode(skillType, forKey: "skill_type") } if value != nil { aCoder.encode(value, forKey: "value") } if skillTypeId != nil { aCoder.encode(skillTypeId, forKey: "skill_type_id") } if value2 != nil { aCoder.encode(value2, forKey: "value_2") } if value3 != nil { aCoder.encode(value3, forKey: "value_3") } } }
cc5476980c4b82be4289332abd7b5a3f
36.887931
224
0.610087
false
false
false
false
orta/eidolon
refs/heads/master
KioskTests/KioskTests.swift
mit
1
class KioskTests {} import UIKit var sharedInstances = Dictionary<String, AnyObject>() public extension UIStoryboard { public class func fulfillment() -> UIStoryboard { // This will ensure that a storyboard instance comes out of the testing bundle // instead of the MainBundle. return UIStoryboard(name: "Fulfillment", bundle: NSBundle(forClass: KioskTests.self)) } public func viewControllerWithID(identifier:ViewControllerStoryboardIdentifier) -> UIViewController { let id = identifier.rawValue // Uncomment for experimental caching. // // if let cached: NSData = sharedInstances[id] as NSData { // return NSKeyedUnarchiver.unarchiveObjectWithData(cached) as UIViewController // // } else { let vc = self.instantiateViewControllerWithIdentifier(id) as UIViewController // sharedInstances[id] = NSKeyedArchiver.archivedDataWithRootObject(vc); return vc; // } } }
1e10e84643ab40875b2a34e72b7e9288
31.096774
105
0.687437
false
true
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobufPluginLibrary/Array+Extensions.swift
apache-2.0
4
// Sources/SwiftProtobufPluginLibrary/Array+Extensions.swift - Additions to Arrays // // Copyright (c) 2014 - 2017 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/master/LICENSE.txt // // ----------------------------------------------------------------------------- import Foundation extension Array { /// Like map, but calls the transform with the index and value. /// /// NOTE: It would seem like doing: /// return self.enumerated().map { /// return try transform($0.index, $0.element) /// } /// would seem like a simple thing to avoid extension. However as of Xcode 8.3.2 /// (Swift 3.1), building/running 5000000 interation test (macOS) of the differences /// are rather large - /// Release build: /// Using enumerated: 3.694987967 /// Using enumeratedMap: 0.961241992 /// Debug build: /// Using enumerated: 20.038512905 /// Using enumeratedMap: 8.521299144 func enumeratedMap<T>(_ transform: (Int, Element) throws -> T) rethrows -> [T] { var i: Int = -1 return try map { i += 1 return try transform(i, $0) } } } #if !swift(>=4.2) extension Array { func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Int? { var i = self.startIndex while i < self.endIndex { if try predicate(self[i]) { return i } self.formIndex(after: &i) } return nil } } #endif // !swift(>=4.2)
ab08b6c20597f4de973cd6d2b7e402f2
29.288462
86
0.607619
false
false
false
false
rastogigaurav/mTV
refs/heads/master
mTV/mTV/ViewModels/MovieListViewModel.swift
mit
1
// // MovieListViewModel.swift // mTV // // Created by Gaurav Rastogi on 6/25/17. // Copyright © 2017 Gaurav Rastogi. All rights reserved. // import UIKit class MovieListViewModel: NSObject { var movies:[Movie] = []{ willSet{ filteredMovies = newValue } } var section:MovieSections var filteredMovies:[Movie] = [] var startDateIndex:Int = years_1950_2017.count-18 var endDateIndex:Int = years_1950_2017.count-1 var displayMovies:DisplayMoviesProtocol! init(with displayList:DisplayMoviesProtocol, selectedSection section:MovieSections){ self.section = section self.displayMovies = displayList } func fetchMovies(withPage page:Int, reload:@escaping (_ totalMovies:Int?)->Void){ self.displayMovies.displayMovies(forSection: self.section, withPage: page) { [unowned self] (total,movies,section) in if let list = movies{ self.movies.append(contentsOf: list) } reload(total) } } func filter(basedOn startIndex:Int, endIndex:Int, reload:@escaping ()->())->Void{ self.displayMovies.filter(movieList: movies, startYear: years_1950_2017[startIndex], endYear: years_1950_2017[endIndex]) {[unowned self] (filteredMovies) in self.startDateIndex = startIndex self.endDateIndex = endIndex self.filteredMovies = filteredMovies reload() } } func numberOfItemsInSection(section:Int)->Int{ return self.filteredMovies.count } func titleAndReleaseYearForMovie(at indexPath:IndexPath)->String?{ if let mTitle = self.filteredMovies[indexPath.row].title{ return (mTitle + " (" + String(self.filteredMovies[indexPath.row].releaseYear) + ")") } return nil } func releaseDateForMovie(at indexPath:IndexPath)->String?{ if let releaseDate = self.filteredMovies[indexPath.row].releaseDate{ return releaseDate } return nil } func posterImageUrlForMovie(at indexPath:IndexPath)->String?{ if let posterImageUrl = self.filteredMovies[indexPath.row].posterPathURL(){ return posterImageUrl } return nil } func movieId(forMovieAt indexPath:IndexPath)->Int{ return (self.filteredMovies[indexPath.row]).id! } func titel()->String?{ switch self.section { case .topRated: return "Top Rated" case .upcoming: return "Upcoming" case .nowPlaying: return "Now Playing" case .popular: return "Popular" default: return nil } } }
bb946dd2a81844ea2e1527dceab82889
28.326316
164
0.609117
false
false
false
false
pozi119/Valine
refs/heads/master
Valine/Valine.swift
gpl-2.0
1
// // Valine.swift // Valine // // Created by Valo on 15/12/23. // Copyright © 2015年 Valo. All rights reserved. // import UIKit public func pageHop(hopMethod:HopMethod,hop:Hop)->AnyObject?{ if hop.controller != nil { Utils.setParameters(hop.parameters, forObject:hop.controller!) } switch hopMethod{ case .Push: Manager.sharedManager.currentNaviController?.pushViewController(hop.controller!, animated:hop.animated) if(hop.removeVCs?.count > 0){ var existVCs = Manager.sharedManager.currentNaviController?.viewControllers for var idx = 0; idx < existVCs?.count; ++idx{ let vc = existVCs![idx] let vcName = NSStringFromClass(vc.classForKeyedArchiver!) for tmpName in hop.removeVCs!{ if vcName.containsString(tmpName){ existVCs?.removeAtIndex(idx) } } } Manager.sharedManager.currentNaviController?.viewControllers = existVCs! } case .Pop: if hop.controller == nil{ Manager.sharedManager.currentNaviController?.popViewControllerAnimated(hop.animated) } else{ var destVC = hop.controller let existVCs = Manager.sharedManager.currentNaviController?.viewControllers for vc in existVCs!{ let vcName = NSStringFromClass(vc.classForKeyedArchiver!) if vcName.containsString(hop.aController!){ destVC = vc if hop.parameters != nil{ Utils.setParameters(hop.parameters, forObject:destVC!) } break } } Manager.sharedManager.currentNaviController?.popToViewController(destVC!, animated: hop.animated) } case .Present: var sourceVC:UIViewController if hop.sourceInNav && Manager.sharedManager.currentNaviController != nil{ sourceVC = Manager.sharedManager.currentNaviController! } else{ sourceVC = Manager.sharedManager.currentViewController! } var destVC = hop.controller if hop.destInNav{ if destVC!.navigationController != nil{ destVC = destVC!.navigationController! } else{ destVC = UINavigationController(rootViewController: destVC!) } } if hop.alpha < 1.0 && hop.alpha > 0.0 { hop.controller!.view.alpha = hop.alpha } sourceVC.presentViewController(destVC!, animated:hop.animated, completion:hop.completion) case .Dismiss: Manager.sharedManager.currentViewController?.dismissViewControllerAnimated(hop.animated, completion:hop.completion) } return nil }
30a7c49d9194098f6a70910cd5fd0cd1
34.313253
123
0.582054
false
false
false
false
yarshure/Surf
refs/heads/UIKitForMac
Surf-Mac/RequestsBasic.swift
bsd-3-clause
1
// // RequestsBasic.swift // XDataService // // Created by yarshure on 2018/1/17. // Copyright © 2018年 A.BIG.T. All rights reserved. // import Cocoa import SwiftyJSON import NetworkExtension import SFSocket import XProxy open class RequestsBasic: NSViewController,NSTableViewDelegate,NSTableViewDataSource { public var results:[SFRequestInfo] = [] public var dbURL:URL? @IBOutlet public weak var tableView:NSTableView! public override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { print("load....") super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } @objc required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) print("load coder....") } public func processData(data:Data) { let oldresults = results results.removeAll() let obj = try! JSON.init(data: data) if obj.error == nil { let count = obj["count"] if count.intValue != 0 { let result = obj["data"] if result.type == .array { for item in result { let json = item.1 let r = SFRequestInfo.init(rID: 0) r.map(json) let rr = oldresults.filter({ info -> Bool in if info.reqID == r.reqID && info.subID == r.subID { return true } return false }) if rr.isEmpty { results.append(r) r.speedtraffice = r.traffice }else { let old = rr.first! if r.traffice.rx > old.traffice.rx { //sub id reset r.speedtraffice.rx = r.traffice.rx - old.traffice.rx } if r.traffice.tx > old.traffice.tx{ //? r.speedtraffice.tx = r.traffice.tx - old.traffice.tx } results.append(r) } } } if results.count > 0 { results.sort(by: { $0.reqID < $1.reqID }) } } } tableView.reloadData() } public func numberOfRows(in tableView: NSTableView) -> Int { return results.count } public func tableView(_ tableView: NSTableView , objectValueFor tableColumn: NSTableColumn? , row: Int) -> Any? { let result = results[row] if (tableColumn?.identifier)!.rawValue == "Icon" { switch result.rule.policy{ case .Direct: return NSImage(named:"NSStatusPartiallyAvailable") case .Proxy: return NSImage(named:"NSStatusAvailable") case .Reject: return NSImage(named:"NSStatusUnavailable") default: break } } return nil } public func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let iden = tableColumn!.identifier.rawValue let result = results[row] let cell:NSTableCellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView if iden == "Index" { cell.textField?.stringValue = "\(result.reqID) \(result.subID)" }else if iden == "App" { cell.textField?.attributedStringValue = result.detailString() }else if iden == "Url" { if result.mode == .HTTP { if let u = URL(string: result.url){ if let h = u.host { cell.textField?.stringValue = h }else { cell.textField?.stringValue = u.description } }else { if let req = result.reqHeader{ cell.textField?.stringValue = req.Host } } }else { cell.textField?.stringValue = result.url } }else if iden == "Rule" { }else if iden == "Date" { cell.textField?.stringValue = result.dataDesc(result.sTime) }else if iden == "Status" { let n = Date() let a = result.activeTime let idle = n.timeIntervalSince(a) if idle > 1 { cell.textField?.stringValue = "idle \(Int(idle))" }else { cell.textField?.stringValue = result.status.description } }else if iden == "Policy" { let rule = result.rule cell.textField?.stringValue = rule.policy.description + " (" + rule.type.description + ":" + rule.name + ")" //(\(rule.type.description):\(rule.name) ProxyName:\(rule.proxyName))" //cell.textField?.stringValue = "Demo"//result.status.description }else if iden == "Up" { let tx = result.speedtraffice.tx cell.textField?.stringValue = self.toString(x: tx,label:"",speed: true) }else if iden == "Down" { let rx = result.speedtraffice.rx cell.textField?.stringValue = self.toString(x: rx,label:"",speed: true) }else if iden == "Method" { if result.mode == .TCP{ cell.textField?.stringValue = "TCP" }else { if let req = result.reqHeader { if req.method == .CONNECT { cell.textField?.stringValue = "HTTPS" }else { cell.textField?.stringValue = req.method.rawValue } } } }else if iden == "Icon" { switch result.rule.policy{ case .Direct: cell.imageView?.objectValue = NSImage(named:"NSStatusPartiallyAvailable") case .Proxy: cell.imageView?.objectValue = NSImage(named:"NSStatusAvailable") case .Reject: cell.imageView?.objectValue = NSImage(named:"NSStatusUnavailable") default: break } }else if iden == "DNS" { if !result.rule.ipAddress.isEmpty { cell.textField?.stringValue = result.rule.ipAddress }else { if !result.remoteIPaddress.isEmpty{ let x = result.remoteIPaddress.components(separatedBy: " ") if x.count > 1 { cell.textField?.stringValue = x.last! }else { cell.textField?.stringValue = x.first! } }else { if !result.rule.name.isEmpty { cell.textField?.stringValue = result.rule.name }else { let x = "NONE" let s = NSMutableAttributedString(string:x ) let r = NSMakeRange(0, 4); s.addAttributes([NSAttributedString.Key.foregroundColor:NSColor.red,NSAttributedString.Key.backgroundColor:NSColor.white], range: r) cell.textField?.attributedStringValue = s } } } } if row % 2 == 0 { cell.backgroundStyle = .dark }else { cell.backgroundStyle = .light } return cell } public func toString(x:UInt,label:String,speed:Bool) ->String { var s = "/s" if !speed { s = "" } if x < 1024{ return label + " \(x) B" + s }else if x >= 1024 && x < 1024*1024 { return label + String(format: "%0.2f KB", Float(x)/1024.0) + s }else if x >= 1024*1024 && x < 1024*1024*1024 { return label + String(format: "%0.2f MB", Float(x)/1024/1024) + s }else { return label + String(format: "%0.2f GB", Float(x)/1024/1024/1024) + s } } }
2cf343369c6ce3041bf0521fc9278bbf
34.419608
156
0.443756
false
false
false
false
BridgeTheGap/KRStackView
refs/heads/master
Example/KRStackView/ViewController.swift
mit
1
// // ViewController.swift // KRStackView // // Created by Joshua Park on 07/13/2016. // Copyright (c) 2016 Joshua Park. All rights reserved. // import UIKit import KRStackView private var Screen: UIScreen { return UIScreen.main } private var DEFAULT_FRAME = CGRect(x: 20.0, y: 20.0, width: 148.0, height: 400.0) class ViewController: UIViewController { @IBOutlet weak var stackView: KRStackView! @IBOutlet weak var viewRed: UIView! @IBOutlet weak var viewYellow: UIView! @IBOutlet weak var viewBlue: UIView! @IBOutlet weak var viewControls: UIView! @IBOutlet weak var switchEnabled: UISwitch! @IBOutlet weak var controlDirection: UISegmentedControl! @IBOutlet weak var switchShouldWrap: UISwitch! @IBOutlet weak var controlAlignment: UISegmentedControl! @IBOutlet weak var sliderTop: UISlider! @IBOutlet weak var sliderRight: UISlider! @IBOutlet weak var sliderBottom: UISlider! @IBOutlet weak var sliderLeft: UISlider! @IBOutlet weak var switchIndividual: UISwitch! @IBOutlet weak var controlView: UISegmentedControl! @IBOutlet weak var sliderWidth: UISlider! @IBOutlet weak var sliderHeight: UISlider! @IBOutlet weak var sliderSpacing: UISlider! @IBOutlet weak var sliderOffset: UISlider! override func viewDidLoad() { super.viewDidLoad() stackView.enabled = false viewControls.frame.origin.x = Screen.bounds.width } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backgroundAction(_ sender: AnyObject) { UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 300.0, initialSpringVelocity: 4.0, options: [], animations: { if self.viewControls.frame.origin.x == Screen.bounds.width { self.viewControls.frame.origin.x = 401.0 } else { self.viewControls.frame.origin.x = Screen.bounds.width } }, completion: nil) } // MARK: - Controls @IBAction func enabledAction(_ sender: AnyObject) { let enabled = (sender as! UISwitch).isOn stackView.enabled = enabled if !enabled { switchIndividual.isOn = false switchIndividual.sendActions(for: .valueChanged) } for view in viewControls.subviews { if [switchEnabled, controlView, sliderWidth, sliderHeight, sliderSpacing, sliderOffset].contains(view) { continue } if let control = view as? UIControl { control.isEnabled = enabled } } stackView.setNeedsLayout() } @IBAction func directionAction(_ sender: AnyObject) { stackView.frame = DEFAULT_FRAME if stackView.direction == .vertical { stackView.direction = .horizontal } else { stackView.direction = .vertical } stackView.setNeedsLayout() } @IBAction func wrapAction(_ sender: AnyObject) { stackView.frame = DEFAULT_FRAME stackView.shouldWrap = (sender as! UISwitch).isOn stackView.setNeedsLayout() } @IBAction func alignmentAction(_ sender: AnyObject) { stackView.frame = DEFAULT_FRAME guard let control = sender as? UISegmentedControl else { return } switch control.selectedSegmentIndex { case 0: stackView.alignment = .origin case 1: stackView.alignment = .center default: stackView.alignment = .endPoint } stackView.setNeedsLayout() } @IBAction func topInsetAction(_ sender: AnyObject) { stackView.frame = DEFAULT_FRAME stackView.insets.top = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } @IBAction func rightInsetAction(_ sender: AnyObject) { stackView.frame = DEFAULT_FRAME stackView.insets.right = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } @IBAction func bottomInsetAction(_ sender: AnyObject) { stackView.frame = DEFAULT_FRAME stackView.insets.bottom = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } @IBAction func leftInsetAction(_ sender: AnyObject) { stackView.frame = DEFAULT_FRAME stackView.insets.left = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } @IBAction func individualAction(_ sender: AnyObject) { let enabled = (sender as! UISwitch).isOn controlView.isEnabled = enabled sliderWidth.isEnabled = enabled sliderHeight.isEnabled = enabled sliderSpacing.isEnabled = enabled && controlView.selectedSegmentIndex != 2 sliderOffset.isEnabled = enabled stackView.itemSpacing = enabled ? [8.0, 8.0] : nil stackView.itemOffset = enabled ? [0.0, 0.0, 0.0] : nil } @IBAction func viewSelectAction(_ sender: AnyObject) { let index = (sender as! UISegmentedControl).selectedSegmentIndex let view = [viewRed, viewYellow, viewBlue][index]! sliderWidth.value = Float(view.frame.width) sliderHeight.value = Float(view.frame.height) sliderSpacing.isEnabled = switchIndividual.isOn && controlView.selectedSegmentIndex != 2 sliderSpacing.value = index != 2 ? Float(stackView.itemSpacing![index]) : sliderSpacing.value sliderOffset.value = Float(stackView.itemOffset![index]) } @IBAction func widthAction(_ sender: AnyObject) { let index = controlView.selectedSegmentIndex let view = [viewRed, viewYellow, viewBlue][index]! view.frame.size.width = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } @IBAction func heightAction(_ sender: AnyObject) { let index = controlView.selectedSegmentIndex let view = [viewRed, viewYellow, viewBlue][index] view?.frame.size.height = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } @IBAction func spacingAction(_ sender: AnyObject) { let index = controlView.selectedSegmentIndex stackView.itemSpacing![index] = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } @IBAction func offsetAction(_ sender: AnyObject) { let index = controlView.selectedSegmentIndex stackView.itemOffset![index] = CGFloat((sender as! UISlider).value) stackView.setNeedsLayout() } }
3e9a15efd1abdc783394e297d561cb3d
33.739583
140
0.647826
false
false
false
false
wumbo/Wumbofant
refs/heads/master
Wumbofant/CSVLoader.swift
bsd-3-clause
1
// // CSVLoader.swift // Wumbofant // // Created by Simon Crequer on 13/07/15. // Copyright (c) 2015 Simon Crequer. All rights reserved. // import Cocoa import CoreData class CSVLoader { var url: NSURL init(url: NSURL) { self.url = url loadEntries() } lazy var entries: [LogEntry] = { let managedObjectContext = (NSApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let fetchRequest = NSFetchRequest(entityName: "LogEntry") let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [LogEntry] return fetchResults }() /** Loads the CSV file given by url and parses it into an array of LogEntry objects */ func loadEntries() { var error: NSError? var contents: String? = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error) if error != nil { println("Error fetching file contents: \(error)") } else if contents != nil { var lines: [String] = contents!.componentsSeparatedByString("\r\n") if lines[0] == "Product,Project,Iteration,Story,Task,Comment,User,Date,Spent effort (hours)" { lines.removeAtIndex(0) for line in lines { let items = readLine(line) let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd.MM.yyyy HH:mm" let date: NSDate = dateFormatter.dateFromString(items[7])! // Create a CoreData entity for the LogEntry that can be referenced from // anywhere in the application let entry = NSEntityDescription.insertNewObjectForEntityForName("LogEntry", inManagedObjectContext: (NSApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!) as! LogEntry entry.product = items[0] entry.project = items[1] entry.iteration = items[2] entry.story = items[3] entry.task = items[4] entry.comment = items[5] entry.user = items[6] entry.date = date entry.spentEffort = NSNumber(float: NSString(string: items[8]).floatValue) } } } } /** Parses a line from the CSV file into an array of Strings. Rather than treating every comma as a seperator, it first checks if a comma is inside "quotation marks" and only treats it as a seperator if it isn't. :param: line The line of CSV data to be parsed :returns: An array of 9 Strings containing each part of the LogEntry */ private func readLine(line: String) -> [String] { var values: [String] = ["","","","","","","","",""] var index: Int = 0 var quoteReached: Bool = false for c in line { if c != "," && c != "\"" { values[index].append(c) } else if c == "\"" { if !quoteReached { quoteReached = true } else { quoteReached = false } } else if c == "," { if quoteReached { values[index].append(c) } else { index++ } } } return values } }
504b7655f7a0b2a321b49325fba4a680
33.45283
216
0.523692
false
false
false
false
kyungmin/pigeon
refs/heads/master
Pigeon/Pigeon/FrontEditViewController.swift
mit
1
// // FrontEditViewController.swift // Pigeon // // Created by Kyungmin Kim on 3/17/15. // Copyright (c) 2015 Kyungmin Kim. All rights reserved. // import UIKit class FrontEditViewController: UIViewController, UIViewControllerTransitioningDelegate, UIGestureRecognizerDelegate { @IBOutlet weak var frontBackground: UIImageView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var buttonGroup: UIView! var photoScale: CGFloat! = 1 var labelScale: CGFloat! = 1 var translation: CGPoint! = CGPoint(x: 0.0, y: 0.0) var location: CGPoint! = CGPoint(x: 0.0, y: 0.0) var originalImageFrame: CGRect! var originalImageCenter: CGPoint! var currentSelection: AnyObject! var imageTransition: ImageTransition! var textField: UITextField! var newSticker: UIImageView! var stickerNames: [String]! var segues: [String!] = [] var originalImageY: CGFloat! //create a variable to catch the image passing from the previous view controller var photoImage:UIImage! override func viewDidLoad() { super.viewDidLoad() originalImageY = scrollView.center.y //assign selected image to imageView imageView.image = photoImage imageView.contentMode = UIViewContentMode.ScaleAspectFill originalImageFrame = imageView.frame originalImageCenter = imageView.center scrollView.contentSize = imageView.frame.size segues = ["fontSegue", "stickerSegue", "templateSegue"] stickerNames = ["sticker_heart_highlighted", "sticker_plane_highlighted", "sticker_lips_highlighted"] buttonGroup.center.y = buttonGroup.center.y + buttonGroup.frame.height NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewDidAppear(animated: Bool) { showMenu() } func keyboardWillShow(notification: NSNotification!) { var userInfo = notification.userInfo! var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber var animationDuration = durationValue.doubleValue var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber var animationCurve = curveValue.integerValue UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: { self.scrollView.center.y = 200 self.frontBackground.center.y -= (self.originalImageY - 200) }, completion: nil) } func keyboardWillHide(notification: NSNotification!) { var userInfo = notification.userInfo! // Get the keyboard height and width from the notification // Size varies depending on OS, language, orientation var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber var animationDuration = durationValue.doubleValue var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber var animationCurve = curveValue.integerValue UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: { self.scrollView.center.y = self.originalImageY self.frontBackground.center.y += (self.originalImageY - 200) }, completion: nil) } @IBAction func didPinchImage(sender: UIPinchGestureRecognizer) { photoScale = sender.scale var target = sender.view! if (sender.state == UIGestureRecognizerState.Changed) { target.transform = CGAffineTransformScale(target.transform, photoScale, photoScale) } else if (sender.state == UIGestureRecognizerState.Ended) { if (target.frame.size.width < originalImageFrame.size.width) { target.transform = CGAffineTransformMakeScale(1, 1) } checkImageBoundary() } sender.scale = 1 } @IBAction func didPinchLabel(sender: UIPinchGestureRecognizer) { imageView.userInteractionEnabled = false if sender.scale >= 1 { labelScale = 1 } else { labelScale = -1 } var label = sender.view as UILabel if (sender.state == UIGestureRecognizerState.Changed) { label.frame.size = CGSize(width: label.frame.width + labelScale, height: label.frame.height + labelScale) label.font = label.font.fontWithSize(label.font.pointSize + labelScale) } else if (sender.state == UIGestureRecognizerState.Ended) { imageView.userInteractionEnabled = true } sender.scale = 1 } @IBAction func didPanImage(sender: UIPanGestureRecognizer) { translation = sender.translationInView(view) location = sender.locationInView(view) //println(sender.view) if (sender.state == UIGestureRecognizerState.Began) { originalImageCenter = imageView.center } else if (sender.state == UIGestureRecognizerState.Changed) { imageView.transform = CGAffineTransformScale(sender.view!.transform, photoScale, photoScale) imageView.center = CGPoint(x: originalImageCenter.x + translation.x, y: originalImageCenter.y + translation.y) } else if (sender.state == UIGestureRecognizerState.Ended) { checkImageBoundary() } } @IBAction func didPanLabel(sender: UIPanGestureRecognizer) { translation = sender.translationInView(view) var label = sender.view as UILabel if (sender.state == UIGestureRecognizerState.Began) { originalImageCenter = sender.view!.center } else if (sender.state == UIGestureRecognizerState.Changed) { label.textColor = UIColor.grayColor() label.transform = CGAffineTransformScale(sender.view!.transform, labelScale, labelScale) label.center = CGPoint(x: originalImageCenter.x + translation.x, y: originalImageCenter.y + translation.y) } else if (sender.state == UIGestureRecognizerState.Ended) { label.textColor = UIColor.whiteColor() imageView.userInteractionEnabled = true } } @IBAction func didTapLabel(sender: UIPanGestureRecognizer) { var label = sender.view as UILabel currentSelection = label textField = UITextField(frame: CGRect(x: 0, y: 0, width: label.frame.width, height: label.frame.height)) label.alpha = 0 textField.center = label.center textField.textAlignment = .Center textField.text = label.text textField.font = label.font textField.textColor = UIColor.whiteColor() scrollView.addSubview(textField) textField.becomeFirstResponder() textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if textField != nil { view.endEditing(true) var label = currentSelection as UILabel label.text = textField.text label.alpha = 1 textField.removeFromSuperview() } super.touchesBegan(touches, withEvent: event) } func addFont(selectedFont: String) { var newLabel = UILabel(frame: CGRectMake(0, 0, 200, 50)) newLabel.font = UIFont(name: selectedFont, size: CGFloat(20)) newLabel.text = "Your text" newLabel.textColor = UIColor.whiteColor() newLabel.textAlignment = .Center newLabel.center = imageView.center newLabel.userInteractionEnabled = true imageView.userInteractionEnabled = false currentSelection = newLabel addTapGestureRecognizer(newLabel) addPanGestureRecognizer(newLabel) addPinchGestureRecognizer(newLabel) scrollView.addSubview(newLabel) } func addStickers(selectedStickers: [NSDictionary!]) { imageView.userInteractionEnabled = false for sticker in selectedStickers { var imageName = stickerNames[sticker["tag"] as Int] var image = UIImage(named: imageName) newSticker = UIImageView(image: image) newSticker.center = CGPoint(x: sticker["x"] as CGFloat, y: sticker["y"] as CGFloat) scrollView.addSubview(newSticker) newSticker.userInteractionEnabled = true } } func setTemplate(selectedWidth: CGFloat) { UIView.animateKeyframesWithDuration(0.3, delay: 0, options: nil, animations: { () -> Void in self.scrollView.frame.size = CGSize(width: selectedWidth, height: self.scrollView.frame.height) }, completion: nil) } // scaling text func addPinchGestureRecognizer(target :AnyObject) { var pinchGesture = UIPinchGestureRecognizer(target: self, action: "didPinchLabel:") pinchGesture.delegate = self target.addGestureRecognizer(pinchGesture) } // editing text func addTapGestureRecognizer(target :AnyObject) { var tapGesture = UITapGestureRecognizer(target: self, action: "didTapLabel:") tapGesture.delegate = self target.addGestureRecognizer(tapGesture) } // moving text func addPanGestureRecognizer(target :AnyObject) { var panGesture = UIPanGestureRecognizer(target: self, action: "didPanLabel:") panGesture.delegate = self target.addGestureRecognizer(panGesture) } func checkImageBoundary() { if (imageView.frame.origin.x >= 0) { imageView.frame.origin.x = 0 } if (imageView.frame.origin.y >= 0) { imageView.frame.origin.y = 0 } if (imageView.frame.origin.x < 0 && imageView.frame.origin.x + imageView.frame.size.width < scrollView.frame.width) { imageView.frame.origin.x = imageView.frame.origin.x + (scrollView.frame.width - (imageView.frame.origin.x + imageView.frame.size.width)) } if (imageView.frame.origin.y < 0 && imageView.frame.origin.y + imageView.frame.size.height < scrollView.frame.height) { imageView.frame.origin.y = imageView.frame.origin.y + (scrollView.frame.height - (imageView.frame.origin.y + imageView.frame.size.height)) } } @IBAction func didPressMenu(sender: AnyObject) { performSegueWithIdentifier(segues[sender.tag], sender: self) } @IBAction func didPressBackButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func didPressNextButton(sender: AnyObject) { performSegueWithIdentifier("saveFontSegue", sender: self) } func showMenu() { UIView.animateWithDuration(0.4, delay: 0.4, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.4, options: nil, animations: { () -> Void in self.buttonGroup.center = CGPoint(x:self.buttonGroup.center.x, y: self.buttonGroup.center.y - self.buttonGroup.frame.height) }, completion: nil) } func hideMenu() { UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.4, options: nil, animations: { () -> Void in self.buttonGroup.center = CGPoint(x:self.buttonGroup.center.x, y: self.buttonGroup.center.y + self.buttonGroup.frame.height) }, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { imageTransition = ImageTransition() imageTransition.duration = 0.3 var fromViewController = segue.sourceViewController as FrontEditViewController if segue.identifier == "fontSegue" { var toViewController = segue.destinationViewController as FontViewController toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom toViewController.transitioningDelegate = imageTransition } else if segue.identifier == "stickerSegue" { var toViewController = segue.destinationViewController as StickerViewController toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom toViewController.transitioningDelegate = imageTransition } else if segue.identifier == "templateSegue" { var toViewController = segue.destinationViewController as TemplateViewController toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom toViewController.transitioningDelegate = imageTransition } else if segue.identifier == "saveFontSegue" { hideMenu() var toViewController = segue.destinationViewController as FakeFrontViewController toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom toViewController.transitioningDelegate = imageTransition } } }
11ad97524b4a069f27f0b5af1576553e
41.009009
151
0.66781
false
false
false
false
a2/Gulliver
refs/heads/master
Gulliver Tests/Source/SocialProfileSpec.swift
mit
1
import AddressBook import Gulliver import Nimble import Quick class SocialProfileSpec: QuickSpec { override func spec() { describe("multiValueRepresentation") { it("should contain the correct data") { let profile = SocialProfile(URL: "http://twitter.com/jbgoode", service: SocialProfile.Services.Twitter, username: "@jbgoode", userIdentifier: nil) let mvr = profile.multiValueRepresentation as! [NSObject : AnyObject] expect((mvr[kABPersonSocialProfileURLKey as String] as! String)) == "http://twitter.com/jbgoode" expect((mvr[kABPersonSocialProfileServiceKey as String] as! String)) == kABPersonSocialProfileServiceTwitter as String expect((mvr[kABPersonSocialProfileUsernameKey as String] as! String)) == "@jbgoode" expect(mvr[kABPersonSocialProfileUserIdentifierKey as String]).to(beNil()) } it("is a valid representation") { let profile = SocialProfile(URL: "http://twitter.com/jbgoode", service: SocialProfile.Services.Twitter, username: "@jbgoode", userIdentifier: nil) let multiValue: ABMutableMultiValueRef = ABMultiValueCreateMutable(numericCast(kABDictionaryPropertyType)).takeRetainedValue() if !ABMultiValueAddValueAndLabel(multiValue, profile.multiValueRepresentation, kABWorkLabel, nil) { fail("Could not add profile to multi value") } let record: ABRecordRef = ABPersonCreate().takeRetainedValue() var error: Unmanaged<CFErrorRef>? = nil if !ABRecordSetValue(record, kABPersonSocialProfileProperty, multiValue, &error) { let nsError = (error?.takeUnretainedValue()).map { unsafeBitCast($0, NSError.self) } fail("Could not set value on record: \(nsError?.localizedDescription)") } } } describe("init(multiValueRepresentation:)") { it("creates a valid SocialProfile") { let representation: [NSObject : AnyObject] = [ kABPersonSocialProfileURLKey as String: "http://twitter.com/jbgoode", kABPersonSocialProfileServiceKey as String: kABPersonSocialProfileServiceTwitter as String, kABPersonSocialProfileUsernameKey as String: "@jbgoode", ] let profile = SocialProfile(multiValueRepresentation: representation) expect(profile).notTo(beNil()) expect(profile!.URL) == "http://twitter.com/jbgoode" expect(profile!.service) == SocialProfile.Services.Twitter expect(profile!.username) == "@jbgoode" } it("works with vCard data") { let fileURL = NSBundle(forClass: PostalAddressSpec.self).URLForResource("Johnny B. Goode", withExtension: "vcf")! let data = NSData(contentsOfURL: fileURL)! let records = ABPersonCreatePeopleInSourceWithVCardRepresentation(nil, data as CFDataRef).takeRetainedValue() as [ABRecordRef] let multiValue: ABMultiValueRef = ABRecordCopyValue(records[0], kABPersonSocialProfileProperty).takeRetainedValue() let values = LabeledValue<SocialProfile>.read(multiValue) expect(values[0].label) == kABWorkLabel as String expect(values[0].value) == SocialProfile(URL: "http://twitter.com/jbgoode", service: SocialProfile.Services.Twitter, username: "jbgoode", userIdentifier: nil) expect(values[1].label) == kABWorkLabel as String expect(values[1].value) == SocialProfile(URL: "http://facebook.com/johnny.b.goode", service: SocialProfile.Services.Facebook, username: "johnny.b.goode", userIdentifier: nil) } } } }
7b1667ef598bdc91c2919382985baca1
59.625
190
0.641237
false
false
false
false
muukii/StackScrollView
refs/heads/master
StackScrollView/StackScrollView.swift
mit
1
// StackScrollView.swift // // Copyright (c) 2016 muukii // // 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 StackScrollView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private enum LayoutKeys { static let top = "me.muukii.StackScrollView.top" static let right = "me.muukii.StackScrollView.right" static let left = "me.muukii.StackScrollView.left" static let bottom = "me.muukii.StackScrollView.bottom" static let width = "me.muukii.StackScrollView.width" static let height = "me.muukii.StackScrollView.height" } private static func defaultLayout() -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = .zero return layout } @available(*, unavailable) open override var dataSource: UICollectionViewDataSource? { didSet { } } @available(*, unavailable) open override var delegate: UICollectionViewDelegate? { didSet { } } private var direction: UICollectionView.ScrollDirection { (collectionViewLayout as! UICollectionViewFlowLayout).scrollDirection } // MARK: - Initializers public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) setup() } public convenience init(frame: CGRect) { self.init(frame: frame, collectionViewLayout: StackScrollView.defaultLayout()) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private(set) public var views: [UIView] = [] private func identifier(_ v: UIView) -> String { return v.hashValue.description } private func setup() { backgroundColor = .white switch direction { case .vertical: alwaysBounceVertical = true case .horizontal: alwaysBounceHorizontal = true @unknown default: fatalError() } delaysContentTouches = false keyboardDismissMode = .interactive backgroundColor = .clear super.delegate = self super.dataSource = self } open override func touchesShouldCancel(in view: UIView) -> Bool { return true } open func append(view: UIView) { views.append(view) register(Cell.self, forCellWithReuseIdentifier: identifier(view)) reloadData() } open func append(views _views: [UIView]) { views += _views _views.forEach { view in register(Cell.self, forCellWithReuseIdentifier: identifier(view)) } reloadData() } @available(*, unavailable, message: "Unimplemented") func append(lazy: @escaping () -> UIView) { } open func insert(views _views: [UIView], at index: Int, animated: Bool, completion: @escaping () -> Void) { layoutIfNeeded() var _views = _views _views.removeAll(where: views.contains(_:)) views.insert(contentsOf: _views, at: index) _views.forEach { view in register(Cell.self, forCellWithReuseIdentifier: identifier(view)) } let batchUpdates: () -> Void = { self.performBatchUpdates({ self.insertItems(at: (index ..< index.advanced(by: _views.count)).map({ IndexPath(item: $0, section: 0) })) }, completion: { _ in completion() }) } if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: batchUpdates, completion: nil) } else { UIView.performWithoutAnimation(batchUpdates) } } open func insert(views _views: [UIView], before view: UIView, animated: Bool, completion: @escaping () -> Void = {}) { guard let index = views.firstIndex(of: view) else { completion() return } insert(views: _views, at: index, animated: animated, completion: completion) } open func insert(views _views: [UIView], after view: UIView, animated: Bool, completion: @escaping () -> Void = {}) { guard let index = views.firstIndex(of: view)?.advanced(by: 1) else { completion() return } insert(views: _views, at: index, animated: animated, completion: completion) } open func remove(view: UIView, animated: Bool, completion: @escaping () -> Void = {}) { layoutIfNeeded() if let index = views.firstIndex(of: view) { views.remove(at: index) if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: { self.performBatchUpdates({ self.deleteItems(at: [IndexPath(item: index, section: 0)]) }, completion: { _ in completion() }) }) { (finish) in } } else { UIView.performWithoutAnimation { performBatchUpdates({ self.deleteItems(at: [IndexPath(item: index, section: 0)]) }, completion: { _ in completion() }) } } } } open func remove(views: [UIView], animated: Bool, completion: @escaping () -> Void = {}) { layoutIfNeeded() var indicesForRemove: [Int] = [] for view in views { if let index = self.views.firstIndex(of: view) { indicesForRemove.append(index) } } // It seems that the layout is not updated properly unless the order is aligned. indicesForRemove.sort(by: >) for index in indicesForRemove { self.views.remove(at: index) } if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: { self.performBatchUpdates({ self.deleteItems(at: indicesForRemove.map { IndexPath.init(item: $0, section: 0) }) }, completion: { _ in completion() }) }) } else { UIView.performWithoutAnimation { performBatchUpdates({ self.deleteItems(at: indicesForRemove.map { IndexPath.init(item: $0, section: 0) }) }, completion: { _ in completion() }) } } } /// This method might fail if the view is out of bounds. Use `func scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool)` instead @available(*, deprecated, message: "Use `scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool)` instead") open func scroll(to view: UIView, animated: Bool) { let targetRect = view.convert(view.bounds, to: self) scrollRectToVisible(targetRect, animated: true) } open func scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool) { if let index = views.firstIndex(of: view) { scrollToItem(at: IndexPath(item: index, section: 0), at: position, animated: animated) } } public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return views.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let view = views[indexPath.item] let _identifier = identifier(view) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: _identifier, for: indexPath) if view.superview == cell.contentView { return cell } precondition(cell.contentView.subviews.isEmpty) if view is ManualLayoutStackCellType { cell.contentView.addSubview(view) } else { view.translatesAutoresizingMaskIntoConstraints = false cell.contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] cell.contentView.addSubview(view) let top = view.topAnchor.constraint(equalTo: cell.contentView.topAnchor) let right = view.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor) let bottom = view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor) let left = view.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor) top.identifier = LayoutKeys.top right.identifier = LayoutKeys.right bottom.identifier = LayoutKeys.bottom left.identifier = LayoutKeys.left NSLayoutConstraint.activate([ top, right, bottom, left, ]) } return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let view = views[indexPath.item] if let view = view as? ManualLayoutStackCellType { switch direction { case .vertical: return view.size(maxWidth: collectionView.bounds.width, maxHeight: nil) case .horizontal: return view.size(maxWidth: nil, maxHeight: collectionView.bounds.height) @unknown default: fatalError() } } else { switch direction { case .vertical: let width: NSLayoutConstraint = { guard let c = view.constraints.first(where: { $0.identifier == LayoutKeys.width }) else { let width = view.widthAnchor.constraint(equalToConstant: collectionView.bounds.width) width.identifier = LayoutKeys.width width.isActive = true return width } return c }() width.constant = collectionView.bounds.width let size = view.superview?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) return size case .horizontal: let heightConstraint: NSLayoutConstraint = { guard let c = view.constraints.first(where: { $0.identifier == LayoutKeys.height }) else { let heightConstraint = view.heightAnchor.constraint(equalToConstant: collectionView.bounds.height) heightConstraint.identifier = LayoutKeys.height heightConstraint.isActive = true return heightConstraint } return c }() heightConstraint.constant = collectionView.bounds.height let size = view.superview?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) return size @unknown default: fatalError() } } } public func updateLayout(animated: Bool) { if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: { self.performBatchUpdates(nil, completion: nil) self.layoutIfNeeded() }) { (finish) in } } else { UIView.performWithoutAnimation { self.performBatchUpdates(nil, completion: nil) self.layoutIfNeeded() } } } final class Cell: UICollectionViewCell { override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { return layoutAttributes } } }
8e536156b7aff63e7cdc6815cd8dcb86
29.515012
165
0.656475
false
false
false
false
jeden/jsonablest
refs/heads/master
jsonablest/JsonablestTests/EncodingTests.swift
mit
1
// // EncodingTests.swift // EncodingTests // // Created by Antonio Bello on 6/4/16. // // import XCTest import Jsonablest private let someTimeInterval: TimeInterval = 1494261446.378659 private let someTimestamp = Date(timeIntervalSince1970: someTimeInterval) class EncodingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAutomaticEncodeSuccess() { let expectedDictionary: JsonDictionary = [ "oneString": "one", "twoInt": 2, "threeFloat": 3.0, "fourDouble": 4.0, "fiveBool": true, "sixDate": someTimestamp.toIso8610(), "sevenOptional": 7, ] let structure = StructWithNoExplicitEncode(oneString: "one", twoInt: 2, threeFloat: 3.0, fourDouble: 4.0, fiveBool: true, sixDate: Date(timeIntervalSince1970: someTimeInterval), sevenOptional: 7, eightNil: nil) let exportedDictionary = structure.jsonEncode() XCTAssert(exportedDictionary == expectedDictionary, "No match: \(exportedDictionary)") } func testAutomaticEncodeShouldFailWithWrongValue() { let value = SimpleInt(value: 1) let correctExpectation: JsonDictionary = ["value": 1] let wrongExpectation: JsonDictionary = [ "value": 2] let exported = value.jsonEncode() XCTAssert(correctExpectation == exported, "The actual json encoding doesn't match with the expected") XCTAssertFalse(wrongExpectation == exported, "the json encoding should be different than the expected wrong dictionary") } func testAutomaticEncodeWithEmbeddedJsonEncodables() { let embedded = SimpleInt(value: 10) let value = EmbeddingStruct(embedded: embedded) let expected: JsonDictionary = [ "embedded": [ "value": 10 ] as JsonType ] let exported = value.jsonEncode() XCTAssert(expected == exported, "The generated json doens't match the expected one") } func testAutomaticEncodeWithIgnoredFields() { let value = FieldsWithIgnores(exported: "yes", ignored: true) let expected: JsonDictionary = [ "exported": "yes" ] let exported = value.jsonEncode() XCTAssert(expected == exported, "The generated json doens't match the expected one") } func testAutomaticEncodeWithReplacementFields() { let value = FieldsWithReplacements(original: "yes", replaced: "it should be replaced") let expected: JsonDictionary = [ "original": "yes", "replacement": "it should be replaced" ] let exported = value.jsonEncode() XCTAssert(expected == exported, "The generated json doens't match the expected one") } } // MARK: Internal structures /// A struct not having a jsonEncode() method, so using the default // one implemented in the protocol extension private struct StructWithNoExplicitEncode : JsonEncodable { let oneString : String let twoInt: Int let threeFloat: Float let fourDouble: Double let fiveBool: Bool let sixDate: Date let sevenOptional: Int? let eightNil: Bool? } private struct SimpleInt : JsonEncodable { let value: Int } private struct EmbeddingStruct : JsonEncodable { let embedded: SimpleInt } private struct FieldsWithIgnores : JsonEncodable { let exported: String let ignored: Bool } extension FieldsWithIgnores : JsonEncodingIgnorable { var jsonFieldIgnores : [String] { return ["ignored"] } } private struct FieldsWithReplacements : JsonEncodable { let original: String let replaced: String } extension FieldsWithReplacements : JsonEncodingReplaceable { var jsonFieldReplacements : [String : String] { return [ "replaced": "replacement" ] } } private func == (op1: JsonDictionary, op2: JsonDictionary) -> Bool { return NSDictionary(dictionary: op1).isEqual(to: op2) }
087dfac0b96fd4990de25e726943e1c6
27.895522
212
0.731921
false
true
false
false
bwide/Sorting-Algorithms-Playground
refs/heads/master
Sorting algorithms.playground/Pages/QuickSort.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import UIKit import PlaygroundSupport let size = 200 let array = VisualSortableArray.init(arraySize: size) func elementAt(index: Int) -> Int { return array.get(index: index) } func swap(i: Int, j: Int){ return array.swap(i: i, j: j) } func select(i: Int, j: Int) -> Bool { return array.select(i: i, j: j) } PlaygroundPage.current.liveView = array.view DispatchQueue.global(qos: .background).async { sleep(2) func quickSort(array: VisualSortableArray, fromLeftIndex leftIndex: Int, toRightIndex rightIndex: Int) { let index = partition(array: array, fromLeftIndex: leftIndex, toRightIndex: rightIndex) if leftIndex < index - 1 { quickSort(array: array, fromLeftIndex: leftIndex, toRightIndex: index - 1) } if index < rightIndex { quickSort(array: array, fromLeftIndex: index, toRightIndex: rightIndex) } } func partition(array: VisualSortableArray, fromLeftIndex leftIndex: Int, toRightIndex rightIndex: Int) -> Int { var localLeftIndex = leftIndex var localRightIndex = rightIndex let pivot = elementAt(index: (localLeftIndex + localRightIndex) / 2) while localLeftIndex <= localRightIndex { while elementAt(index: localLeftIndex) < pivot { localLeftIndex += 1 select(i: localLeftIndex, j: localRightIndex) } while localRightIndex > 0 && elementAt(index: localRightIndex) > pivot { localRightIndex -= 1 select(i: localLeftIndex, j: localRightIndex) } if localLeftIndex <= localRightIndex { if localLeftIndex != localRightIndex { swap(i: localLeftIndex, j: localRightIndex) } localLeftIndex += 1 if localRightIndex > 0 { localRightIndex -= 1 select(i: localLeftIndex, j: localRightIndex) } } } return localLeftIndex } quickSort(array: array, fromLeftIndex: 0, toRightIndex: array.count - 1) } //: [Next](@next)
f04d312784e6e45e11982a8aa60b8a11
28.474359
115
0.572423
false
false
false
false
aboutsajjad/Bridge
refs/heads/master
Bridge/DownloadCoordinator/DownloadTableViewCell.swift
mit
1
// // DownloadTableViewCell.swift // Bridge // // Created by Sajjad Aboutalebi on 5/11/18. // Copyright © 2018 Sajjad Aboutalebi. All rights reserved. // import UIKit import MZDownloadManager import SnapKit import MBCircularProgressBar class DownloadTableViewCell: UITableViewCell { lazy var progressview: MBCircularProgressBarView = { let pv = MBCircularProgressBarView() pv.maxValue = 100 pv.progressAngle = 90 pv.progressLineWidth = 1 pv.progressColor = .blue pv.progressStrokeColor = .purple pv.backgroundColor = .white return pv }() lazy var titlelabel: UILabel = { let lb = UILabel() lb.font = lb.font.withSize(16) lb.numberOfLines = 2 return lb }() lazy var remainingLabel: UILabel = { let lb = UILabel() lb.font = lb.font.withSize(15) lb.textColor = .gray return lb }() lazy var speedLabel: UILabel = { let lb = UILabel() lb.font = lb.font.withSize(14) lb.numberOfLines = 0 lb.textColor = .lightGray return lb }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(progressview) addSubview(titlelabel) addSubview(remainingLabel) addSubview(speedLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() progressview.snp.makeConstraints { (maker) in maker.top.left.equalToSuperview().offset(5) maker.height.equalTo(70) maker.width.equalTo(progressview.snp.height) maker.bottom.equalToSuperview().offset(-5) } titlelabel.snp.remakeConstraints { (maker) in maker.top.equalToSuperview() maker.left.equalTo(progressview.snp.right).offset(5) maker.right.equalToSuperview() } remainingLabel.snp.remakeConstraints { (maker) in maker.top.equalTo(titlelabel.snp.bottom) maker.left.equalTo(progressview.snp.right).offset(5) } speedLabel.snp.remakeConstraints { (maker) in maker.top.equalTo(remainingLabel.snp.bottom) maker.left.equalTo(progressview.snp.right).offset(5) maker.bottom.equalToSuperview() } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func updateCellForRowAtIndexPath(_ indexPath : IndexPath, downloadModel: MZDownloadModel) { titlelabel.text = downloadModel.fileName remainingLabel.text = "\((Double(downloadModel.progress)*1000).rounded()/10)% - \(downloadModel.downloadedFile?.size.roundTo() ?? "0") \(downloadModel.downloadedFile?.unit ?? "KB") of \(downloadModel.file?.size.roundTo() ?? "0") \(downloadModel.file?.unit ?? "KB")" speedLabel.text = "\(downloadModel.speed?.speed.roundTo() ?? "0") \(downloadModel.speed?.unit ?? "KB")/s - \(downloadModel.remainingTime?.hours ?? 0) houre(s) and \(downloadModel.remainingTime?.minutes ?? 0) remaining" progressview.value = CGFloat(downloadModel.progress) * 100 } }
7af74ea6bd07fdb49b7638c7212c61b4
33.435644
273
0.627085
false
false
false
false
garygriswold/Bible.js
refs/heads/master
SafeBible2/SafeBible_ios/SafeBible/Models/ReaderViewQueue.swift
mit
1
// // ReaderViewQueue.swift // Settings // // Created by Gary Griswold on 11/9/18. // Copyright © 2018 ShortSands. All rights reserved. // import UIKit class ReaderViewQueue { static let shared = ReaderViewQueue() private enum PreviousCall { case first case next case prior case preload } private static let QUEUE_MAX: Int = 10 private static let EXTRA_NEXT: Int = 1 private static let EXTRA_PRIOR: Int = 1 private var queue: [ReaderViewController] private var unused: Set<ReaderViewController> private var previousCall: PreviousCall private init() { self.queue = [ReaderViewController]() self.unused = Set<ReaderViewController>() self.previousCall = .first } func first(reference: Reference) -> ReaderViewController { self.previousCall = .first for controller in self.queue { self.addUnused(controller: controller) } self.queue.removeAll() let controller = self.getUnused(reference: reference) self.queue.append(controller) return controller } /** * The ReaderViewController is one that is already in the queue. * So, it is guarantteed to be found within the list. */ func next(controller: UIViewController) -> ReaderViewController? { self.previousCall = .next if let index = self.findController(controller: controller) { if index < (queue.count - 1) { return self.queue[index + 1] } else { return appendAfter() } } else { return nil } } func prior(controller: UIViewController) -> ReaderViewController? { self.previousCall = .prior if let index = self.findController(controller: controller) { if index > 0 { return self.queue[index - 1] } else { return insertBefore() } } else { return nil } } /** * UIPageViewController is usually calling next and prior to preload the next and prior pages, * but never for the initial set, and only most of the time when the page is swiped. * This method is called after any page is loaded to add one additional pages before and or after */ func preload() { switch self.previousCall { case .first: _ = self.appendAfter() _ = self.insertBefore() case .next: _ = self.appendAfter() case .prior: _ = self.insertBefore() case .preload: _ = 1 // do nothing } self.previousCall = .preload } func updateCSS(css: String) { print("update Rule in ReaderViewQueue: \(css)") for webView in self.queue { webView.execJavascript(message: css) } } func reloadIfActive(reference: Reference) { for reader in self.queue { if reader.reference == reference { reader.reloadReference() return } } } private func appendAfter() -> ReaderViewController { let reference = self.queue.last!.reference! let controller = self.getUnused(reference: reference.nextChapter()) self.queue.append(controller) if self.queue.count > ReaderViewQueue.QUEUE_MAX { let first = self.queue.removeFirst() self.addUnused(controller: first) } return controller } private func insertBefore() -> ReaderViewController { let reference = self.queue[0].reference! let controller = self.getUnused(reference: reference.priorChapter()) self.queue.insert(controller, at: 0) if self.queue.count > ReaderViewQueue.QUEUE_MAX { let last = self.queue.removeLast() self.addUnused(controller: last) } return controller } private func getUnused(reference: Reference) -> ReaderViewController { var webView = self.unused.popFirst() if webView == nil { webView = ReaderViewController() } webView!.clearWebView() // Needed to clear old content off page, 0.4 ms to 0.0ms webView!.loadReference(reference: reference) // The page is loaded when this is called return webView! } private func addUnused(controller: ReaderViewController) { controller.view.removeFromSuperview() self.unused.insert(controller) } private func findController(controller: UIViewController) -> Int? { guard let readController = controller as? ReaderViewController else { fatalError("ReaderViewQueue.findController must receive ReaderViewController") } let reference = readController.reference! for index in 0..<self.queue.count { if self.queue[index].reference == reference { return index } } return nil } }
2c912fbf9cc5dcbd8c23220c14e55cac
30.487654
100
0.590472
false
false
false
false
mattjgalloway/emoncms-ios
refs/heads/master
EmonCMSiOS/Controllers/LoginController.swift
mit
1
// // LoginController.swift // EmonCMSiOS // // Created by Matt Galloway on 13/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation import RxSwift import RxCocoa import Locksmith final class LoginController { enum LoginControllerError: Error { case Generic case KeychainFailed } private var _account = Variable<Account?>(nil) let account: Observable<Account?> init() { self.account = _account.asObservable().shareReplay(1) self.loadAccount() } private func loadAccount() { guard let accountURL = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue), let accountUUIDString = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue), let accountUUID = UUID(uuidString: accountUUIDString) else { return } guard let data = Locksmith.loadDataForUserAccount(userAccount: accountUUIDString), let apikey = data["apikey"] as? String else { return } let account = Account(uuid: accountUUID, url: accountURL, apikey: apikey) self._account.value = account } func login(withAccount account: Account) throws { do { if let currentAccount = _account.value { if currentAccount == account { return } } let data = ["apikey": account.apikey] do { try Locksmith.saveData(data: data, forUserAccount: account.uuid.uuidString) } catch LocksmithError.duplicate { // We already have it, let's try updating it try Locksmith.updateData(data: data, forUserAccount: account.uuid.uuidString) } UserDefaults.standard.set(account.url, forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue) UserDefaults.standard.set(account.uuid.uuidString, forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue) self._account.value = account } catch { throw LoginControllerError.KeychainFailed } } func logout() throws { guard let accountURL = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue) else { throw LoginControllerError.Generic } do { try Locksmith.deleteDataForUserAccount(userAccount: accountURL) UserDefaults.standard.removeObject(forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue) self._account.value = nil } catch { throw LoginControllerError.KeychainFailed } } }
2c74364d5816368ed266f6ff35f4982e
29.353659
125
0.709522
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
stdlib/public/core/HeapBuffer.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims typealias _HeapObject = SwiftShims.HeapObject @warn_unused_result @_silgen_name("swift_bufferAllocate") func _swift_bufferAllocate( bufferType: AnyClass, _ size: Int, _ alignMask: Int) -> AnyObject /// A class containing an ivar "value" of type Value, and /// containing storage for an array of Element whose size is /// determined at create time. /// /// The analogous C++-ish class template would be: /// /// template <class Value, class Element> /// struct _HeapBuffer { /// Value value; /// Element baseAddress[]; // length determined at creation time /// /// _HeapBuffer() = delete /// static shared_ptr<_HeapBuffer> create(Value init, int capacity); /// } /// /// Note that the Element array is RAW MEMORY. You are expected to /// construct and---if necessary---destroy Elements there yourself, /// either in a derived class, or it can be in some manager object /// that owns the _HeapBuffer. public // @testable (test/Prototypes/MutableIndexableDict.swift) class _HeapBufferStorage<Value,Element> : NonObjectiveCBase { public override init() {} /// The type used to actually manage instances of /// `_HeapBufferStorage<Value,Element>`. typealias Buffer = _HeapBuffer<Value, Element> deinit { Buffer(self)._value.destroy() } @warn_unused_result final func __getInstanceSizeAndAlignMask() -> (Int,Int) { return Buffer(self)._allocatedSizeAndAlignMask() } } /// Management API for `_HeapBufferStorage<Value, Element>` public // @testable struct _HeapBuffer<Value, Element> : Equatable { /// A default type to use as a backing store. typealias Storage = _HeapBufferStorage<Value, Element> // _storage is passed inout to _isUnique. Although its value // is unchanged, it must appear mutable to the optimizer. var _storage: Builtin.NativeObject? public // @testable var storage: AnyObject? { return _storage.map { Builtin.castFromNativeObject($0) } } @warn_unused_result static func _valueOffset() -> Int { return _roundUpToAlignment(sizeof(_HeapObject.self), alignof(Value.self)) } @warn_unused_result static func _elementOffset() -> Int { return _roundUpToAlignment(_valueOffset() + sizeof(Value.self), alignof(Element.self)) } @warn_unused_result static func _requiredAlignMask() -> Int { // We can't use max here because it can allocate an array. let heapAlign = alignof(_HeapObject.self) &- 1 let valueAlign = alignof(Value.self) &- 1 let elementAlign = alignof(Element.self) &- 1 return (heapAlign < valueAlign ? (valueAlign < elementAlign ? elementAlign : valueAlign) : (heapAlign < elementAlign ? elementAlign : heapAlign)) } var _address: UnsafeMutablePointer<Int8> { return UnsafeMutablePointer( Builtin.bridgeToRawPointer(self._nativeObject)) } var _value: UnsafeMutablePointer<Value> { return UnsafeMutablePointer( _HeapBuffer._valueOffset() + _address) } public // @testable var baseAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(_HeapBuffer._elementOffset() + _address) } @warn_unused_result func _allocatedSize() -> Int { return _swift_stdlib_malloc_size(_address) } @warn_unused_result func _allocatedAlignMask() -> Int { return _HeapBuffer._requiredAlignMask() } @warn_unused_result func _allocatedSizeAndAlignMask() -> (Int, Int) { return (_allocatedSize(), _allocatedAlignMask()) } /// Return the actual number of `Elements` we can possibly store. @warn_unused_result func _capacity() -> Int { return (_allocatedSize() - _HeapBuffer._elementOffset()) / strideof(Element.self) } init() { self._storage = nil } public // @testable init(_ storage: _HeapBufferStorage<Value,Element>) { self._storage = Builtin.castToNativeObject(storage) } init(_ storage: AnyObject) { _sanityCheck( _usesNativeSwiftReferenceCounting(storage.dynamicType), "HeapBuffer manages only native objects" ) self._storage = Builtin.castToNativeObject(storage) } init<T : AnyObject>(_ storage: T?) { self = storage.map { _HeapBuffer($0) } ?? _HeapBuffer() } init(nativeStorage: Builtin.NativeObject?) { self._storage = nativeStorage } /// Create a `_HeapBuffer` with `self.value = initializer` and /// `self._capacity() >= capacity`. public // @testable init( _ storageClass: AnyClass, _ initializer: Value, _ capacity: Int ) { _sanityCheck(capacity >= 0, "creating a _HeapBuffer with negative capacity") _sanityCheck( _usesNativeSwiftReferenceCounting(storageClass), "HeapBuffer can only create native objects" ) let totalSize = _HeapBuffer._elementOffset() + capacity * strideof(Element.self) let alignMask = _HeapBuffer._requiredAlignMask() let object: AnyObject = _swift_bufferAllocate( storageClass, totalSize, alignMask) self._storage = Builtin.castToNativeObject(object) self._value.initialize(initializer) } public // @testable var value : Value { unsafeAddress { return UnsafePointer(_value) } nonmutating unsafeMutableAddress { return _value } } /// `true` if storage is non-`nil`. var hasStorage: Bool { return _storage != nil } subscript(i: Int) -> Element { unsafeAddress { return UnsafePointer(baseAddress + i) } nonmutating unsafeMutableAddress { return baseAddress + i } } var _nativeObject: Builtin.NativeObject { return _storage! } @warn_unused_result static func fromNativeObject(x: Builtin.NativeObject) -> _HeapBuffer { return _HeapBuffer(nativeStorage: x) } @warn_unused_result public // @testable mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } @warn_unused_result public // @testable mutating func isUniquelyReferencedOrPinned() -> Bool { return _isUniqueOrPinned(&_storage) } } // HeapBuffers are equal when they reference the same buffer @warn_unused_result public // @testable func == <Value, Element> ( lhs: _HeapBuffer<Value, Element>, rhs: _HeapBuffer<Value, Element>) -> Bool { return lhs._nativeObject == rhs._nativeObject }
fdf26bb67081d81d39bdc2e01e61d29b
28.133047
80
0.667207
false
false
false
false
tryswift/TryParsec
refs/heads/swift/4.0
Sources/TryParsec/Parser+Combinator.swift
mit
1
import Runes //infix operator >>- : RunesMonadicPrecedenceLeft // redefine /// Parses zero or one occurrence of `p`. /// - SeeAlso: Haskell Parsec's `optionMaybe`. public func zeroOrOne<In, Out>(_ p: Parser<In, Out>) -> Parser<In, Out?> { return (p <&> { Optional($0) }) <|> pure(nil) } /// Parses zero or more occurrences of `p`. /// - Note: Returning parser never fails. public func many<In, Out, Outs: RangeReplaceableCollection>(_ p: Parser<In, Out>) -> Parser<In, Outs> where Outs.Iterator.Element == Out { return many1(p) <|> pure(Outs()) } /// Parses one or more occurrences of `p`. public func many1<In, Out, Outs: RangeReplaceableCollection>(_ p: Parser<In, Out>) -> Parser<In, Outs> where Outs.Iterator.Element == Out { return cons <^> p <*> many(p) } /// Parses one or more occurrences of `p` until `end` succeeds, /// and returns the list of values returned by `p`. public func manyTill<In, Out, Out2, Outs: RangeReplaceableCollection>( _ p: Parser<In, Out>, _ end: Parser<In, Out2> ) -> Parser<In, Outs> where Outs.Iterator.Element == Out { return fix { recur in { _ in (end *> pure(Outs())) <|> (cons <^> p <*> recur(())) }}(()) } /// Skips zero or more occurrences of `p`. /// - Note: Returning parser never fails. public func skipMany<In, Out>(_ p: Parser<In, Out>) -> Parser<In, ()> { return skipMany1(p) <|> pure(()) } /// Skips one or more occurrences of `p`. public func skipMany1<In, Out>(_ p: Parser<In, Out>) -> Parser<In, ()> { return p *> skipMany(p) } /// Separates zero or more occurrences of `p` using separator `sep`. /// - Note: Returning parser never fails. public func sepBy<In, Out, Outs: RangeReplaceableCollection, Sep>( _ p: Parser<In, Out>, _ separator: Parser<In, Sep> ) -> Parser<In, Outs> where Outs.Iterator.Element == Out { return sepBy1(p, separator) <|> pure(Outs()) } /// Separates one or more occurrences of `p` using separator `sep`. public func sepBy1<In, Out, Outs: RangeReplaceableCollection, Sep>( _ p: Parser<In, Out>, _ separator: Parser<In, Sep> ) -> Parser<In, Outs> where Outs.Iterator.Element == Out { return cons <^> p <*> many(separator *> p) } /// Separates zero or more occurrences of `p` using optionally-ended separator `sep`. /// - Note: Returning parser never fails. public func sepEndBy<In, Out, Outs: RangeReplaceableCollection, Sep>( _ p: Parser<In, Out>, _ separator: Parser<In, Sep> ) -> Parser<In, Outs> where Outs.Iterator.Element == Out { return sepEndBy1(p, separator) <|> pure(Outs()) } /// Separates one or more occurrences of `p` using optionally-ended separator `sep`. public func sepEndBy1<In, Out, Outs: RangeReplaceableCollection, Sep>( _ p: Parser<In, Out>, _ separator: Parser<In, Sep> ) -> Parser<In, Outs> where Outs.Iterator.Element == Out { return p >>- { x in ((separator *> sepEndBy(p, separator)) >>- { xs in pure(Outs(x) + xs) }) <|> pure(Outs(x)) } } /// Parses `n` occurrences of `p`. public func count<In, Out, Outs: RangeReplaceableCollection>( _ n: Int, _ p: Parser<In, Out> ) -> Parser<In, Outs> where Outs.Iterator.Element == Out { guard n > 0 else { return pure(Outs()) } return cons <^> p <*> count(n-1, p) } /// /// Parses zero or more occurrences of `p`, separated by `op` /// which left-associates multiple outputs from `p` by applying its binary operation. /// /// If there are zero occurrences of `p`, default value `x` is returned. /// /// - Note: Returning parser never fails. /// public func chainl<In, Out>( _ p: Parser<In, Out>, _ op: Parser<In, (Out, Out) -> Out>, _ x: Out ) -> Parser<In, Out> { return chainl1(p, op) <|> pure(x) } /// /// Parses one or more occurrences of `p`, separated by `op` /// which left-associates multiple outputs from `p` by applying its binary operation. /// /// This parser can be used to eliminate left recursion which typically occurs in expression grammars. /// /// For example (pseudocode): /// /// ``` /// let expr = chainl1(term, symbol("-") *> pure(-)) /// ``` /// /// can be interpretted as: /// /// ``` /// // [EBNF] expr = term { - term } /// let expr = curry({ $1.reduce($0, combine: -) }) <^> term <*> many(symbol("-") *> term) /// ``` /// /// but more efficient since `chainl1` doesn't use `many` to convert to /// `RangeReplaceableCollectionType` first and then `reduce`. /// public func chainl1<In, Out>( _ p: Parser<In, Out>, _ op: Parser<In, (Out, Out) -> Out> ) -> Parser<In, Out> { return p >>- { x in fix { recur in { x in (op >>- { f in p >>- { y in recur(f(x, y)) } }) <|> pure(x) }}(x) } } /// /// Parses zero or more occurrences of `p`, separated by `op` /// which right-associates multiple outputs from `p` by applying its binary operation. /// /// If there are zero occurrences of `p`, default value `x` is returned. /// /// - Note: Returning parser never fails. /// public func chainr<In, Out>( _ p: Parser<In, Out>, _ op: Parser<In, (Out, Out) -> Out>, _ x: Out ) -> Parser<In, Out> { return chainr1(p, op) <|> pure(x) } /// Parses one or more occurrences of `p`, separated by `op` /// which right-associates multiple outputs from `p` by applying its binary operation. public func chainr1<In, Out>( _ p: Parser<In, Out>, _ op: Parser<In, (Out, Out) -> Out> ) -> Parser<In, Out> { return fix { recur in { _ in p >>- { x in (op >>- { f in recur(()) >>- { y in pure(f(x, y)) } }) <|> pure(x) } }}(()) } /// Applies `p` without consuming any input. public func lookAhead<In, Out>(_ p: Parser<In, Out>) -> Parser<In, Out> { return Parser { input in let reply = parse(p, input) switch reply { case .fail: return reply case let .done(_, output): return .done(input, output) } } } /// Folds `parsers` using Alternative's `<|>`. public func choice<In, Out, S: Sequence>(_ parsers: S) -> Parser<In, Out> where S.Iterator.Element == Parser<In, Out> { return parsers.reduce(empty(), { $0 <|> $1 }) }
e1050c9ec0b7968282877d5d6602d074
28.124424
137
0.585918
false
false
false
false
1457792186/JWSwift
refs/heads/master
SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGAssetViewController.swift
apache-2.0
1
// // LGAssetViewController.swift // LGWeChatKit // // Created by jamy on 10/28/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit import Photos private let reuseIdentifier = "assetviewcell" class LGAssetViewController: UIViewController { var collectionView: UICollectionView! var currentIndex: IndexPath! var selectButton: UIButton! var playButton: UIBarButtonItem! var cellSize: CGSize! var assetModels = [LGAssetModel]() var selectedInfo: NSMutableArray? var selectIndex = 0 lazy var imageManager: PHCachingImageManager = { return PHCachingImageManager() }() override func viewDidLoad() { super.viewDidLoad() setupCollectionView() cellSize = (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize collectionView.selectItem(at: IndexPath(item: selectIndex, section: 0), animated: false, scrollPosition: .centeredHorizontally) } func setupCollectionView() { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: view.bounds.width, height: view.bounds.height - 64) layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) collectionView.register(LGAssetViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) collectionView.backgroundColor = UIColor.white collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.dataSource = self collectionView.delegate = self view.addSubview(collectionView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNavgationBar() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } func setupNavgationBar() { let button = UIButton(type: .custom) button.setImage(UIImage(named: "CellGreySelected"), for: UIControlState()) button.frame = CGRect(x: 0, y: 0, width: 30, height: 30) button.addTarget(self, action: #selector(LGAssetViewController.selectCurrentImage), for: .touchUpInside) let item = UIBarButtonItem(customView: button) navigationItem.rightBarButtonItem = item selectButton = button let cancelButton = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(LGAssetViewController.dismissView)) navigationItem.leftBarButtonItem = cancelButton } func selectCurrentImage() { let indexPaths = collectionView.indexPathsForVisibleItems let indexpath = indexPaths.first let cell = collectionView.cellForItem(at: indexpath!) as! LGAssetViewCell let asset = assetModels[(indexpath?.row)!] if asset.select { asset.select = false selectedInfo?.remove(cell.imageView.image!) selectButton.setImage(UIImage(named: "CellGreySelected"), for: UIControlState()) } else { asset.select = true selectedInfo?.add(cell.imageView.image!) selectButton.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState()) } } func dismissView() { self.dismiss(animated: true, completion: nil) } } // MARK: - collectionView delegate extension LGAssetViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assetModels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LGAssetViewCell // cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "imageTapGesture:")) let assetModel = assetModels[indexPath.row] let viewModel = LGAssetViewModel(assetMode: assetModel) viewModel.updateImage(cellSize) cell.viewModel = viewModel if assetModel.select { selectButton.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState()) } else { selectButton.setImage(UIImage(named: "CellGreySelected"), for: UIControlState()) } currentIndex = indexPath return cell } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let assetModel = assetModels[indexPath.row] let viewModel = LGAssetViewModel(assetMode: assetModel) let cell = cell as! LGAssetViewCell if viewModel.livePhoto.value.size.width != 0 || (viewModel.asset.value.mediaType == .video) { cell.stopPlayer() } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let assetModel = assetModels[indexPath.row] let viewModel = LGAssetViewModel(assetMode: assetModel) let cell = collectionView.cellForItem(at: indexPath) as! LGAssetViewCell if viewModel.livePhoto.value.size.width != 0 || (viewModel.asset.value.mediaType == .video) { cell.playLivePhoto() } else { if UIApplication.shared.isStatusBarHidden == false { UIApplication.shared.setStatusBarHidden(true, with: .slide) navigationController?.navigationBar.isHidden = true } else { navigationController?.navigationBar.isHidden = false UIApplication.shared.setStatusBarHidden(false, with: .slide) } } } } // MARK: - scrollView delegate extension LGAssetViewController { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = Int(collectionView.contentOffset.x / view.bounds.width + 0.5) self.title = "\(offsetX + 1)" + "/" + "\(assetModels.count)" if offsetX >= 0 && offsetX < assetModels.count && selectButton != nil { let assetModel = assetModels[offsetX] if assetModel.select { selectButton.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState()) } else { selectButton.setImage(UIImage(named: "CellGreySelected"), for: UIControlState()) } } } }
64ef8ca46b2aeba7b21d1de76ad113f9
37.322034
138
0.666814
false
false
false
false
nakau1/NerobluCore
refs/heads/master
NerobluCoreDemo/AppDelegate.swift
apache-2.0
1
// ============================================================================= // NerobluCoreDemo // Copyright (C) NeroBlu. All rights reserved. // ============================================================================= import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } }
e19667b93318ae94891a84480aca39cd
29.4375
122
0.521561
false
false
false
false
MobileToolkit/Glover
refs/heads/master
Sources/Configuration.swift
mit
2
// // Configuration.swift // Glover // // Created by Sebastian Owodzin on 12/03/2016. // Copyright © 2016 mobiletoolkit.org. All rights reserved. // import Foundation import CoreData open class Configuration { fileprivate lazy var applicationDocumentsDirectory: URL = { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! }() var model: NSManagedObjectModel var persistentStoreConfigurations: [PersistentStoreConfiguration] = [] open func addPersistentStoreConfiguration(_ persistentStoreConfiguration: PersistentStoreConfiguration) { persistentStoreConfigurations.append(persistentStoreConfiguration) } public init(model: NSManagedObjectModel) { self.model = model } open class func singleSQLiteStoreConfiguration(_ model: NSManagedObjectModel) -> Configuration { let configuration = Configuration(model: model) let storeURL = configuration.applicationDocumentsDirectory.appendingPathComponent("gloverDB.sqlite") let storeConfig = PersistentStoreConfiguration(type: .SQLite, url: storeURL) configuration.addPersistentStoreConfiguration(storeConfig) return configuration } open class func singleBinaryStoreConfiguration(_ model: NSManagedObjectModel) -> Configuration { let configuration = Configuration(model: model) let storeURL = configuration.applicationDocumentsDirectory.appendingPathComponent("gloverDB.bin") let storeConfig = PersistentStoreConfiguration(type: .Binary, url: storeURL) configuration.addPersistentStoreConfiguration(storeConfig) return configuration } open class func singleInMemoryStoreConfiguration(_ model: NSManagedObjectModel) -> Configuration { let configuration = Configuration(model: model) configuration.addPersistentStoreConfiguration(PersistentStoreConfiguration(type: .InMemory)) return configuration } }
d24a0eab48778793e380574c6784fb82
33.086207
109
0.750632
false
true
false
false
LYM-mg/MGOFO
refs/heads/master
MGOFO/MGOFO/AppDelegate.swift
mit
1
// // AppDelegate.swift // MGOFO // // Created by i-Techsys.com on 2017/5/9. // Copyright © 2017年 i-Techsys. All rights reserved. // 7728ab18dd2abf89a6299740e270f4c6 import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //后台任务 var backgroundTask:UIBackgroundTaskIdentifier! = nil func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setUpKeyWindow() setUpAllThird() return true } fileprivate func setUpKeyWindow() { self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.backgroundColor = UIColor.white let homeVc = HomeViewController() let sideVc = SideViewController() let homeNav = BaseNavigationController(rootViewController: homeVc) let revealController = SWRevealViewController(rearViewController: sideVc, frontViewController: homeNav) revealController?.delegate = self self.window?.rootViewController = revealController self.window?.makeKeyAndVisible() } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { //如果已存在后台任务,先将其设为完成 /* if self.backgroundTask != nil { application.endBackgroundTask(self.backgroundTask) self.backgroundTask = UIBackgroundTaskInvalid } */ //如果要后台运行 //注册后台任务 self.backgroundTask = application.beginBackgroundTask(expirationHandler: { () -> Void in //如果没有调用endBackgroundTask,时间耗尽时应用程序将被终止 application.endBackgroundTask(self.backgroundTask) self.backgroundTask = UIBackgroundTaskInvalid }) } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } extension AppDelegate: SWRevealViewControllerDelegate { @nonobjc func revealController(_ revealController: SWRevealViewController, animationControllerFor operation: SWRevealControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> Any? { if operation != SWRevealControllerOperationReplaceRightController { return nil } return nil } } extension AppDelegate { fileprivate func setUpAllThird() { // 注册高德地图以及设置支持https AMapServices.shared().enableHTTPS = true AMapServices.shared().apiKey = "7728ab18dd2abf89a6299740e270f4c6" } }
841e0a8572d3f7581ad11b354021bd26
38
285
0.702834
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/SelfProfile/TeamAccountView.swift
gpl-3.0
1
// Wire // Copyright (C) 2019 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 UIKit import WireDataModel final class TeamAccountView: AccountView { override var collapsed: Bool { didSet { self.imageView.isHidden = collapsed } } private let imageView: TeamImageView private var teamObserver: NSObjectProtocol! private var conversationListObserver: NSObjectProtocol! override init?(account: Account, user: ZMUser? = nil, displayContext: DisplayContext) { if let content = user?.team?.teamImageViewContent ?? account.teamImageViewContent { imageView = TeamImageView(content: content, style: .big) } else { return nil } super.init(account: account, user: user, displayContext: displayContext) isAccessibilityElement = true accessibilityTraits = .button shouldGroupAccessibilityChildren = true imageView.contentMode = .scaleAspectFill imageViewContainer.addSubview(imageView) selectionView.pathGenerator = { size in let radius = 6 let radii = CGSize(width: radius, height: radius) let path = UIBezierPath(roundedRect: CGRect(origin: .zero, size: size), byRoundingCorners: UIRectCorner.allCorners, cornerRadii: radii) return path } createConstraints() update() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap(_:))) addGestureRecognizer(tapGesture) if let team = user?.team { teamObserver = TeamChangeInfo.add(observer: self, for: team) team.requestImage() } } private func createConstraints() { let inset: CGFloat = CGFloat.TeamAccountView.imageInset [imageView, imageViewContainer].prepareForLayout() NSLayoutConstraint.activate([ imageView.leadingAnchor.constraint(equalTo: imageViewContainer.leadingAnchor, constant: inset), imageView.topAnchor.constraint(equalTo: imageViewContainer.topAnchor, constant: inset), imageView.trailingAnchor.constraint(equalTo: imageViewContainer.trailingAnchor, constant: -inset), imageView.bottomAnchor.constraint(equalTo: imageViewContainer.bottomAnchor, constant: -inset) ]) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func update() { super.update() accessibilityValue = String(format: "conversation_list.header.self_team.accessibility_value".localized, self.account.teamName ?? "") + " " + accessibilityState accessibilityIdentifier = "\(self.account.teamName ?? "") team" } func createDotConstraints() -> [NSLayoutConstraint] { let dotSize: CGFloat = 9 let dotInset: CGFloat = 2 [dotView, imageViewContainer].prepareForLayout() return [ dotView.centerXAnchor.constraint(equalTo: imageViewContainer.trailingAnchor, constant: -dotInset), dotView.centerYAnchor.constraint(equalTo: imageViewContainer.topAnchor, constant: dotInset), dotView.widthAnchor.constraint(equalTo: dotView.heightAnchor), dotView.widthAnchor.constraint(equalToConstant: dotSize) ] } } extension TeamAccountView: TeamObserver { func teamDidChange(_ changeInfo: TeamChangeInfo) { if changeInfo.imageDataChanged { changeInfo.team.requestImage() } guard let content = changeInfo.team.teamImageViewContent else { return } imageView.content = content } }
ade5642882cae9278fbc317d9518074b
35.727273
167
0.660666
false
false
false
false
hyperconnect/SQLite.swift
refs/heads/master
Carthage/Checkouts/SQLite.swift/Sources/SQLite/Extensions/Cipher.swift
mit
2
#if SQLITE_SWIFT_SQLCIPHER import SQLCipher /// Extension methods for [SQLCipher](https://www.zetetic.net/sqlcipher/). /// @see [sqlcipher api](https://www.zetetic.net/sqlcipher/sqlcipher-api/) extension Connection { /// - Returns: the SQLCipher version public var cipherVersion: String? { return (try? scalar("PRAGMA cipher_version")) as? String } /// Specify the key for an encrypted database. This routine should be /// called right after sqlite3_open(). /// /// @param key The key to use.The key itself can be a passphrase, which is converted to a key /// using [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) key derivation. The result /// is used as the encryption key for the database. /// /// Alternatively, it is possible to specify an exact byte sequence using a blob literal. /// With this method, it is the calling application's responsibility to ensure that the data /// provided is a 64 character hex string, which will be converted directly to 32 bytes (256 bits) /// of key data. /// e.g. x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99' /// @param db name of the database, defaults to 'main' public func key(_ key: String, db: String = "main") throws { try _key_v2(db: db, keyPointer: key, keySize: key.utf8.count) } public func key(_ key: Blob, db: String = "main") throws { try _key_v2(db: db, keyPointer: key.bytes, keySize: key.bytes.count) } /// Change the key on an open database. If the current database is not encrypted, this routine /// will encrypt it. /// To change the key on an existing encrypted database, it must first be unlocked with the /// current encryption key. Once the database is readable and writeable, rekey can be used /// to re-encrypt every page in the database with a new key. public func rekey(_ key: String, db: String = "main") throws { try _rekey_v2(db: db, keyPointer: key, keySize: key.utf8.count) } public func rekey(_ key: Blob, db: String = "main") throws { try _rekey_v2(db: db, keyPointer: key.bytes, keySize: key.bytes.count) } // MARK: - private private func _key_v2(db: String, keyPointer: UnsafePointer<UInt8>, keySize: Int) throws { try check(sqlite3_key_v2(handle, db, keyPointer, Int32(keySize))) try cipher_key_check() } private func _rekey_v2(db: String, keyPointer: UnsafePointer<UInt8>, keySize: Int) throws { try check(sqlite3_rekey_v2(handle, db, keyPointer, Int32(keySize))) } // When opening an existing database, sqlite3_key_v2 will not immediately throw an error if // the key provided is incorrect. To test that the database can be successfully opened with the // provided key, it is necessary to perform some operation on the database (i.e. read from it). private func cipher_key_check() throws { let _ = try scalar("SELECT count(*) FROM sqlite_master;") } } #endif
9719fc73b40a6da4f8c7ecc13d7bff85
45.651515
113
0.659305
false
false
false
false
itsbriany/Weather
refs/heads/master
Weather/Weather/WeatherEntryModel.swift
apache-2.0
1
// // WeatherEntryModel.swift // Weather // // Created by Brian Yip on 2016-02-11. // Copyright © 2016 Brian Yip. All rights reserved. // import Foundation public class WeatherEntryModel: NSCopying { // MARK: Properties var summary: String? var title: String? // MARK: Constructors init(weatherEntryModel: WeatherEntryModel) { self.summary = weatherEntryModel.summary self.title = weatherEntryModel.title } init(summary: String, title: String) { self.summary = summary self.title = title } init() { self.summary = "" self.title = "" } // MARK: NSCopying implementation @objc public func copyWithZone(zone: NSZone) -> AnyObject { return WeatherEntryModel(weatherEntryModel: self) } // MARK: Interface func reset() { self.summary?.removeAll() self.title?.removeAll() } func copy() -> WeatherEntryModel { return copyWithZone(nil) as! WeatherEntryModel } }
45f7fb1cef26059e8730bf716cf427ee
19.901961
63
0.597183
false
false
false
false
CartoDB/mobile-ios-samples
refs/heads/master
AdvancedMap.Swift/Feature Demo/RotationListener.swift
bsd-2-clause
1
// // MapClickListener.swift // AdvancedMap.Swift // // Created by Aare Undo on 24/07/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit import CartoMobileSDK class RotationListener: NTMapEventListener { var delegate: RotationDelegate? var map: NTMapView! var previousAngle: CGFloat? var previousZoom: CGFloat? override func onMapMoved() { let angle = CGFloat(map.getRotation()) let zoom = CGFloat(map.getZoom()) if (previousAngle != angle) { delegate?.rotated(angle: angle) previousAngle = angle } else if (previousZoom != zoom) { delegate?.zoomed(zoom: zoom) previousZoom = zoom } } } protocol RotationDelegate { func rotated(angle: CGFloat) func zoomed(zoom: CGFloat) }
38ea826361f47edf77d62d5e087abb5c
20.463415
48
0.611364
false
false
false
false
JQJoe/RxDemo
refs/heads/develop
Carthage/Checkouts/RxSwift/RxExample/RxExample/Example.swift
apache-2.0
8
// // Example.swift // RxExample // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if os(iOS) import UIKit typealias Image = UIImage #elseif os(macOS) import Cocoa import AppKit typealias Image = NSImage #endif let MB = 1024 * 1024 func exampleError(_ error: String, location: String = "\(#file):\(#line)") -> NSError { return NSError(domain: "ExampleError", code: -1, userInfo: [NSLocalizedDescriptionKey: "\(location): \(error)"]) } extension String { func toFloat() -> Float? { let numberFormatter = NumberFormatter() return numberFormatter.number(from: self)?.floatValue } func toDouble() -> Double? { let numberFormatter = NumberFormatter() return numberFormatter.number(from: self)?.doubleValue } } func showAlert(_ message: String) { #if os(iOS) UIAlertView(title: "RxExample", message: message, delegate: nil, cancelButtonTitle: "OK").show() #elseif os(macOS) let alert = NSAlert() alert.messageText = message alert.runModal() #endif }
3ed8f9716fe80194e28233f9a0a69c47
24
116
0.646957
false
false
false
false
practicalswift/Pythonic.swift
refs/heads/master
src/Pythonic-test.swift
mit
1
#!/usr/bin/env swift -I . import Pythonic // ** (power operator) assert(1 + 2**2 + 2 == 7) assert(1 + 2.0**2.0 + 2 == 7) assert(1**1 + 2.0**2.0 + 2 == 7) assert(2 * 2 ** 2 * 3 ** 2 * 3 ** 3 == 1944) assert(2**2 == 4) assert(2.0**2.0 == 4) // abs assert(abs(-0.1) == 0.1) assert(abs(-1) == 1) // all assert(!all(["", "bar", "baz"])) assert(!all([false, false, false])) assert(!all([false, false, true])) assert(all(["foo", "bar", "baz"])) assert(all([0.0001, 0.0001])) assert(all([true, true, true])) // any assert(!any([0, 0])) assert(!any([false, false, false])) assert(any(["", "foo", "bar", "baz"])) assert(any([0.1, 0])) assert(any([false, false, true])) // bin assert(bin(2) == "0b10") assert(bin(7) == "0b111") assert(bin(1024) == "0b10000000000") // bool assert(!bool("")) assert(!bool(0)) assert(bool("foo")) assert(bool(1)) assert(bool([1])) // assert(!bool(set([]))) // error: could not find an overload for 'assert' that accepts the supplied arguments // chr assert(chr(97) == "a") assert(chr(ord("b")) == "b") assert(ord(chr(255)) == 255) // cmp assert(cmp("bar", "bar") == 0) assert(cmp("bar", "foo") == -1) assert(cmp("foo", "bar") == 1) assert(cmp(0, 0) == 0) assert(cmp(0, 1) == -1) assert(cmp(1, 0) == 1) assert(cmp([1, 2, 3, 100], [1, 2, 3, 100]) == 0) assert(cmp([1, 2, 3, 100], [1, 2, 3, 1]) == 1) assert(cmp([1, 2, 3, 100], [2, 3, 4, 5]) == -1) assert(cmp([8, 1, 9, 2], [100, 3, 7, 8]) == -1) assert(cmp([8, 1, 9, 2], [3, 7, 8, 1]) == 1) assert(cmp([8, 1, 9, 2], [7, 8, 1, 10000]) == 1) assert(cmp([8, 1, 9, 2], [8, 1, 100, 100]) == -1) assert(cmp([8, 1, 9, 2], [1, 100, 100, 100]) == 1) assert(cmp([8, 1, 9, 2], [100, 100, 100, 100]) == -1) assert(cmp([1, 9, 2, 100], [100, 100, 100, 100]) == -1) assert(cmp([9, 2, 100, 100], [100, 100, 100, 100]) == -1) assert(cmp([2, 100, 100, 100], [100, 100, 100, 100]) == -1) assert(cmp([100, 100, 100, 100], [100, 100, 100, 100]) == 0) assert(cmp([0, 0], [0, 0]) == 0) assert(cmp([0, 0], [0, 1]) == -1) assert(cmp([0, 0], [1, 0]) == -1) assert(cmp([0, 0], [1, 1]) == -1) assert(cmp([0, 1], [0, 0]) == 1) assert(cmp([0, 1], [0, 1]) == 0) assert(cmp([0, 1], [1, 0]) == -1) assert(cmp([0, 1], [1, 1]) == -1) assert(cmp([1, 0], [0, 0]) == 1) assert(cmp([1, 0], [0, 1]) == 1) assert(cmp([1, 0], [1, 0]) == 0) assert(cmp([1, 0], [1, 1]) == -1) assert(cmp([1, 1], [0, 0]) == 1) assert(cmp([1, 1], [0, 1]) == 1) assert(cmp([1, 1], [1, 0]) == 1) assert(cmp([1, 1], [1, 1]) == 0) assert(cmp([1, 1, 1], [0, 0]) == 1) assert(cmp([1, 1, 0], [0, 0]) == 1) assert(cmp([1, 1], [0, 0, 0]) == 1) assert(cmp([1, 1], [0, 0, 1]) == 1) assert(cmp([0, 1, 1, 1], [0, 0]) == 1) assert(cmp([1, 1, 1, 0], [0, 0]) == 1) assert(cmp([1, 1], [1, 0, 0, 0]) == 1) assert(cmp([1, 1], [0, 1, 0, 1]) == 1) assert(cmp([1, 1, 1], [0, 0, 0]) == 1) assert(cmp([1, 1, 0], [0, 1, 0]) == 1) assert(cmp([1, 1], [0, 1, 0, 0]) == 1) assert(cmp([1, 1, 0], [0, 0, 1]) == 1) assert(cmp([1, 1, 1], [0, 1, 0]) == 1) assert(cmp([1, 1, 0], [0, 0, 0]) == 1) assert(cmp([1, 1], [0, 0, 1, 0]) == 1) assert(cmp([1, 1], [1, 0, 0, 1]) == 1) assert(cmp([0, 1, 1, 1], [0, -1, 0]) == 1) assert(cmp([1, 1, -1, 1, 0], [0, 0]) == 1) assert(cmp([1, 1, -1], [1, 0, 0, 0]) == 1) assert(cmp([1, 1], [0, -1, 1, 0, 1]) == 1) assert(cmp([1, 1, 1], [0, -1, 0, 0]) == 1) assert(cmp([1, 1, 0], [0, 1, -1, 0]) == 1) assert(cmp([1, 1], [0, 1, 0, 0, -1]) == 1) assert(cmp([1, 1, 0], [0, -1, 0, 1]) == 1) assert(cmp([1, 1, 1], [-1, 0, 1, 0]) == 1) assert(cmp([1, 1, 0, -1], [0, 0, 0]) == 1) assert(cmp([1, -1, 1], [0, 0, 1, 0]) == 1) assert(cmp([-1, 1, 1], [1, 0, 0, 1]) == -1) assert(cmp([-1, -1, 1], [1, 0, 0, 1]) == -1) assert(cmp([-1, -1, -1], [1, 0, 0, 1]) == -1) assert(cmp([-1, -1, -1], [0, 0, 0, 1]) == -1) assert(cmp([-1, -1, -1], [0, 0, 0, 0]) == -1) // double (truthness) assert(bool(0.00000001)) assert(bool(1.0)) assert(!bool(0.0)) // double.is_integer/isInteger assert(!0.000000000001.is_integer()) assert(!1.1.is_integer()) assert(1.0.is_integer()) // file // TODO: Missing test. // float assert(!bool(float(0.0))) assert(bool(float(0 + 0.0001))) assert(bool(float(0.00000001))) assert(bool(float(1.0))) // float.is_integer assert(!float(1.1).is_integer()) assert(float(1.0).is_integer()) assert(float(100).is_integer()) // hex assert(hex(0) == "0x0") assert(hex(1) == "0x1") assert(hex(10) == "0xa") assert(hex(100) == "0x64") assert(hex(1000) == "0x3e8") assert(hex(10000000) == "0x989680") // int assert(int(1.1) == 1) assert(int(9.9) == 9) // int (truthness) assert(bool(1)) assert(!bool(0)) // json assert(json.dumps([1, 2, 3]).replace("\n", "").replace(" ", "") == "[1,2,3]") // len assert(len("") == 0) assert(len("\t") == 1) assert(len("foo") == 3) assert(len(["foo", "bar", "baz"]) == 3) assert(len(["foo", "bar"]) == 2) assert(len(["foo"]) == 1) // list assert(list([1, 2, 3]) == [1, 2, 3]) assert(list([1, 2, 3]).count(1) == 1) // list (truthness) assert(bool([1, 2, 3])) assert(bool([1, 2])) assert(bool([1])) // list(set) assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(0) == 0) assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(1) == 1) assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(2) == 1) assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(3) == 1) assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(4) == 1) assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(5) == 0) // list.count assert([1, 2, 2, 3, 3, 3].count(1) == 1) assert([1, 2, 2, 3, 3, 3].count(2) == 2) assert([1, 2, 2, 3, 3, 3].count(3) == 3) assert([1, 2, 3].count(4) == 0) // list.index assert(["foo", "bar", "baz"].index("baz") == 2) assert([1, 2, 3].index(3) == 2) assert(list(["a", "b", "c"]).index("b") == 1) // literals assert(0b0 == 0) assert(0b111111111111111111111111111111111111111111111111111111111111111 == 9223372036854775807) assert(0o00 == 0) assert(0o10 == 8) assert(0o11 == 9) assert(0x00 == 0) assert(0xff == 255) assert(1.25e-2 == 0.0125) assert(1.25e2 == 125) // long assert(long(1.1) == 1) // math.acos assert(math.acos(-1) == math.pi) // math.asin assert(math.asin(1) == math.pi / 2) // math.atan assert(math.atan(1) == math.pi / 4) // math.cos assert(math.cos(math.pi) == -1) // math.degrees assert(math.degrees(math.pi) == 180) // math.factorial assert(math.factorial(0) == 1) assert(math.factorial(20) == 2432902008176640000) // math.pow assert(math.pow(2, 2) == 4) assert(math.pow(2.0, 2.0) == 4.0) // math.radians assert(math.radians(270) == math.pi * 1.5) // math.sin assert(math.sin(math.pi / 2) == 1) // math.sqrt assert(math.sqrt(9) == 3) // math.tan // Python returns 0.999... for tan(π / 4) assert(math.tan(math.pi / 4) <= 1) assert(math.tan(math.pi / 4) > 0.9999999) // max assert(max(1, 2) == 2) assert(max(1, 2, 3) == 3) assert(max([1, 2, 3]) == 3) assert(max([1, 2]) == 2) // min assert(min(1, 2) == 1) assert(min(1, 2, 3) == 1) assert(min([1, 2, 3]) == 1) assert(min([1, 2]) == 1) // object assert(bool(object())) // oct assert(oct(0) == "0") assert(oct(1) == "01") assert(oct(10) == "012") assert(oct(100) == "0144") assert(oct(1000) == "01750") // assert(oct(100000000000) == "01351035564000") // open assert(open("Pythonic-test.txt").read().splitlines()[2] == "This test file is being read") // ord assert(ord("a") == 97) assert(ord(chr(98)) == 98) // os.getcwd() assert(bool(os.getcwd())) // os.path.exists assert(!os.path.exists("/tmp.foo/")) assert(os.path.exists("/tmp/")) assert(os.path.exists("Pythonic-test.txt")) // os.path.join assert(os.path.join("a", "b", "c") == "a/b/c") assert(os.path.join("/a", "b", "c") == "/a/b/c") // os.system (+ os.unlink + os.path.exists) os.unlink("/tmp/pythonic-test.txt") assert(os.system("/usr/bin/touch /tmp/pythonic-test.txt") == 0) assert(os.path.exists("/tmp/pythonic-test.txt")) os.unlink("/tmp/pythonic-test.txt") // pow assert(pow(2.0, 2.0) == 4.0) // random.random assert(random.random() < 1) // random.randint assert(random.randint(0, 10) <= 10) // random.randrange assert(random.randrange(0, 10) <= 9) // range assert(range(0) == []) assert(range(0, 10, 2) == [0, 2, 4, 6, 8]) assert(range(0, 5, -1) == []) assert(range(0, 50, 7) == [0, 7, 14, 21, 28, 35, 42, 49]) assert(range(1, 0) == []) assert(range(1, 11) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) assert(range(10) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) // re.search assert(!re.search("^bar", "foobarbaz")) assert(!re.search("hello", "foobarbaz")) assert(re.search("[\r\n]", "foo\rfoo").group(0) == "\r") assert(re.search("\r\n", "foo\r\nfoo").group(0) == "\r\n") assert(bool(re.search("^foo", "foobarbaz"))) assert(re.search("^foo", "foobarbaz").group(0) == "foo") assert(bool(re.search("^foo.*baz$", "foobarbaz"))) assert(bool(re.search("foo", "foobarbaz"))) assert(bool(re.search("o", "foobarbaz"))) // re.match assert(!re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[2]) assert(!re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[4]) assert(!re.match("o", "foobarbaz")) assert(!re.search("zoo", "barfoobar")) assert(len(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()) == 2) assert(len(re.search("foo", "barfoobar").groups()) == 0) assert(list(re.match("(.*) down (.*) on (.*)", "Bugger all down here on earth!").groups()) == ["Bugger all", "here", "earth!"]) assert(list(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").groups()) == ["Hello foo bar baz", "foo", "bar", "baz"]) assert(list(re.match("Hello[ \t]*(.*)world", "Hello Python world").groups())[0] == "Python ") assert(list(re.search("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()) == ["var", "tmp", "foo"]) assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(0) == "Hello foo bar baz") assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(1) == "Hello foo bar baz") assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(2) == "foo") assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(3) == "bar") assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(4) == "baz") assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[0] == "var") assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[1] == "tmp") assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[2] == "foo") assert(re.match("Hello[ \t]*(.*)world", "Hello Python world").group(0) == "Hello Python world") assert(re.match("Hello[ \t]*(.*)world", "Hello Python world").group(1) == "Python ") assert(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()[0] == "baz") assert(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()[1] == "baz") assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[0] == "foobarbazfoobarba") assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[1] == "z") assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[3] == "z") assert(bool(re.match("^foo", "foobarbaz"))) assert(bool(re.match("foo", "foobarbaz"))) assert(bool(re.search("foo", "barfoobar"))) // re.split assert(re.split("/", "") == [""]) assert(re.split("/", "/") == ["", ""]) assert(re.split("/", "foo/") == ["foo", ""]) assert(re.split("/", "foo/bar") == ["foo", "bar"]) assert(re.split("/", "foo/bar/") == ["foo", "bar", ""]) assert(re.split("/", "foo/bar/baz") == ["foo", "bar", "baz"]) assert(re.split("/", "foo/bar/baz/") == ["foo", "bar", "baz", ""]) assert(re.split("[0-9]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e", "f", "z", "", "", "ee", "", "ch", "", "", "h", "", "fhh", "h", "ui", "", "", "sh", ""]) assert(re.split("[0-9]", "foo/bar/baz") == ["foo/bar/baz"]) assert(re.split("[0-9]", "foo/bar/baz/") == ["foo/bar/baz/"]) assert(re.split("[XY]+", "aXYbXYc") == ["a", "b", "c"]) assert(re.split("[\r\n]", "\r\n\t\t\r\n\r\t\n\r\r\n\n\t\t") == ["", "", "\t\t", "", "", "\t", "", "", "", "", "\t\t"]) assert(re.split("[\r\n]+", "foo\naw\tef\roa\r\nwef") == ["foo", "aw\tef", "oa", "wef"]) assert(re.split("[^a-z]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e", "f", "z", "", "", "ee", "", "ch", "", "", "h", "", "fhh", "h", "ui", "", "", "sh", ""]) assert(re.split("[a-z]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["", "8", "8", "888", "", "88", "", "838", "23", "", "", "3", "2", "", "388", "", "3"]) assert(re.split("a-z", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e8f8z888ee88ch838h23fhh3h2ui388sh3"]) assert(re.split("[^a-zA-Z0-9]", "foo bar baz") == ["foo", "bar", "baz"]) assert(re.split("\\s(?=\\w+:)", "foo:bar baz:foobar") == ["foo:bar", "baz:foobar"]) assert(re.split("[^a-z]", "foo1bar2baz3foo11bar22baz33foo111bar222baz333") == ["foo", "bar", "baz", "foo", "", "bar", "", "baz", "", "foo", "", "", "bar", "", "", "baz", "", "", ""]) assert(re.split("[^a-z]+", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo") == ["foo", "foobar", "baz", "foobarbaz", "bazbarfoo"]) assert(re.split("[^a-z]+", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["foo", "foobar", "baz", "foobarbaz", "bazbarfoo", ""]) assert(re.split("[^a-z]+", "12345foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["", "foo", "foobar", "baz", "foobarbaz", "bazbarfoo", ""]) assert(re.split("([^a-z]+)", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo") == ["foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo"]) assert(re.split("([^a-z]+)", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo", "12345", ""]) assert(re.split("([^a-z]+)", "12345foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["", "12345", "foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo", "12345", ""]) assert(re.split("([^a-zA-Z0-9])", "foo bar baz") == ["foo", " ", "bar", " ", "baz"]) assert(re.split("(abc)", "abcfooabcfooabcfoo") == ["", "abc", "foo", "abc", "foo", "abc", "foo"]) assert(re.split("abc", "abcfooabcfooabcfoo") == ["", "foo", "foo", "foo"]) // assert(re.split("(a)b(c)", "abcfooabcfooabcfoo") == ["", "a", "c", "foo", "a", "c", "foo", "a", "c", "foo"]) // Failing edge case which is not Python compatible yet. // re.sub assert(re.sub("^foo", "bar", "foofoo") == "barfoo") assert(re.sub("^zfoo", "bar", "foofoo") == "foofoo") assert(re.sub("([^a-zA-Z0-9])foo([^a-zA-Z0-9])", "\\1bar\\2", "foobarfoobar foo bar foo bar") == "foobarfoobar bar bar bar bar") // round assert(round(1.1) == 1) // set assert(!(set([1, 2, 3]) < set([1, 2, 3]))) assert(!(set([4]) < set([1, 2, 3]))) assert(set([1, 1, 1, 2, 2, 3, 3, 4]) == set([1, 2, 3, 4])) assert(set([1, 2, 3]) & set([3, 4, 5]) == set([3])) assert(set([1, 2, 3]) - set([3, 4, 5]) == set([1, 2])) assert(set([1, 2, 3]) | set([3, 4, 5]) == set([1, 2, 3, 4, 5])) assert(bool(set([1, 2, 3]))) assert(set([1, 2]) < set([1, 2, 3])) assert(bool(set([1, 2]))) assert(set([1]) < set([1, 2, 3])) assert(bool(set([1]))) // set + split assert(set("foo bar".split(" ")) == set(["foo", "bar"])) // set.isdisjoint assert(!set([1, 2, 3]).isdisjoint(set([3, 4, 5]))) assert(set([1, 2, 3]).isdisjoint(set([4, 8, 16]))) // str (conversion) assert(str(123) == "123") assert(str(1.23) == "1.23") // str (indexing) assert("foobar"[0] == "f") assert("\r\t"[0] == "\r") assert("\r\t"[1] == "\t") // str (truthness) assert(bool(" ")) assert(!bool("")) // str (positive and negative indexing) assert("foo"[-1] == "o") assert("foo"[-2] == "o") assert("foo"[0] == "f") assert("foo"[len("foo")-1] == "o") // str * int (repeat string) assert("foo" * 3 == "foofoofoo") assert("foo" * 3 == "foofoofoo") assert(-1 * "foo" == "") assert(0 * "foo" == "") assert(1 * "foo" == "foo") assert(2 * "foo" * 2 == "foofoofoofoo") assert(2 * "foo" == "foofoo") // str % tuple assert("Hello %d! Number %s" % (1, "world") == "Hello 1! Number world") assert("Hello %d!" % (1) == "Hello 1!") assert("Hello %s! Number %d" % ("world", 1) == "Hello world! Number 1") assert("Hello %s!" % ("world") == "Hello world!") assert("With commit %d, this string building syntax is now %s!" % (197, "supported") == "With commit 197, this string building syntax is now supported!") assert("foo %% bar %011d baz %s" % (100, "foobar") == "foo % bar 00000000100 baz foobar") assert("foo %d" % (123) == "foo 123") // str.capitalize assert("".capitalize() == "") assert("f".capitalize() == "F") assert("fo".capitalize() == "Fo") assert("foo baR".capitalize() == "Foo bar") assert("foo".capitalize() == "Foo") // str.center assert("foo".center(5) == " foo ") assert("foo".center(6, "-") == "-foo--") assert("foobar".center(9, "-") == "--foobar-") assert("foobar".center(4) == "foobar") // str.count assert("foo".count("f") == 1) assert("foo".count("o") == 2) assert("foo".count("b") == 0) // str.endswith assert("foobar".endswith("bar")) // str.expandtabs assert(len("\t".expandtabs()) == 8) assert(len("\t".expandtabs(10)) == 10) assert(len("\t\t".expandtabs(10)) == 20) assert(len(("\t" * 2).expandtabs()) == 16) assert("\t".expandtabs() == " " * 8) // str.find assert("foo".find("foobarfoobar") == -1) assert("foobar".find("") == 0) assert("foobar".find("bar") == 3) assert("foobar".find("f") == 0) assert("foobar".find("foobar") == 0) assert("foobar".find("foobars") == -1) assert("foobar".find("zbar") == -1) // str.in (translated to "str1 in str" when running as Python code) assert(!"foo".`in`("baz")) assert(!"foobar".`in`("")) assert("".`in`("foobar")) assert("foo".`in`("foobar")) assert("ob".`in`("foobar")) // str.index assert("foobar".index("foobar") == 0) assert("foobar".index("") == 0) assert("foobar".index("f") == 0) assert("foobar".index("bar") == 3) // str.isalnum assert(!"foo ".isalnum()) assert("foo1".isalnum()) // str.isalpha assert(!"foo1".isalpha()) assert("fooo".isalpha()) // str.isdigit assert(!"foo1".isdigit()) assert("123".isdigit()) // str.islower assert(!"FOO".islower()) assert("foo".islower()) // str.isspace assert(!" x ".isspace()) assert(!" a\t".isspace()) assert(" ".isspace()) assert(" \t".isspace()) // str.istitle assert(!"foo foo".istitle()) assert(!"foo".istitle()) assert("Foo Foo".istitle()) assert("Foo".istitle()) // str.isupper assert(!"foo".isupper()) assert("FOO".isupper()) // str.join assert(":".join(["foo", "bar", "baz"]) == "foo:bar:baz") // str.ljust assert("foo".ljust(5) == "foo ") assert("foo".ljust(10, "-") == "foo-------") assert("foobar".ljust(4) == "foobar") // str.lower assert("FooBar".lower() == "foobar") // str.lstrip assert(" \n\t foobar \n\t ".lstrip() == "foobar \n\t ") // str.partition assert("the first part\nthe second part".partition("\n") == ("the first part", "\n", "the second part")) assert("the first part".partition("\n") == ("the first part", "", "")) assert("the first part\n".partition("\n") == ("the first part", "\n", "")) assert("\nthe second part".partition("\n") == ("", "\n", "the second part")) // str.replace assert("fzzbar".replace("z", "o") == "foobar") // str.rfind // assert("Foo Bar Baz Baz Qux".rfind("fubar") == -1) - Python raises ValueError assert("Foo Bar Baz Baz Qux".rfind("Bar") == 4) assert("Foo Bar Baz Baz Qux".rfind("Baz") == 12) // assert("Foo Bar Baz Baz Qux".rfind("y") == -1) - Python raises ValueError assert("Foo Bar Baz Baz Qux".rfind("Q") == 16) assert("Foo Bar Baz Baz Qux".rfind("z") == 14) // str.rindex // assert("Foo Bar Baz Baz Qux".rindex("fubar") == -1) - Python raises ValueError assert("Foo Bar Baz Baz Qux".rindex("Bar") == 4) assert("Foo Bar Baz Baz Qux".rindex("Baz") == 12) // assert("Foo Bar Baz Baz Qux".rindex("y") == -1) - Python raises ValueError assert("Foo Bar Baz Baz Qux".rindex("Q") == 16) assert("Foo Bar Baz Baz Qux".rindex("z") == 14) // str.rjust assert("foo".rjust(5) == " foo") assert("foo".rjust(10, "-") == "-------foo") assert("foobar".rjust(4) == "foobar") // str.rpartition assert("Foo Bar Baz Baz Qux".rpartition("fubar") == ("", "", "Foo Bar Baz Baz Qux")) assert("Foo Bar Baz Baz Qux".rpartition("Bar") == ("Foo ", "Bar", " Baz Baz Qux")) assert("Foo Bar Baz Baz Qux".rpartition("Baz") == ("Foo Bar Baz ", "Baz", " Qux")) assert("Foo Bar Baz Baz Qux".rpartition("y") == ("", "", "Foo Bar Baz Baz Qux")) assert("Foo Bar Baz Baz Qux".rpartition("Q") == ("Foo Bar Baz Baz ", "Q", "ux")) assert("Foo Bar Baz Baz Qux".rpartition("z") == ("Foo Bar Baz Ba", "z", " Qux")) // str.rstrip assert(" \n\t foobar \n\t ".rstrip() == " \n\t foobar") // str.split assert("a\t\n\r\t\n\t\n\r\nb\r\nc\t".split() == ["a", "b", "c"]) assert("foo bar".split(" ") == ["foo", "bar"]) assert("foo:bar:baz".split(":") == ["foo", "bar", "baz"]) assert("foo\r\n \r\nbar\rfoo\nfoo\n\nfoo\n\n\nfoo".split() == ["foo", "bar", "foo", "foo", "foo", "foo"]) assert("foo\r\nbar\rfoo\nfoo\n\nfoo\n\n\nfoo".split() == ["foo", "bar", "foo", "foo", "foo", "foo"]) assert(len(open("Pythonic-test.txt").read().split()) == 23) // str.splitlines assert("foo\naw\tef\roa\r\nwef".splitlines() == ["foo", "aw\tef", "oa", "wef"]) assert("foo\rfoo\nfoo\r\nfoo\n\rfoo\nfoo".splitlines() == ["foo", "foo", "foo", "foo", "", "foo", "foo"]) assert("\nfoo\rfoo\nfoo\r\nfoo\n\rfoo\nfoo\n".splitlines() == ["", "foo", "foo", "foo", "foo", "", "foo", "foo"]) // str.startswith assert("foobar".startswith("foo")) // str.strip assert(" \n foobar \n ".strip() == "foobar") assert(" foobar ".strip() == "foobar") assert("".strip() == "") assert("foobar".strip() == "foobar") assert(" \n\t foobar \n\t ".strip() == "foobar") // str.swapcase assert("foo".swapcase() == "FOO") assert("FooBar".swapcase() == "fOObAR") assert("›ƒé".swapcase() == "›ƒé") // str.title assert("foo bar".title() == "Foo Bar") // str.upper assert("FooBar".upper() == "FOOBAR") // str.zfill assert("foo".zfill(-1) == "foo") assert("foo".zfill(0) == "foo") assert("foo".zfill(1) == "foo") assert("foo".zfill(10) == "0000000foo") assert(len("foo".zfill(1000)) == 1000) // sum assert(sum([1, 2, 3]) == 6) assert(sum([1, 2, 3], 1) == 7) assert(sum([1.1, 1.2]) == 2.3) // sys.argv if len(sys.argv) == 1 && sys.argv[0] == "./Pythonic-test.swift" { // Make sure test case passes also when run using shebang line. sys.argv = ["./Pythonic-test", "arg1", "arg2"] } assert(sys.argv[0].startswith("./Pythonic-test")) assert(sys.argv[1] == "arg1") assert(sys.argv[2] == "arg2") assert(len(sys.argv) == 3) // sys.platform assert(sys.platform == "darwin") // time.time assert(time.time() > 1405028001.224846) // datetime assert(datetime(2014, 7, 4) == datetime.strptime("07/04/14", "%m/%d/%y")) assert(datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M").strftime("%d/%m/%y %H:%M") == "21/11/06 16:30") assert(datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M").strftime("%d/%m/%y %H:%M") == "21/11/06 16:30") // tuple – comparison of 2-part tuples assert((1, 1) == (1, 1)) assert(!((1, 1) == (1, 214))) // tuple – comparison of 3-part tuples assert((1, 1, 1) == (1, 1, 1)) assert(!((1, 1, 1) == (1, 1, 214))) // uuid assert(len(uuid.uuid4().hex) == 32) // xrange assert(list(xrange(10)) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) assert(list(xrange(1, 10)) == [1, 2, 3, 4, 5, 6, 7, 8, 9]) let performPythonIncompatibleTests = true if performPythonIncompatibleTests { // dict (semantics + copy()) var dict1 = ["foo": 1] assert(dict1["foo"] != nil) assert(dict1["bar"] == nil) var dict2 = dict1 dict2["bar"] = 2 assert(dict1["foo"] != nil) assert(dict1["bar"] == nil) assert(dict2["foo"] != nil) assert(dict2["bar"] != nil) var dict3 = dict1 dict3["bar"] = 3 assert(dict1["foo"] != nil) assert(dict1["bar"] == nil) assert(dict3["foo"] != nil) assert(dict3["bar"] != nil) // dict assert(!dict<str, str>()) assert(bool(["foo": "bar"])) assert(len(dict<str, str>()) == 0) // dict.clear var dict4 = ["foo": "bar"] assert(bool(dict4)) dict4.clear() assert(!bool(dict4)) // dict.fromkeys assert(dict.fromkeys(["a", "b", "c"], 1) == ["a": 1, "c": 1, "b": 1]) // dict.items var h = ["foo": 1, "bar": 2, "baz": 3] var arrayOfTuples = h.items() // NOTE: list.sort() sorts in place in Python, but not in Swift. arrayOfTuples.sortInPlace() { $0.1 < $1.1 } assert(arrayOfTuples[0].0 == "foo" && arrayOfTuples[0].1 == 1) assert(arrayOfTuples[1].0 == "bar" && arrayOfTuples[1].1 == 2) assert(arrayOfTuples[2].0 == "baz" && arrayOfTuples[2].1 == 3) // divmod assert(divmod(100, 9).0 == 11) assert(divmod(100, 9).1 == 1) assert(divmod(101.0, 8.0).0 == 12.0) assert(divmod(101.0, 8.0).1 == 5.0) assert(divmod(102.0, 7).0 == 14.0) assert(divmod(102.0, 7).1 == 4.0) assert(divmod(103, 6.0).0 == 17.0) assert(divmod(103, 6.0).1 == 1.0) // double.isInteger let d1 = 1.0 let d2 = 1.1 assert(d1.isInteger()) assert(!d2.isInteger()) // float.isInteger assert(float(1.0).isInteger()) assert(!float(1.1).isInteger()) // hasattr class Baz { let foo = "foobar" let bar = "foobar" } let baz = Baz() assert(hasattr(baz, "foo")) assert(hasattr(baz, "baz") == false) // list assert(!list<int>()) // list.count + list.index + list.reverseInPlace var arr: [String] = ["foo", "bar", "baz", "foo"] assert(arr.count("foo") == 2) arr.remove("foo") assert(arr.count("foo") == 1) assert(arr.index("bar") == 0) arr.append("hello") assert(arr.index("hello") == 3) arr.reverseInPlace() assert(arr.index("hello") == 0) // list.index assert(["foo", "bar", "baz"].index(1) == nil) assert([1, 2, 3].index("foo") == nil) assert([1, 2, 3].index(4) == nil) // list.pop var mutableArray = [1, 2, 3] assert(mutableArray.pop() == 3) assert(mutableArray.pop(0) == 1) assert(mutableArray.pop(1) == nil) assert(mutableArray.pop(0) == 2) assert(mutableArray.pop() == nil) // list.remove var anotherMutableArray = [3, 2, 1, 3] anotherMutableArray.remove(0) assert(anotherMutableArray == [3, 2, 1, 3]) anotherMutableArray.remove(2) assert(anotherMutableArray == [3, 1, 3]) anotherMutableArray.remove(1) assert(anotherMutableArray == [3, 3]) anotherMutableArray.remove(3) assert(anotherMutableArray == [3]) anotherMutableArray.remove(3) assert(anotherMutableArray == []) // len assert(len(list<str>()) == 0) assert(len(["foo": "bar"]) == 1) assert(len(["foo": "bar", "baz": "foo"]) == 2) // map var mapObj = ["foo": "foobar"] assert(len(mapObj) == 1) assert(mapObj["foo"] != nil) // map.get assert(mapObj.get("foo") == "foobar") // map.has_key/hasKey assert(mapObj.has_key("foo")) assert(mapObj.hasKey("foo")) // map.pop assert(mapObj.pop("foo") == "foobar") assert(len(mapObj) == 0) // map.popItem mapObj["foo"] = "bar" let t = mapObj.popItem() assert(len(mapObj) == 0) // map.clear mapObj.clear() assert(len(mapObj) == 0) assert(mapObj["foobar"] == nil) // open(…) [modes: w, a, r (default)] + fh.write + fh.close + os.path.exists let temporaryTestFile = "/tmp/pythonic-io.txt" var f = open(temporaryTestFile, "w") f.write("foo") f.close() f = open(temporaryTestFile, "a") f.write("bar\n") f.close() f = open(temporaryTestFile) var foundText = false for line in f { if line == "foobar" { foundText = true } } assert(foundText) assert(os.path.exists(temporaryTestFile)) os.unlink(temporaryTestFile) assert(!os.path.exists(temporaryTestFile)) // os.popen3 var (stdin, stdout, stderr) = os.popen3("/bin/echo foo") var foundOutput = false for line in stdout { if line == "foo" { foundOutput = true } } assert(foundOutput) // os.popen2 foundOutput = false (stdin, stdout) = os.popen2("/bin/echo foo") for line in stdout { if line == "foo" { foundOutput = true } } assert(foundOutput) // random.choice let array = ["foo", "bar"] let randomChoice = random.choice(array) assert(randomChoice == "foo" || randomChoice == "bar") // re.search assert(!re.search("", "foobarbaz")) // re.search.group assert(re.search("^foo", "foobarbaz")[0] == "foo") // set var emptyIntSet: Set<Int> = set() assert(!emptyIntSet) assert(set([1, 2, 3]) + set([3, 4, 5]) == set([1, 2, 3, 4, 5])) assert(set([set([1, 2, 3]), set([1, 2, 3]), set([2, 4, 8])]) != set([set([1, 2, 3]), set([2, 4, 9])])) assert(set([set([1, 2, 3]), set([1, 2, 3]), set([2, 4, 8])]) == set([set([1, 2, 3]), set([2, 4, 8])])) assert(bool(set([1, 2, 3]))) var set1 = Set<Int>() assert(len(set1) == 0) set1 += 1 assert(len(set1) == 1) assert(set1 == Set([1])) set1.insert(2) // TODO: Should add Python style set.add(element). assert(set1 == Set([1, 2])) set1.insert(3) assert(set1 == Set([1, 2, 3])) set1.insert(1) assert(set1 == Set([1, 2, 3])) set1.insert(2) assert(set1 == Set([1, 2, 3])) set1.insert(3) assert(set1 == Set([1, 2, 3])) set1.remove(2) assert(set1 == Set([1, 3])) set1.remove(2) assert(set1 == Set([1, 3])) set1 -= 2 assert(set1 == Set([1, 3])) var set2 = Set([1, 8, 16, 32, 64, 128]) assert(set2 == Set([128, 64, 32, 16, 8, 1])) var set3 = set1 + set2 assert(set3 == Set([128, 64, 32, 16, 8, 1, 3])) var set4 = set1 - set2 assert(set4 == Set([3])) set4 += set2 assert(set4 == Set([128, 64, 32, 16, 8, 1, 3])) set4 -= set2 assert(set4 == Set([3])) var set5 = Set(set4) assert(set5 == Set([3])) assert(set5 == set4) var set6 = Set([1, 2, 3]) & Set([1, 3]) assert(set6 == Set([1, 3])) set6 &= set6 assert(set6 == Set([1, 3])) var set7 = Set([1, 2, 3]) | Set([1, 3]) assert(set7 == Set([1, 2, 3])) set7 |= set7 assert(set7 == Set([1, 2, 3])) var set8: Set<Int> = [1, 2, 3] assert(len(set8) == 3) var set9 = Set([0, 1, 2]) set9.insert(3) set9.insert(3) assert(set9 == Set([0, 1, 2, 3])) var set10 = Set([2, 4, 8, 16]) assert(set9 + set10 == Set([0, 1, 2, 3, 4, 8, 16])) assert(set9 - set10 == Set([0, 1, 3])) assert(set9 & set10 == Set([2])) assert(set([1, 2, 3]).contains(1)) assert(!set([1, 2, 3]).contains(4)) // statistics.mean assert(statistics.mean([-1.0, 2.5, 3.25, 5.75]) == 2.625) assert(statistics.mean([0.5, 0.75, 0.625, 0.375]) == 0.5625) assert(statistics.mean([1, 2, 3, 4, 4]) == 2.8) // statistics.median assert(statistics.median([1, 3, 5, 7]) == 4.0) assert(statistics.median([1, 3, 5]) == 3) assert(statistics.median([2, 3, 4, 5]) == 3.5) // statistics.median_high assert(statistics.median_high([1, 3, 5]) == 3) assert(statistics.median_high([1, 3, 5, 7]) == 5) // statistics.median_low assert(statistics.median_low([1, 3, 5]) == 3) assert(statistics.median_low([1, 3, 5, 7]) == 3) // str (handling of "\r\n" not compatible with Python) assert("\r\n\t"[0] == "\r\n") assert("\r\n\t"[1] == "\t") // str.endsWith assert("foobar".endsWith("bar")) // str.index assert("foobar".index("foobars") == -1) assert("foobar".index("zbar") == -1) // str.split assert("foobar".split("") == ["foobar"]) // str.startsWith assert("foobar".startsWith("foo")) // str.title assert("they're bill's friends from the UK".title() == "They're Bill's Friends From The Uk") // str[(Int?, Int?)] assert("Python"[(nil, 2)] == "Py") assert("Python"[(2, nil)] == "thon") assert("Python"[(2, 4)] == "th") assert("Python"[(nil, -3)] == "Pyt") assert("Python"[(-3, nil)] == "hon") // str[range] assert("foobar"[0..<3] == "foo") // time.sleep time.sleep(0.001) // datetime let day = datetime.strptime("11/08/14 21:13", "%d/%m/%y %H:%M") assert(day.strftime("%a %A %w %d %b %B %m %y %Y") == "Mon Monday 1 11 Aug August 08 14 2014") assert(day.strftime("%H %I %p %M %S %f %j %%") == "21 09 pm 13 00 000000 223 %" || day.strftime("%H %I %p %M %S %f %j %%") == "21 09 PM 13 00 000000 223 %") assert(day.strftime("It's day number %d; the month is %B.") == "It's day number 11; the month is August.") assert(day.isoformat(" ") == "2014-08-11 21:13:00") // timedelta let year = timedelta(days: 365) let anotherYear = timedelta(weeks: 40, days: 84, hours: 23, minutes: 50, seconds: 600) assert(year.total_seconds() == 31536000.0) assert(year == anotherYear) // datetime & timedelta let oneDayDelta = timedelta(days: 1) let nextDay = day + oneDayDelta let previousDay = day - oneDayDelta assert(nextDay - previousDay == oneDayDelta * 2) let otherDay = day.replace(day: 15, hour: 22) assert(otherDay - nextDay == timedelta(days: 3, seconds: 60 * 60)) // zip let zipped = zip([3, 4], [9, 16]) // let (l1, r1) = zipped[0] // assert(l1 == 3 && r1 == 9) // let (l2, r2) = zipped[1] // assert(l2 == 4 && r2 == 16) // file.__iter__ , as in "for line in open(filename)" var filehandletest = "" for line in fileHandleFromString("line 1\nline 2\n") { filehandletest += line + "\n" } assert(filehandletest == "line 1\nline 2\n") assert(["line 1", "line 2"] == Array(fileHandleFromString("line 1\nline 2\n"))) assert(["line 1"] == Array(fileHandleFromString("line 1\n"))) assert(["line 1"] == Array(fileHandleFromString("line 1"))) assert(["line 1", "", "line 3"] == Array(fileHandleFromString("line 1\n\nline 3"))) assert(["", "line 2", "line 3"] == Array(fileHandleFromString("\nline 2\nline 3"))) assert(["", "", "line 3"] == Array(fileHandleFromString("\n\nline 3"))) // Others: assert("foobar"[0..<2] == "fo") assert(bool("x" as Character)) } let performTestsRequiringNetworkConnectivity = false if performTestsRequiringNetworkConnectivity && performPythonIncompatibleTests { let getTest = requests.get("http://httpbin.org/get") print("GET:") print(getTest.text) let postDataString = "…" let postTestWithString = requests.post("http://httpbin.org/post", postDataString) print("POST(str):") print(postTestWithString.text) let postDataDict = ["…": "…", "key": "value", "number": "123"] let postTestWithDict = requests.post("http://httpbin.org/post", postDataDict) print("POST(dict):") print(postTestWithDict.text) } sys.exit()
0f9ab0ddd5060969ecf66f4668e95a3d
32.038278
217
0.555076
false
false
false
false
ciamic/VirtualTourist
refs/heads/master
VirtualTourist/VirtualTouristMapViewController.swift
mit
1
// // VirtualTouristMapViewController.swift // // Copyright (c) 2017 michelangelo // // 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 import CoreData class VirtualTouristMapViewController: UIViewController { // MARK: Outlets @IBOutlet weak var mapView: MKMapView! @IBOutlet var longPressGestureRecognizer: UILongPressGestureRecognizer! @IBOutlet weak var removePinLabel: UILabel! @IBOutlet weak var editBarButtonItem: UIBarButtonItem! // MARK: Properties fileprivate var isEditMode = false //true if we are in edit mode (i.e. can delete Pins) private lazy var fetchedResultsController: NSFetchedResultsController<Pin> = { let request = NSFetchRequest<Pin>(entityName: "Pin") request.sortDescriptors = [NSSortDescriptor(key: "latitude", ascending: true)] let fetchedResultsController = NSFetchedResultsController<Pin>(fetchRequest: request, managedObjectContext: CoreDataStack.shared.mainContext, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultsController }() private struct AlphaValues { static let Opaque: CGFloat = 1.0 static let Transparent: CGFloat = 0.0 } // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self loadAndSetCoordinatesPreferences() longPressGestureRecognizer.addTarget(self, action: #selector(longPressureGestureRecognized(_:))) mapView.addGestureRecognizer(longPressGestureRecognizer) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() loadAnnotationsFromFetchedResultsController() } catch { debugPrint(error.localizedDescription) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Actions @IBAction func editBarButtonItemTapped(_ sender: UIBarButtonItem) { isEditMode = !isEditMode UIView.animate(withDuration: 0.5) { if self.isEditMode { self.removePinLabel.alpha = AlphaValues.Opaque self.editBarButtonItem.title = "Done" } else { self.removePinLabel.alpha = AlphaValues.Transparent self.editBarButtonItem.title = "Edit" } } } // MARK: Utility @objc private func longPressureGestureRecognized(_ gestureRecognizer: UIGestureRecognizer) { if gestureRecognizer.state == .ended { let touchPoint = gestureRecognizer.location(in: mapView) let coordinates = mapView.convert(touchPoint, toCoordinateFrom: mapView) addPin(withLatitude: coordinates.latitude, withLongitude: coordinates.longitude) } } private func addPin(withLatitude latitude: Double, withLongitude longitude: Double) { let _ = Pin(latitude: latitude, longitude: longitude, inContext: CoreDataStack.shared.mainContext) //DispatchQueue.main.async { // CoreDataStack.shared.save() //} } private func loadAnnotationsFromFetchedResultsController() { mapView.removeAnnotations(mapView.annotations) if let pins = fetchedResultsController.fetchedObjects { for pin in pins { mapView.addAnnotation(pin) } } } } // MARK: MKMapViewDelegate extension VirtualTouristMapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let identifier = "Pin" var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) } else { annotationView!.annotation = annotation } annotationView!.canShowCallout = false return annotationView } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { guard let pin = view.annotation as? Pin else { return } if isEditMode { CoreDataStack.shared.mainContext.delete(pin) } else { if let collectionVC = storyboard?.instantiateViewController(withIdentifier: "collectionViewController") as? VirtualTouristCollectionViewController { collectionVC.pin = pin mapView.deselectAnnotation(pin, animated: false) navigationController?.pushViewController(collectionVC, animated: true) } } } private struct MapKeys { static let RegionHasBeenSaved = "com.VirtualTourist.RegionHasBeenSaved" static let LastRegionLatitude = "com.VirtualTourist.Latitude" static let LastRegionLongitude = "com.VirtualTourist.Longitude" static let LastRegionLongitudeDelta = "com.VirtualTourist.LongitudeDelta" static let LastRegionLatitudeDelta = "com.VirtualTourist.LatitudeDelta" } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { storeCoordinatesPreferences() } private func storeCoordinatesPreferences() { let defaults = UserDefaults.standard defaults.setValue(true, forKey: MapKeys.RegionHasBeenSaved) let region = mapView.region defaults.set(region.center.latitude, forKey: MapKeys.LastRegionLatitude) defaults.set(region.center.longitude, forKey: MapKeys.LastRegionLongitude) defaults.set(region.span.latitudeDelta, forKey: MapKeys.LastRegionLatitudeDelta) defaults.set(region.span.longitudeDelta, forKey: MapKeys.LastRegionLongitudeDelta) } fileprivate func loadAndSetCoordinatesPreferences() { let defaults = UserDefaults.standard if defaults.bool(forKey: MapKeys.RegionHasBeenSaved) { var region = MKCoordinateRegion() region.center.latitude = defaults.double(forKey: MapKeys.LastRegionLatitude) region.center.longitude = defaults.double(forKey: MapKeys.LastRegionLongitude) region.span.latitudeDelta = defaults.double(forKey: MapKeys.LastRegionLatitudeDelta) region.span.longitudeDelta = defaults.double(forKey: MapKeys.LastRegionLongitudeDelta) mapView.setRegion(region, animated: true) } } } // MARK: NSFetchedResultControllerDelegate extension VirtualTouristMapViewController: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { let pin = anObject as! Pin switch type { case .insert: mapView.addAnnotation(pin) case .delete: mapView.removeAnnotation(pin) /* This would cause the delegate to be notified even when photos relative to the pin would get updated/removed (i.e. in VirtualTouristCollectionViewController) case .move: fallthrough case .update: break */ default: return } DispatchQueue.main.async { CoreDataStack.shared.save() } } }
ac2277133eef6ac3f05dfc81c9ec71a2
38.62037
190
0.677378
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModelTests/Schedule/TheFirstTimeSyncFinishes_ApplicationShould.swift
mit
1
import EurofurenceModel import XCTest class TheFirstTimeSyncFinishes_ApplicationShould: XCTestCase { func testRestrictEventsToTheFirstConDayWhenRunningBeforeConStarts() { let response = ModelCharacteristics.randomWithoutDeletions let firstDay = unwrap(response.conferenceDays.changed.min(by: { $0.date < $1.date })) let context = EurofurenceSessionTestBuilder().with(.distantPast).build() let schedule = context.eventsService.makeEventsSchedule() let delegate = CapturingEventsScheduleDelegate() schedule.setDelegate(delegate) context.performSuccessfulSync(response: response) let expectedEvents = response.events.changed.filter({ $0.dayIdentifier == firstDay.identifier }) EventAssertion(context: context, modelCharacteristics: response) .assertEvents(delegate.events, characterisedBy: expectedEvents) } }
3fc5eac3a875726680d4efd92195510a
44.15
104
0.748616
false
true
false
false
buyiyang/iosstar
refs/heads/master
iOSStar/Scenes/User/bankCard/BindingBankCardVC.swift
gpl-3.0
3
// // BindingBankCardVC.swift // iOSStar // // Created by sum on 2017/5/15. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import SVProgressHUD class BindingBankCardVC: UITableViewController { //持卡人姓名 @IBOutlet var name: UITextField! //银行卡号 @IBOutlet var cardNum: UITextField! //手机号 @IBOutlet var phone: UITextField! //验证码 @IBOutlet var vaildCode: UITextField! //定时器 var openProvince = "" var openCityStr = "" @IBOutlet var openCity: UITextField! private var timer: Timer? //时间戳 private var codeTime = 60 //时间戳 var timeStamp = "" //token var vToken = "" // cityPickerView var cityPickerView = UIPickerView() // cityToolBar var cityToolBar = UIToolbar() // cityList var dataCity = Array<Dictionary<String, AnyObject>>() // cityPickerView选择的row (省份) var selectRow = 0 // cityPickerView选择的Componentow (市) var selectComponent = 0 //发送验证码 @IBOutlet var SendCode: UIButton! override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView.init() initCity() initCityPickerView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 获取cityData func initCity() { let address : String = Bundle.main.path(forResource: "City", ofType: "plist")! let dic = NSDictionary.init(contentsOfFile: address) as! [String : Array<Any>] dataCity = dic["city"]! as! Array<Dictionary<String, AnyObject>> as Array<Dictionary<String, AnyObject>> // print(dataCity) } // cityPickerView func initCityPickerView(){ cityPickerView = UIPickerView.init() cityPickerView.delegate = self cityPickerView.dataSource = self cityToolBar = UIToolbar.init(frame: CGRect.init(x: 0, y: self.view.frame.size.height - self.cityToolBar.frame.size.height - 44.0, width: self.view.frame.size.width, height: 44)) openCity.inputView = cityPickerView openCity.inputAccessoryView = cityToolBar // 确定按钮 let sure : UIButton = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 40, height: 44)) sure.setTitle("确定", for: .normal) sure.setTitleColor(UIColor.init(hexString: "666666"), for: .normal) sure.addTarget(self, action: #selector(sureClick), for: .touchUpInside) let sureItem : UIBarButtonItem = UIBarButtonItem.init(customView: sure) let space : UIButton = UIButton.init(frame: CGRect.init(x: 40, y: 0, width: self.view.frame.size.width-140, height: 44)) space.setTitle("", for: .normal) let spaceItem : UIBarButtonItem = UIBarButtonItem.init(customView: space) // 取消按钮 let cancel : UIButton = UIButton.init(frame: CGRect.init(x: self.view.frame.size.width-44, y: 0, width: 40, height: 44)) cancel.setTitle("取消", for: .normal) cancel.addTarget(self, action: #selector(cancelClick), for: .touchUpInside) cancel.setTitleColor(UIColor.init(hexString: "666666"), for: .normal) cancel.setTitleColor(UIColor.init(hexString: "666666"), for: .normal) let cancelItem : UIBarButtonItem = UIBarButtonItem.init(customView: cancel) cityToolBar.setItems([sureItem,spaceItem,cancelItem], animated: true) } @IBAction func sendCode(_ sender: Any) { if !isTelNumber(num: phone.text!) { SVProgressHUD.showErrorMessage(ErrorMessage: "请输入正确的手机号", ForDuration: 2, completion: nil) return } if checkTextFieldEmpty([phone]) && isTelNumber(num: phone.text!) { let sendVerificationCodeRequestModel = SendVerificationCodeRequestModel() sendVerificationCodeRequestModel.phone = (self.phone.text!) sendVerificationCodeRequestModel.type = 3 AppAPIHelper.login().SendVerificationCode(model: sendVerificationCodeRequestModel, complete: { [weak self] (result) in SVProgressHUD.dismiss() self?.SendCode.isEnabled = true if let response = result { if response["result"] as! Int == 1 { self?.timer = Timer.scheduledTimer(timeInterval: 1,target:self!,selector: #selector(self?.updatecodeBtnTitle),userInfo: nil,repeats: true) self?.timeStamp = String.init(format: "%ld", response["timeStamp"] as! Int) self?.vToken = String.init(format: "%@", response["vToken"] as! String) }else{ SVProgressHUD.showErrorMessage(ErrorMessage: "验证码获取失败", ForDuration: 2, completion: nil) } } }, error: { (error) in self.didRequestError(error) self.SendCode.isEnabled = true }) } } //MARK:- 更新秒数 func updatecodeBtnTitle() { if codeTime == 0 { SendCode.isEnabled = true SendCode.setTitle("重新发送", for: .normal) codeTime = 60 timer?.invalidate() SendCode.setTitleColor(UIColor.init(hexString: "ffffff"), for: .normal) SendCode.backgroundColor = UIColor(hexString: AppConst.Color.orange) return } SendCode.isEnabled = false codeTime = codeTime - 1 let title: String = "\(codeTime)秒重新发送" SendCode.setTitle(title, for: .normal) SendCode.setTitleColor(UIColor.init(hexString: "000000"), for: .normal) SendCode.backgroundColor = UIColor(hexString: "ECECEC") } @IBAction func bingCard(_ sender: Any) { if checkTextFieldEmpty([phone,cardNum,name,openCity,vaildCode]){ let string = "yd1742653sd" + self.timeStamp + self.vaildCode.text! + self.phone.text! if string.md5_string() != self.vToken{ SVProgressHUD.showErrorMessage(ErrorMessage: "验证码错误", ForDuration: 1.0, completion: nil) return } let model = BindCardListRequestModel() model.bankUsername = name.text! model.account = cardNum.text! model.prov = openProvince model.city = openCityStr AppAPIHelper.user().bindcard(requestModel: model, complete: { [weak self](result) in SVProgressHUD.showSuccessMessage(SuccessMessage: "绑定成功", ForDuration: 1, completion: { self?.navigationController?.popViewController(animated: true) }) }, error: { (error) in self.didRequestError(error) }) } } } extension BindingBankCardVC : UIPickerViewDelegate,UIPickerViewDataSource { // city确定按钮事件 func sureClick(){ let dic : Dictionary = dataCity[selectComponent] openProvince = dataCity[selectComponent]["name"] as! String if let name = dic["name"] as? String{ if let arr : Array = (dic[name] as AnyObject) as? Array<AnyObject> { if let nameDic = arr[selectRow]["name"] { if nameDic != nil { openCityStr = nameDic as! String openCity.text = openProvince + " " + openCityStr } openCity.resignFirstResponder() selectRow = 0 selectComponent = 0 cityPickerView.selectRow(selectComponent, inComponent: 0, animated: true) cityPickerView.selectRow(0, inComponent: 1, animated: true) } } } } func cancelClick(){ selectRow = 0 selectComponent = 0 cityPickerView.selectRow(0 , inComponent: 0, animated: true) cityPickerView.selectRow(0 , inComponent: 1, animated: true) openCity.resignFirstResponder() } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return dataCity.count }else{ let dic : Dictionary = dataCity[selectComponent] let name = dic["name"] as! String let arr : Array = dic[name] as! Array<AnyObject> return arr.count } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return dataCity[row]["name"] as? String }else{ let dic : Dictionary = dataCity[selectComponent] let name = dic["name"] as! String let arr : Array = (dic[name] as AnyObject) as! Array<AnyObject> let nameDic = arr[row]["name"] return nameDic as? String } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 0{ selectComponent = row openProvince = dataCity[row]["name"] as! String pickerView.reloadComponent(1) }else{ selectRow = row } } }
b8de100f93bd8fd05dc3251d0043ee78
36.003534
162
0.543163
false
false
false
false
zxpLearnios/MyProject
refs/heads/master
test_projectDemo1/TVC && NAV/MyCustomTVC.swift
mit
1
// // MyCustomTVC.swift // test_Colsure // // Created by Jingnan Zhang on 16/5/10. // Copyright © 2016年 Jingnan Zhang. All rights reserved. // 1. 自定义TVC, 使用提醒按钮 2. 有判断类型; 3. plusBtn 做动画,从某处到tabbar的指定位置,动画结束后,主动刷新tabbar的子控件,在tabbar里加了判断,移除plusBtn,将此处加自定义的只有图片的tabbarItem即可;实现切屏时的位移问题的处理。 即只要是通过addSubView上到tabbar的估计在横竖屏切换时都会出错,必须是tabbar自带的东西才不会出错的。 import UIKit class MyCustomTVC: UITabBarController, UITabBarControllerDelegate, CAAnimationDelegate { var childVCs = [UIViewController]() var customTabBar = MyTabBar() var plusBtn = MyPlusButton() // 真正的和其他item平均分占了tabbar,如在自定义的tabbar里加plusBtn,则最左边的item的有效范围始终会挡住plusBtn的左半部 var toPoint = CGPoint.zero var isCompleteAnimate = false // MARK: xib\代码 都会调之,但此类型只会调一次 override class func initialize() { self.doInit() } // MARK: 做一些事 class func doInit() { // 所有的字控制器的tabbarItem的 字体属性 let tabbarItem = UITabBarItem.appearance() // 不能用UIBarButtonItem let itemAttributeNormal = [NSFontAttributeName: UIFont.systemFont(ofSize: 10), NSForegroundColorAttributeName: UIColor.red] let itemAttributeHighlight = [NSFontAttributeName: UIFont.systemFont(ofSize: 10), NSForegroundColorAttributeName: UIColor.green] tabbarItem.setTitleTextAttributes(itemAttributeNormal, for: UIControlState()) tabbarItem.setTitleTextAttributes(itemAttributeHighlight, for: .selected) // 用highlight无效 // 此处设置tabbarItem的图片无效(估计纯代码情况下也是无效) // tabBarItem.image = UIImage(named: "Customer_select") // tabBarItem.selectedImage = UIImage(named: "Customer_unselect") } override func viewDidLoad() { super.viewDidLoad() // -1 self.delegate = self // 0. 以便子控制器的view做转场动画时看到白色 self.view.backgroundColor = UIColor.white // 1, 加子控制器 let fistVC = firstChildVC() self.addChildViewControllers(fistVC, title: "第一个", itemImage: UIImage(named: "tabBar_me_icon"), itemSelectedImage: UIImage(named: "tabBar_me_click_icon")) let secondVC = secondChildVC() self.addChildViewControllers(secondVC, title: "第二个", itemImage: UIImage(named: "tabBar_essence_icon"), itemSelectedImage: UIImage(named: "tabBar_essence_click_icon")) let thirdVC = ThirdChildVC() self.addChildViewControllers(thirdVC, title: "第三个", itemImage: UIImage(named: "tabBar_friendTrends_icon"), itemSelectedImage: UIImage(named: "tabBar_friendTrends_click_icon")) // 2。 KVO替换原tabbar self.setValue(customTabBar, forKey: "tabBar") // 4.设置tabbaralpha self.tabBar.alpha = 0.8 let time = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.addPlusButton() } self.addChildViewControllers(UIViewController(), title: "", itemImage: UIImage(named: "tabBar_publish_icon"), itemSelectedImage: UIImage(named: "tabBar_publish_icon")) // 5. 屏幕旋转通知 kDevice.beginGeneratingDeviceOrientationNotifications() kNotificationCenter.addObserver(self, selector: #selector(orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // for item in self.tabBar.subviews { // if item.isKindOfClass(UIControl) { // item.removeFromSuperview() // 此时不要 // } // } // MARK: 判断类型 // is 和 item.isKindOfClass 都是判断一个实例是否是某种类型 // print(self.childViewControllers) } // 横屏变竖屏后,会再次调用之,故须做处理, 即不能在此处加加号按钮了,因为横屏变竖屏显示testVC后,就会进入此法,此时加号按钮会显示在testVC底部,且进入TabbarVC后plusBtn的位置也不对, 故在viewDidLoad里加plusBtn但需要延迟等viewDidAppear后才可以加,确保只会执行一次; 此时屏幕还是横着的 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 3.添加加号按钮, 必须在视图显示完毕后添加 // addPlusButton() } // MARK: 屏幕旋转了 @objc fileprivate func orientationDidChange(){ if kDevice.orientation == .portrait { } if kDevice.orientation == .landscapeRight || kDevice.orientation == .landscapeLeft { } } // MARK: 添加加号按钮 func addPlusButton(){ // 设置加号按钮 self.tabBar.addSubview(plusBtn) // let width = self.view.width / 4 // customTabBar.buttonW plusBtn.bounds = CGRect(x: 0, y: 0, width: width, height: 50) plusBtn.setImage(UIImage(named: "tabBar_publish_icon"), for: UIControlState()) // plusBtn.setTitle("加号", forState: .Normal) plusBtn.addTarget(self, action: #selector(btnAction), for: .touchUpInside) // 动画 let tabbarCenter = self.view.convert(self.tabBar.center, to: self.tabBar) let ani = CABasicAnimation.init(keyPath: "position") ani.duration = 0.5 ani.fromValue = NSValue.init(cgPoint: CGPoint(x: kwidth * 0.2, y: -kheight * 0.7)) toPoint = CGPoint(x: width * 1.5, y: tabbarCenter.y) ani.toValue = NSValue.init(cgPoint: toPoint) ani.delegate = self let time = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.plusBtn.isHidden = false self.plusBtn.layer.add(ani, forKey: "") } } func btnAction(_ plusBtn:MyPlusButton) { plusBtn.isSelected = !plusBtn.isSelected print("点击了加号按钮") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: 添加子控制器 fileprivate func addChildViewControllers(_ viewController:UIViewController, title:String, itemImage:UIImage?, itemSelectedImage:UIImage?){ let newItemSelectdImg = itemSelectedImage?.withRenderingMode(.alwaysOriginal) if self.viewControllers?.count == 3 { // 只有图片的tabbaritem let item = MyCustomTabBarItem.init(image: itemImage, selectedImage: itemSelectedImage) viewController.tabBarItem = item }else{ // 当navigationItem.title != tabBarItem.title 时,必须如此设置:先设置title,在设置navigationItem.title,设置tabBarItem.title已经无用了 // viewController.title = title // viewController.navigationItem.title = "我的账户" viewController.title = title viewController.tabBarItem.image = itemImage viewController.tabBarItem.selectedImage = newItemSelectdImg } let nav = MyCustomNav.init(rootViewController: viewController) self.addChildViewController(nav) } // MARK: UITabBarControllerDelegate func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { let index = self.viewControllers?.index(of: viewController) if index != nil { if index == 3 { self.perform(#selector(btnAction), with: plusBtn, afterDelay: 0) // viewController.tabBarItem.selectedImage = nil // 可以在此处设置点击item时的选中图片,因为点击item选中控制器被禁止了 // self.selectedIndex = 3 // 因为这样会选中并显示控制器 return false }else{ return true } }else{ return false } } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if flag { plusBtn.center = toPoint isCompleteAnimate = true self.tabBar.layoutSubviews() // 主动刷新 } } }
9db46f4a1c4d9567376377d769cd85f9
34.497778
209
0.623263
false
false
false
false
apple/swift-nio-http2
refs/heads/main
Sources/NIOHTTP2PerformanceTester/StreamTeardownBenchmark.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOEmbedded import NIOHPACK import NIOHTTP2 final class StreamTeardownBenchmark: Benchmark { private let concurrentStreams: Int // A manually constructed headers frame. private var headersFrame: ByteBuffer = { var headers = HPACKHeaders() headers.add(name: ":method", value: "GET", indexing: .indexable) headers.add(name: ":authority", value: "localhost", indexing: .nonIndexable) headers.add(name: ":path", value: "/", indexing: .indexable) headers.add(name: ":scheme", value: "https", indexing: .indexable) headers.add(name: "user-agent", value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", indexing: .nonIndexable) headers.add(name: "accept-encoding", value: "gzip, deflate", indexing: .indexable) var hpackEncoder = HPACKEncoder(allocator: .init()) var buffer = ByteBuffer() buffer.writeRepeatingByte(0, count: 9) buffer.moveReaderIndex(forwardBy: 9) try! hpackEncoder.encode(headers: headers, to: &buffer) let encodedLength = buffer.readableBytes buffer.moveReaderIndex(to: buffer.readerIndex - 9) // UInt24 length buffer.setInteger(UInt8(0), at: buffer.readerIndex) buffer.setInteger(UInt16(encodedLength), at: buffer.readerIndex + 1) // Type buffer.setInteger(UInt8(0x01), at: buffer.readerIndex + 3) // Flags, turn on END_HEADERs. buffer.setInteger(UInt8(0x04), at: buffer.readerIndex + 4) // 4 byte stream identifier, set to zero for now as we update it later. buffer.setInteger(UInt32(0), at: buffer.readerIndex + 5) return buffer }() private let emptySettings: ByteBuffer = { var buffer = ByteBuffer() buffer.reserveCapacity(9) // UInt24 length, is 0 bytes. buffer.writeInteger(UInt8(0)) buffer.writeInteger(UInt16(0)) // Type buffer.writeInteger(UInt8(0x04)) // Flags, none. buffer.writeInteger(UInt8(0x00)) // 4 byte stream identifier, set to zero. buffer.writeInteger(UInt32(0)) return buffer }() private var settingsACK: ByteBuffer { // Copy the empty SETTINGS and add the ACK flag var settingsCopy = self.emptySettings settingsCopy.setInteger(UInt8(0x01), at: settingsCopy.readerIndex + 4) return settingsCopy } init(concurrentStreams: Int) { self.concurrentStreams = concurrentStreams } func setUp() { } func tearDown() { } func createChannel() throws -> EmbeddedChannel { let channel = EmbeddedChannel() _ = try channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in return streamChannel.pipeline.addHandler(DoNothingServer()) }.wait() try channel.pipeline.addHandler(SendGoawayHandler(expectedStreams: self.concurrentStreams)).wait() try channel.connect(to: .init(unixDomainSocketPath: "/fake"), promise: nil) // Gotta do the handshake here. var initialBytes = ByteBuffer(string: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") initialBytes.writeImmutableBuffer(self.emptySettings) initialBytes.writeImmutableBuffer(self.settingsACK) try channel.writeInbound(initialBytes) while try channel.readOutbound(as: ByteBuffer.self) != nil { } return channel } func destroyChannel(_ channel: EmbeddedChannel) throws { _ = try channel.finish() } func run() throws -> Int { var bodyByteCount = 0 var completedIterations = 0 while completedIterations < 10_000 { let channel = try self.createChannel() bodyByteCount &+= try self.sendInterleavedRequestsAndTerminate(self.concurrentStreams, channel) completedIterations += self.concurrentStreams try self.destroyChannel(channel) } return bodyByteCount } private func sendInterleavedRequestsAndTerminate(_ interleavedRequests: Int, _ channel: EmbeddedChannel) throws -> Int { var streamID = HTTP2StreamID(1) for _ in 0 ..< interleavedRequests { self.headersFrame.setInteger(UInt32(Int32(streamID)), at: self.headersFrame.readerIndex + 5) try channel.writeInbound(self.headersFrame) streamID = streamID.advanced(by: 2) } var count = 0 while let data = try channel.readOutbound(as: ByteBuffer.self) { count &+= data.readableBytes channel.embeddedEventLoop.run() } // We need to have got a GOAWAY back, precondition that the count is large enough. precondition(count == 17) return count } } fileprivate class DoNothingServer: ChannelInboundHandler { public typealias InboundIn = HTTP2Frame.FramePayload public typealias OutboundOut = HTTP2Frame.FramePayload } fileprivate class SendGoawayHandler: ChannelInboundHandler { public typealias InboundIn = HTTP2Frame public typealias OutboundOut = HTTP2Frame private static let goawayFrame: HTTP2Frame = HTTP2Frame( streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .enhanceYourCalm, opaqueData: nil) ) private let expectedStreams: Int private var seenStreams: Int init(expectedStreams: Int) { self.expectedStreams = expectedStreams self.seenStreams = 0 } func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { if event is NIOHTTP2StreamCreatedEvent { self.seenStreams += 1 if self.seenStreams == self.expectedStreams { // Send a GOAWAY to tear all streams down. context.writeAndFlush(self.wrapOutboundOut(SendGoawayHandler.goawayFrame), promise: nil) } } } }
63571ef7e220cfcfde70c360a8fe14c0
34.895028
145
0.643374
false
false
false
false
bparish628/iFarm-Health
refs/heads/master
iOS/iFarm-Health/Classes/News/NewsViewController.swift
apache-2.0
1
// // NewsViewController.swift // iFarm-Health // // Created by Benji Parish on 9/26/17. // Copyright © 2017 Benji Parish. All rights reserved. // import UIKit class NewsViewController: UITableViewController { var articles = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // let filePath = Bundle.main.path(forResource:"News", ofType: "plist") // // if let path = filePath { // articles = NSArray(contentsOfFile: path)! as [AnyObject] // print(articles) // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return articles.count } /* 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. } */ }
b31dd27783b671e8ac42d3439bfbfa32
31.072917
136
0.651835
false
false
false
false
lacklock/NiceGesture
refs/heads/master
NiceGestureDemo/PanViewController.swift
mit
1
// // PanViewController.swift // NiceGesture // // Created by 卓同学 on 16/4/4. // Copyright © 2016年 zhuo. All rights reserved. // import UIKit class PanViewController: UIViewController { @IBOutlet weak var lbState: UILabel! override func viewDidLoad() { super.viewDidLoad() lbState.nc_addPanGesture() .whenEnded {[unowned self] (recognizer) -> Void in self.lbState.text=recognizer.state.toString() self.lbState.transform=CGAffineTransformIdentity self.view.layoutIfNeeded() }.whenChanged {[unowned self] (recognizer) -> Void in self.lbState.text=recognizer.state.toString() let touchPoint = recognizer.locationInView(self.view) let offsetX=touchPoint.x-self.view.center.x let offsetY=touchPoint.y-self.view.center.y self.lbState.transform=CGAffineTransformMakeTranslation(offsetX, offsetY) } // lbState.nc_addPanGesture().whenStatesHappend([.Ended,.Changed]) { (gestureRecognizer) -> Void in // print("another way :\(gestureRecognizer.state.toString())") // } } }
cc82d5bf8fc9cae0e864a7cf17e32288
31
106
0.611842
false
false
false
false
MJsaka/MJZZ
refs/heads/master
MJZZ/StatisticData.swift
gpl-3.0
1
// // MJZZStatisticData.swift // MJZZ // // Created by MJsaka on 15/10/21. // Copyright © 2015年 MJsaka. All rights reserved. // import UIKit class MJZZTime : NSObject , NSCoding{ let year : Int let month : Int let day : Int let hour : Int let minute : Int override convenience init() { let calendar = NSCalendar.currentCalendar() calendar.timeZone = NSTimeZone.systemTimeZone() let comp : NSDateComponents = calendar.components([.Year, .Month, .Day , .Hour , .Minute], fromDate: NSDate()) self.init(year: comp.year , month: comp.month , day: comp.day ,hour: comp.hour , minute: comp.minute) } init(year aYear:Int , month aMonth : Int , day aDay : Int ,hour aHour : Int , minute aMinute : Int){ year = aYear month = aMonth day = aDay hour = aHour minute = aMinute } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(year, forKey: "year") aCoder.encodeInteger(month, forKey: "month") aCoder.encodeInteger(day, forKey: "day") aCoder.encodeInteger(hour, forKey: "hour") aCoder.encodeInteger(minute, forKey: "minute") } required init?(coder aDecoder: NSCoder) { year = aDecoder.decodeIntegerForKey("year") month = aDecoder.decodeIntegerForKey("month") day = aDecoder.decodeIntegerForKey("day") hour = aDecoder.decodeIntegerForKey("hour") minute = aDecoder.decodeIntegerForKey("minute") } } @objc protocol MJZZDataProtocol{ var data : [MJZZDataProtocol] {get set} var duration : Int {get set} var time : MJZZTime {get set} func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope) } class MJZZData : NSObject , MJZZDataProtocol , NSCoding { var data : [MJZZDataProtocol] var duration : Int = 0 var time : MJZZTime override convenience init() { self.init(withTime : MJZZTime()) } init(withTime aTime : MJZZTime){ data = [MJZZDataProtocol]() time = aTime } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(duration, forKey: "duration") aCoder.encodeObject(time, forKey: "time") aCoder.encodeObject(data, forKey: "data") } required init(coder aDecoder: NSCoder) { duration = aDecoder.decodeIntegerForKey("duration") time = aDecoder.decodeObjectForKey("time") as! MJZZTime data = aDecoder.decodeObjectForKey("data") as! [MJZZDataProtocol] } func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){ return } } class MJZZDayData : MJZZData { func appendOnceData(aData : MJZZData){ data.insert(aData, atIndex: 0) duration += aData.duration } override func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){ if dataScope == MJZZDataScope.day { for index in indexes { duration -= data[index].duration } if duration == 0 { return } for (var i = indexes.count - 1; i >= 0; --i) { let index = indexes[i] data.removeAtIndex(index) } } } } class MJZZMonthData : MJZZData { func appendOnceData (aData : MJZZData){ var aDayData : MJZZDayData if !data.isEmpty && data.first!.time.day == aData.time.day{ aDayData = data.first as! MJZZDayData }else{ aDayData = MJZZDayData(withTime: aData.time) data.insert(aDayData, atIndex: 0) } aDayData.appendOnceData(aData) duration += aData.duration } override func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){ if dataScope == MJZZDataScope.month { for index in indexes { duration -= data[index].duration } if duration == 0 { return } for (var i = indexes.count - 1; i >= 0; --i) { let index = indexes[i] data.removeAtIndex(index) } } else { duration -= data[dataIndex.dayIndex].duration data[dataIndex.dayIndex].deleteDataAtIndexes(indexes, withSelectedDataIndex: dataIndex, withSelectedDataScope: dataScope) if data[dataIndex.dayIndex].duration == 0 { data.removeAtIndex(dataIndex.dayIndex) } else { duration += data[dataIndex.dayIndex].duration } } } } class MJZZYearData : MJZZData { func appendOnceData (aData : MJZZData){ var aMonthData : MJZZMonthData if !data.isEmpty && data.first!.time.month == aData.time.month { aMonthData = data.first as! MJZZMonthData }else{ aMonthData = MJZZMonthData(withTime: aData.time) data.insert(aMonthData, atIndex: 0) } aMonthData.appendOnceData(aData) duration += aData.duration } override func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){ if dataScope == MJZZDataScope.year { for index in indexes { duration -= data[index].duration } if duration == 0 { return } for (var i = indexes.count - 1; i >= 0; --i) { let index = indexes[i] data.removeAtIndex(index) } } else { duration -= data[dataIndex.monthIndex].duration data[dataIndex.monthIndex].deleteDataAtIndexes(indexes, withSelectedDataIndex: dataIndex, withSelectedDataScope: dataScope) if data[dataIndex.monthIndex].duration == 0 { data.removeAtIndex(dataIndex.monthIndex) } else { duration += data[dataIndex.monthIndex].duration } } } } var singletonStatisticData : MJZZStatisticData = MJZZStatisticData() class MJZZStatisticData : MJZZData{ var bestOnceDuration : Int = 0 class func appendOnceData (aData : MJZZData){ var aYearData : MJZZYearData if !singletonStatisticData.data.isEmpty && singletonStatisticData.data.first!.time.year == aData.time.year { aYearData = singletonStatisticData.data.first as! MJZZYearData }else{ aYearData = MJZZYearData(withTime: aData.time) singletonStatisticData.data.insert(aYearData, atIndex: 0) } aYearData.appendOnceData(aData) singletonStatisticData.duration += aData.duration if aData.duration > singletonStatisticData.bestOnceDuration { singletonStatisticData.bestOnceDuration = aData.duration NSNotificationCenter.defaultCenter().postNotificationName("MJZZNotificationBestDurationChanged", object: singletonStatisticData) } NSNotificationCenter.defaultCenter().postNotificationName("MJZZNotificationStatisticDataChanged", object: singletonStatisticData) } class func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){ singletonStatisticData.duration -= singletonStatisticData.data[dataIndex.yearIndex].duration singletonStatisticData.data[dataIndex.yearIndex].deleteDataAtIndexes(indexes, withSelectedDataIndex: dataIndex, withSelectedDataScope: dataScope) if singletonStatisticData.data[dataIndex.yearIndex].duration == 0 { singletonStatisticData.data.removeAtIndex(dataIndex.yearIndex) } else { singletonStatisticData.duration += singletonStatisticData.data[dataIndex.yearIndex].duration } } class func sharedData() -> MJZZStatisticData { return singletonStatisticData } convenience init(){ self.init(withTime : MJZZTime()) } override init(withTime aTime: MJZZTime) { super.init(withTime: aTime) } override func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) aCoder.encodeInteger(bestOnceDuration, forKey: "bestOnceDuration") } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) bestOnceDuration = aDecoder.decodeIntegerForKey("bestOnceDuration") } }
5f8790b9e8263c7552bc12324aacbd0d
38.870968
153
0.63981
false
false
false
false
SuPair/firefox-ios
refs/heads/master
Client/Frontend/Settings/AppSettingsOptions.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: Strings.FxASignInToSync, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var accessibilityIdentifier: String? { return "SignInToSync" } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self viewController.url = settings.profile.accountConfiguration.signInURL navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.imageView?.image = UIImage.templateImageNamed("FxA-Default") cell.imageView?.tintColor = UIColor.theme.tableView.disabledRowText cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2 cell.imageView?.layer.masksToBounds = true } } class SyncNowSetting: WithAccountSetting { let imageView = UIImageView(frame: CGRect(width: 30, height: 30)) let syncIconWrapper = UIImage.createWithColor(CGSize(width: 30, height: 30), color: UIColor.clear) let syncBlueIcon = UIImage(named: "FxA-Sync-Blue")?.createScaled(CGSize(width: 20, height: 20)) let syncIcon = UIImage(named: "FxA-Sync")?.createScaled(CGSize(width: 20, height: 20)) // Animation used to rotate the Sync icon 360 degrees while syncing is in progress. let continuousRotateAnimation = CABasicAnimation(keyPath: "transform.rotation") override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(stopRotateSyncIcon), name: .ProfileDidFinishSyncing, object: nil) } fileprivate lazy var timestampFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() fileprivate var syncNowTitle: NSAttributedString { if !DeviceInfo.hasConnectivity() { return NSAttributedString( string: Strings.FxANoInternetConnection, attributes: [ NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultMediumFont ] ) } return NSAttributedString( string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [ NSAttributedStringKey.foregroundColor: self.enabled ? UIColor.theme.tableView.syncText : UIColor.theme.tableView.headerTextLight, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont ] ) } fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText, NSAttributedStringKey.font: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFont.Weight.regular)]) func startRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.add(self.continuousRotateAnimation, forKey: "rotateKey") } } @objc func stopRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.removeAllAnimations() } } override var accessoryType: UITableViewCellAccessoryType { return .none } override var style: UITableViewCellStyle { return .value1 } override var image: UIImage? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncIcon } switch syncStatus { case .inProgress: return syncBlueIcon default: return syncIcon } } override var title: NSAttributedString? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncNowTitle } switch syncStatus { case .bad(let message): guard let message = message else { return syncNowTitle } return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .warning(let message): return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.warningText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .inProgress: return syncingTitle default: return syncNowTitle } } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp)) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)] let range = NSRange(location: 0, length: attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override var enabled: Bool { if !DeviceInfo.hasConnectivity() { return false } return profile.hasSyncableAccount() } fileprivate lazy var troubleshootButton: UIButton = { let troubleshootButton = UIButton(type: .roundedRect) troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal) troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside) troubleshootButton.tintColor = UIColor.theme.tableView.rowActionAccessory troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont troubleshootButton.sizeToFit() return troubleshootButton }() fileprivate lazy var warningIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "AmberCaution")) imageView.sizeToFit() return imageView }() fileprivate lazy var errorIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "RedCaution")) imageView.sizeToFit() return imageView }() fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios") @objc fileprivate func troubleshoot() { let viewController = SettingsContentViewController() viewController.url = syncSUMOURL settings.navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .bad(let message): if let _ = message { // add the red warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(errorIcon, toCell: cell) } else { cell.detailTextLabel?.attributedText = status cell.accessoryView = nil } case .warning(_): // add the amber warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(warningIcon, toCell: cell) case .good: cell.detailTextLabel?.attributedText = status fallthrough default: cell.accessoryView = nil } } else { cell.accessoryView = nil } cell.accessoryType = accessoryType cell.isUserInteractionEnabled = !profile.syncManager.isSyncing && DeviceInfo.hasConnectivity() // Animation that loops continously until stopped continuousRotateAnimation.fromValue = 0.0 continuousRotateAnimation.toValue = CGFloat(Double.pi) continuousRotateAnimation.isRemovedOnCompletion = true continuousRotateAnimation.duration = 0.5 continuousRotateAnimation.repeatCount = .infinity // To ensure sync icon is aligned properly with user's avatar, an image is created with proper // dimensions and color, then the scaled sync icon is added as a subview. imageView.contentMode = .center imageView.image = image cell.imageView?.subviews.forEach({ $0.removeFromSuperview() }) cell.imageView?.image = syncIconWrapper cell.imageView?.addSubview(imageView) if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .inProgress: self.startRotateSyncIcon() default: self.stopRotateSyncIcon() } } } fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) { cell.contentView.addSubview(image) cell.textLabel?.snp.updateConstraints { make in make.leading.equalTo(image.snp.trailing).offset(5) make.trailing.lessThanOrEqualTo(cell.contentView) make.centerY.equalTo(cell.contentView) } image.snp.makeConstraints { make in make.leading.equalTo(cell.contentView).offset(17) make.top.equalTo(cell.textLabel!).offset(2) } } override func onClick(_ navigationController: UINavigationController?) { if !DeviceInfo.hasConnectivity() { return } NotificationCenter.default.post(name: .UserInitiatedSyncManually, object: nil) profile.syncManager.syncEverything(why: .syncNow) } } // Sync setting that shows the current Firefox Account status. class AccountStatusSetting: WithAccountSetting { override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(updateAccount), name: .FirefoxAccountProfileChanged, object: nil) } @objc func updateAccount(notification: Notification) { DispatchQueue.main.async { self.settings.tableView.reloadData() } } override var image: UIImage? { if let image = profile.getAccount()?.fxaProfile?.avatar.image { return image.createScaled(CGSize(width: 30, height: 30)) } let image = UIImage(named: "placeholder-avatar") return image?.createScaled(CGSize(width: 30, height: 30)) } override var accessoryType: UITableViewCellAccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .needsVerification: // We link to the resend verification email page. return .disclosureIndicator case .needsPassword: // We link to the re-enter password page. return .disclosureIndicator case .none: // We link to FxA web /settings. return .disclosureIndicator case .needsUpgrade: // In future, we'll want to link to an upgrade page. return .none } } return .disclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { if let displayName = account.fxaProfile?.displayName { return NSAttributedString(string: displayName, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText]) } if let email = account.fxaProfile?.email { return NSAttributedString(string: email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText]) } return NSAttributedString(string: account.email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { var string: String switch account.actionNeeded { case .none: return nil case .needsVerification: string = Strings.FxAAccountVerifyEmail break case .needsPassword: string = Strings.FxAAccountVerifyPassword break case .needsUpgrade: string = Strings.FxAAccountUpgradeFirefox break } let orange = UIColor.theme.tableView.warningText let range = NSRange(location: 0, length: string.count) let attrs = [NSAttributedStringKey.foregroundColor: orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } return nil } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .none: let viewController = SyncContentSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) return case .needsVerification: var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = try? cs?.asURL() { viewController.url = url } case .needsPassword: var cs = URLComponents(url: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = try? cs?.asURL() { viewController.url = url } case .needsUpgrade: // In future, we'll want to link to an upgrade page. return } } navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if let imageView = cell.imageView { imageView.subviews.forEach({ $0.removeFromSuperview() }) imageView.frame = CGRect(width: 30, height: 30) imageView.layer.cornerRadius = (imageView.frame.height) / 2 imageView.layer.masksToBounds = true imageView.image = image } } } // For great debugging! class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.hasPrefix("browser.") || file.hasPrefix("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.hasPrefix("browser.") || file.hasPrefix("logins.") || file.hasPrefix("metadata.") } } catch { print("Couldn't export browser data: \(error).") } } } class ExportLogDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy log files to app container", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Logger.copyPreviousLogsToDocuments(); } } /* FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch. These are usually features behind a partial release and not features released to the entire population. */ class FeatureSwitchSetting: BoolSetting { let featureSwitch: FeatureSwitch let prefs: Prefs init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) { self.featureSwitch = featureSwitch self.prefs = prefs super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title) } override var hidden: Bool { return !ShowDebugSettings } override func displayBool(_ control: UISwitch) { control.isOn = featureSwitch.isMember(prefs) } override func writeBool(_ control: UISwitch) { self.featureSwitch.setMembership(control.isOn, for: self.prefs) } } class EnableBookmarkMergingSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Enable Bidirectional Bookmark Sync ", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { AppConstants.shouldMergeBookmarks = true } } class ForceCrashSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: Force Crash", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Sentry.shared.crash() } } // Show the current version of Firefox class VersionSetting: Setting { unowned let settings: SettingsTableViewController override var accessibilityIdentifier: String? { return "FxVersion" } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .none } override func onClick(_ navigationController: UINavigationController?) { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } } // Opens the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile override var accessibilityIdentifier: String? { return "ShowTour" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class SendAnonymousUsageDataSetting: BoolSetting { init(prefs: Prefs, delegate: SettingsDelegate?) { let statusText = NSMutableAttributedString() statusText.append(NSAttributedString(string: Strings.SendUsageSettingMessage, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])) statusText.append(NSAttributedString(string: " ")) statusText.append(NSAttributedString(string: Strings.SendUsageSettingLink, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.general.highlightBlue])) super.init( prefs: prefs, prefKey: AppConstants.PrefSendUsageData, defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.SendUsageSettingTitle), attributedStatusText: statusText, settingDidChange: { AdjustIntegration.setEnabled($0) LeanPlumClient.shared.set(attributes: [LPAttributeKey.telemetryOptIn: $0]) LeanPlumClient.shared.set(enabled: $0) } ) } override var url: URL? { return SupportUtils.URLForTopic("adjust") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the SUMO page in a new tab class OpenSupportPageSetting: Setting { init(delegate: SettingsDelegate?) { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true) { if let url = URL(string: "https://support.mozilla.org/products/ios") { self.delegate?.settingsOpenURLInNewTab(url) } } } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! weak var navigationController: UINavigationController? weak var settings: AppSettingsTableViewController? override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.tabManager = settings.tabManager self.navigationController = settings.navigationController self.settings = settings as? AppSettingsTableViewController let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.") super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else { settings?.navigateToLoginsList() LeanPlumClient.shared.track(event: .openedLogins) return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.loginsTouchReason, success: { self.settings?.navigateToLoginsList() LeanPlumClient.shared.track(event: .openedLogins) }, cancel: { self.deselectRow() }, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self.settings) self.deselectRow() }) } else { settings?.navigateToLoginsList() LeanPlumClient.shared.track(event: .openedLogins) } } } class TouchIDPasscodeSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TouchIDPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.profile = settings.profile self.tabManager = settings.tabManager let localAuthContext = LAContext() let title: String if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID { title = AuthenticationStrings.faceIDPasscodeSetting } else { title = AuthenticationStrings.touchIDPasscodeSetting } } else { title = AuthenticationStrings.passcode } super.init(title: NSAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AuthenticationSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } @available(iOS 11, *) class ContentBlockerSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TrackingProtection" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsTrackingProtectionSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ContentBlockerSettingViewController(prefs: profile.prefs) viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = Strings.SettingsDataManagementSectionName super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChinaSyncServiceSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } let prefKey = "useChinaSyncService" override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? BrowserProfile.isChinaEdition cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) } } class StageSyncServiceDebugSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } var prefKey: String = "useStageSyncService" override var accessibilityIdentifier: String? { return "DebugStageSync" } override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return true } return false } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: use stage servers", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { // Derive the configuration we display from the profile. Currently, this could be either a custom // FxA server or FxA stage servers. let isOn = prefs.boolForKey(prefKey) ?? false let isCustomSync = prefs.boolForKey(PrefsKeys.KeyUseCustomSyncService) ?? false var configurationURL = ProductionFirefoxAccountConfiguration().authEndpointURL if isCustomSync { configurationURL = CustomFirefoxAccountConfiguration(prefs: profile.prefs).authEndpointURL } else if isOn { configurationURL = StageFirefoxAccountConfiguration().authEndpointURL } return NSAttributedString(string: configurationURL.absoluteString, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? false cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) settings.tableView.reloadData() } } class HomePageSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Homepage" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsHomePageSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = HomePageSettingsViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class NewTabPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "NewTab" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = NewTabContentSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } @available(iOS 12.0, *) class SiriPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "SiriSettings" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsSiriSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SiriSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class OpenWithSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "OpenWith.Setting" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = OpenWithSettingsViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } } class AdvanceAccountSetting: HiddenSetting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "AdvanceAccount.Setting" } override var title: NSAttributedString? { return NSAttributedString(string: Strings.SettingsAdvanceAccountTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]) } override init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(settings: settings) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AdvanceAccountSettingViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } override var hidden: Bool { return !ShowDebugSettings || profile.hasAccount() } } class ThemeSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var accessibilityIdentifier: String? { return "DisplayThemeOption" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsDisplayThemeTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(ThemeSettingsController(), animated: true) } }
d5388c0f4720953deb933841dab45f7c
40.211434
327
0.696928
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/DebugInfo/linetable.swift
apache-2.0
3
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend %s -S -g -o - | %FileCheck %s --check-prefix ASM-CHECK // REQUIRES: CPU=i386 || CPU=x86_64 import Swift func markUsed<T>(_ t: T) {} class MyClass { var x : Int64 init(input: Int64) { x = input } func do_something(_ input: Int64) -> Int64 { return x * input } } func call_me(_ code: @escaping () -> Void) { code () } func main(_ x: Int64) -> Void // CHECK: define hidden {{.*}} void @_T09linetable4main{{[_0-9a-zA-Z]*}}F { var my_class = MyClass(input: 10) // Linetable continuity. Don't go into the closure expression. // ASM-CHECK: .loc [[FILEID:[0-9]]] [[@LINE+1]] 5 call_me ( // ASM-CHECK-NOT: .loc [[FILEID]] [[@LINE+1]] 5 // CHECK: define {{.*}} @_T09linetable4mainys5Int64VFyycfU_Tf2in_n({{.*}}) { var result = my_class.do_something(x) markUsed(result) // CHECK: call {{.*}} @swift_rt_swift_release {{.*}} // CHECK: bitcast // CHECK: llvm.lifetime.end // CHECK: call {{.*}} @swift_rt_swift_release {{.*}}, !dbg ![[CLOSURE_END:.*]] // CHECK-NEXT: ret void, !dbg ![[CLOSURE_END]] // CHECK: ![[CLOSURE_END]] = !DILocation(line: [[@LINE+1]], } ) // The swift_releases at the end should not jump to the point where // that memory was retained/allocated and also not to line 0. // ASM-CHECK-NOT: .loc [[FILEID]] 0 0 // ASM-CHECK: .loc [[FILEID]] [[@LINE+2]] 1 // ASM-CHECK: ret } // ASM-CHECK: {{^_?_T09linetable4mainys5Int64VFyycfU_Tf2in_n:}} // ASM-CHECK-NOT: retq // The end-of-prologue should have a valid location (0 is ok, too). // ASM-CHECK: .loc [[FILEID]] {{0|34}} {{[0-9]+}} prologue_end main(30)
e4a1a45ff28b79b0ea570daee942ec8b
28.77193
85
0.594579
false
false
false
false
davefoxy/SwiftBomb
refs/heads/master
SwiftBomb/Classes/Requests/LocationsRequests.swift
mit
1
// // LocationsRequests.swift // SwiftBomb // // Created by David Fox on 25/04/2016. // Copyright © 2016 David Fox. All rights reserved. // import Foundation extension SwiftBomb { /** Fetches a paginated list of `LocationResource` instances. This list can be filtered to a search term, paginated and sorted. - parameter query: An optional search term used to filter for a particular location. - parameter pagination: An optional `PaginationDefinition` to define the limit and offset when paginating results. - parameter sort: An optional `SortDefinition` to define how the results should be sorted. - parameter fields: An optional array of fields to return in the response. See the available options at http://www.giantbomb.com/api/documentation#toc-0-20. Pass nil to return everything. - parameter completion: A closure returning an optional generic `PaginatedResults` object containing the returned `LocationResource` objects and pagination information and also, an optional `SwiftBombRequestError` object if the request failed. */ public static func fetchLocations(_ query: String? = nil, pagination: PaginationDefinition? = nil, sort: SortDefinition? = nil, fields: [String]? = nil, completion: @escaping (PaginatedResults<LocationResource>?, _ error: SwiftBombRequestError?) -> Void) { let instance = SwiftBomb.framework guard let requestFactory = instance.requestFactory, let networkingManager = instance.networkingManager else { completion(nil, .frameworkConfigError) return } let request = requestFactory.locationRequest(query, pagination: pagination, sort: sort, fields: fields) networkingManager.performPaginatedRequest(request, objectType: LocationResource.self, completion: completion) } } extension RequestFactory { func locationRequest(_ query: String? = nil, pagination: PaginationDefinition? = nil, sort: SortDefinition? = nil, fields: [String]? = nil) -> SwiftBombRequest { var request = SwiftBombRequest(configuration: configuration, path: "locations", method: .get, pagination: pagination, sort: sort, fields: fields) addAuthentication(&request) if let query = query { request.addURLParameter("filter", value: "name:\(query)") } return request } } extension LocationResource { /** Fetches extended info for this location. Also re-populates base data in the case where this object is a stub from another parent resource. - parameter fields: An optional array of fields to return in the response. See the available options at http://www.giantbomb.com/api/documentation#toc-0-20. Pass nil to return everything. - parameter completion: A closure containing an optional `SwiftBombRequestError` if the request failed. */ public func fetchExtendedInfo(_ fields: [String]? = nil, completion: @escaping (_ error: SwiftBombRequestError?) -> Void) { let api = SwiftBomb.framework guard let networkingManager = api.networkingManager, let id = id, let request = api.requestFactory?.simpleRequest("location/\(id)/", fields: fields) else { completion(.frameworkConfigError) return } networkingManager.performDetailRequest(request, resource: self, completion: completion) } }
449578095015f3259101d42221978974
46.581081
260
0.687305
false
true
false
false
Bouke/HAP
refs/heads/master
Sources/HAP/Utils/Data+Extensions.swift
mit
1
import Foundation // Removed in Xcode 8 beta 3 func + (lhs: Data, rhs: Data) -> Data { var result = lhs result.append(rhs) return result } extension Data { init?(hex: String) { var result = [UInt8]() var from = hex.startIndex while from < hex.endIndex { guard let to = hex.index(from, offsetBy: 2, limitedBy: hex.endIndex) else { return nil } guard let num = UInt8(hex[from..<to], radix: 16) else { return nil } result.append(num) from = to } self = Data(result) } } extension RandomAccessCollection where Iterator.Element == UInt8 { var hex: String { self.reduce("") { $0 + String(format: "%02x", $1) } } }
15c7f0254b650496f118f64ed3619824
23.71875
87
0.525917
false
false
false
false