repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
think-dev/MadridBUS
MadridBUS/Source/Data/Repositories/Repository.swift
1
1776
import Foundation class Repository { let requestClient: RequestClient required init(injector: Injector) { self.requestClient = injector.instanceOf(RequestClient.self) } func processSingleResponse<T>(response: Response<T>, functionName: String = #function) throws -> T { guard response.isSuccess else { throw Errors.RepositoryError(error: response.dataError!) } guard let singleData = response.dataResponse else { throw Errors.RepositoryError(error: buildUnexpectedError(functionName: functionName)) } return singleData } func processOptionalResponse<T>(response: Response<T>, functionName: String = #function) throws -> T? { guard response.isSuccess else { throw Errors.RepositoryError(error: response.dataError!) } return response.dataResponse } func processMultiResponse<T>(response: Response<T>, functionName: String = #function) throws -> [T] { guard response.isSuccess else { throw Errors.RepositoryError(error: response.dataError!) } guard let multiData = response.dataArrayResponse else { throw Errors.RepositoryError(error: buildUnexpectedError(functionName: functionName)) } return multiData } func processEmptyResponse<T>(response: Response<T>, functionName: String = #function) throws { guard response.isSuccess else { throw Errors.RepositoryError(error: response.dataError!) } } private func buildUnexpectedError(functionName: String) -> RepositoryError { return RepositoryError(message: "Unexpected data response in \(functionName)") } }
mit
535b55b44486b68d500b32ef9dfd165c
33.153846
107
0.654279
5.285714
false
false
false
false
dnevera/IMProcessing
IMProcessingXOS/ViewController.swift
1
8184
// // ViewController.swift // ImageMetalling-07 // // Created by denis svinarchuk on 14.12.15. // Copyright © 2015 IMetalling. All rights reserved. // import Cocoa import simd enum IMPPrefs{ struct colors { static let background = float4(x:0.1,y:0.1,z:0.1,w:1.0) } } class ViewController: NSViewController { @IBOutlet weak var dominantColorLabel: NSTextField! @IBOutlet weak var minRangeLabel: NSTextField! @IBOutlet weak var maxRangeLabel: NSTextField! @IBOutlet weak var valueSlider1: NSSlider! @IBOutlet weak var textValueLabel: NSTextField! @IBOutlet weak var histogramCDFContainerView: NSView! @IBOutlet weak var histogramContainerView: NSView! @IBOutlet weak var scrollView: NSScrollView! let context = IMPContext() var mainFilter:IMPTestFilter! var lutFilter:IMPLutFilter? var imageView: IMPView! var histogramView: IMPHistogramView! var histogramCDFView: IMPHistogramView! var q = dispatch_queue_create("ViewController", DISPATCH_QUEUE_CONCURRENT) private func asyncChanges(block:()->Void) { dispatch_async(q, { () -> Void in // // немного того, но... :) // dispatch_async(dispatch_get_main_queue()) { () -> Void in block() } }) } @IBAction func changeValue1(sender: NSSlider) { let value = sender.floatValue/100 asyncChanges { () -> Void in self.textValueLabel.stringValue = String(format: "%2.5f", value); self.mainFilter.noise.adjustment.size = value } } @IBAction func changeValue2(sender: NSSlider) { asyncChanges { () -> Void in self.mainFilter.contrastFilter.adjustment.blending.opacity = sender.floatValue/100 } } @IBAction func changeValue3(sender: NSSlider) { asyncChanges { () -> Void in self.mainFilter.awbFilter.adjustment.blending.opacity = sender.floatValue/100 } } @IBAction func changeValue4(sender: NSSlider) { asyncChanges { () -> Void in self.lutFilter?.adjustment.blending.opacity = sender.floatValue/100 } } @IBAction func changeValue5(sender: NSSlider) { asyncChanges { () -> Void in if sender.floatValue < 2 { self.mainFilter.blur.radius = 0 } else { self.mainFilter.blur.radius = (512*sender.floatValue/100).int } self.mainFilter.noise.adjustment.amount.total = (sender.floatValue/100) self.mainFilter.noise.adjustment.amount.color = 1 } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. histogramContainerView.wantsLayer = true histogramContainerView.layer?.backgroundColor = IMPColor.redColor().CGColor histogramView = IMPHistogramView(context: context, frame: histogramContainerView.bounds) //histogramView.histogramLayer.solver.layer.backgroundColor = IMPPrefs.colors.background histogramView.generator.layer.backgroundColor = IMPPrefs.colors.background histogramCDFView = IMPHistogramView(context: context, frame: histogramContainerView.bounds) histogramCDFView.generator.layer.backgroundColor = IMPPrefs.colors.background histogramCDFView.type = .CDF //histogramCDFView.generator.layer.histogramType = (type:.CDF,power:self.valueSlider1.floatValue/100) histogramContainerView.addSubview(histogramView) histogramCDFContainerView.addSubview(histogramCDFView) imageView = IMPView(frame: scrollView.bounds) mainFilter = IMPTestFilter(context: context, histogramView: histogramView, histogramCDFView: histogramCDFView) imageView.filter = mainFilter mainFilter.sourceAnalayzer.addUpdateObserver { (histogram) -> Void in self.asyncChanges({ () -> Void in self.minRangeLabel.stringValue = String(format: "%2.3f", self.mainFilter.rangeSolver.minimum.z) self.maxRangeLabel.stringValue = String(format: "%2.3f", self.mainFilter.rangeSolver.maximum.z) }) } mainFilter.addDestinationObserver { (destination) -> Void in self.asyncChanges({ () -> Void in if var c = self.mainFilter.awbFilter.dominantColor { c *= 255 self.dominantColorLabel.stringValue = String(format: "%3.0f,%3.0f,%3.0f:%3.0f", c.x, c.y, c.z, c.w) } }) } scrollView.drawsBackground = false scrollView.documentView = imageView scrollView.allowsMagnification = true scrollView.acceptsTouchEvents = true NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(ViewController.magnifyChanged(_:)), name: NSScrollViewWillStartLiveMagnifyNotification, object: nil) IMPDocument.sharedInstance.addDocumentObserver { (file, type) -> Void in if type == .Image { do{ self.imageView.filter?.source = try IMPJpegProvider(context: self.imageView.context, file: file) self.asyncChanges({ () -> Void in self.zoomOne() }) } catch let error as NSError { self.asyncChanges({ () -> Void in let alert = NSAlert(error: error) alert.runModal() }) } } else if type == .LUT { do { var description = IMPImageProvider.LutDescription() let lutProvider = try IMPImageProvider(context: self.mainFilter.context, cubeFile: file, description: &description) if let lut = self.lutFilter{ lut.update(lutProvider, description:description) } else{ self.lutFilter = IMPLutFilter(context: self.mainFilter.context, lut: lutProvider, description: description) } self.mainFilter.addFilter(self.lutFilter!) } catch let error as NSError { self.asyncChanges({ () -> Void in let alert = NSAlert(error: error) alert.runModal() }) } } } IMPMenuHandler.sharedInstance.addMenuObserver { (item) -> Void in if let tag = IMPMenuTag(rawValue: item.tag) { switch tag { case .zoomOne: self.zoomOne() case .zoom100: self.zoom100() case .resetLut: if let l = self.lutFilter { self.mainFilter.removeFilter(l) } break } } } } @objc func magnifyChanged(event:NSNotification){ is100 = false } var is100 = false private func zoomOne(){ is100 = false asyncChanges { () -> Void in self.scrollView.magnifyToFitRect(self.scrollView.bounds) } } private func zoom100(){ is100 = true asyncChanges { () -> Void in self.scrollView.magnifyToFitRect(self.imageView.bounds) } } override func viewDidAppear() { super.viewDidAppear() self.zoom100() } override func viewDidLayout() { super.viewDidLayout() if is100 { self.zoom100() } } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
mit
84701508f3d6205e5385eb55bb94cd77
33.327731
135
0.561444
5.077688
false
false
false
false
manfengjun/KYMart
Section/Mine/Controller/KYAddAddressViewController.swift
1
8035
// // KYAddAddressViewController.swift // KYMart // // Created by Jun on 2017/6/15. // Copyright © 2017年 JUN. All rights reserved. // import UIKit class KYAddAddressViewController: BaseViewController { @IBOutlet weak var saveBtn: UIButton! @IBOutlet weak var delBtn: UIButton! @IBOutlet weak var addressAreaL: UILabel! @IBOutlet weak var nameT: UITextField! @IBOutlet weak var addressT: UITextField! @IBOutlet weak var phoneT: UITextField! @IBOutlet weak var codeT: UITextField! @IBOutlet weak var defaultIV: UIImageView! var SaveResultClosure: BackClosure? // 闭包 fileprivate var params:[String:AnyObject]! fileprivate lazy var bgView : UIView = { let bgView = UIView(frame: UIScreen.main.bounds) bgView.backgroundColor = UIColor.rgbColor(r: 0, g: 0, b: 0, a: 0.3) let tap = UITapGestureRecognizer(target: self, action: #selector(hide)) tap.delegate = self bgView.addGestureRecognizer(tap) return bgView }() /// 默认选中 var isDefault:Bool = false var isEdit:Bool = false /// 编辑状态下数据 var model:KYAddressModel? func getAddressName(id:Int) -> String { if let array = CitiesDataTool.sharedManager().queryData(with: id) { if array.count > 0 { return array[0] as! String + " " } } return " " } override func viewDidLoad() { super.viewDidLoad() setBackButtonInNav() navigationItem.title = "添加地址" saveBtn.layer.masksToBounds = true saveBtn.layer.cornerRadius = 5 delBtn.isHidden = !isEdit if isEdit { reloadData() } // Do any additional setup after loading the view. } func reloadData() { if let text = model?.consignee { nameT.text = text } if let text = model?.mobile { phoneT.text = "\(text)" } var addressStr = "" if let provice = model?.province { addressStr += getAddressName(id: provice) params = ["province":String(provice) as AnyObject] if let city = model?.city{ addressStr += getAddressName(id: city) params?["city"] = String(city) as AnyObject if let district = model?.district { addressStr += getAddressName(id: district) params?["district"] = String(district) as AnyObject if let twon = model?.twon { addressStr += getAddressName(id: twon) params?["twon"] = String(twon) as AnyObject addressAreaL.text = addressStr } } } } if let address_id = model?.address_id { params["address_id"] = String(address_id) as AnyObject } if let address = model?.address { addressT.text = address } if let zipcode = model?.zipcode { codeT.text = zipcode } if let is_default = model?.is_default { isDefault = is_default == 1 ? true : false defaultIV.image = (is_default == 1 ? UIImage(named: "cart_select_yes") : UIImage(named: "cart_select_no")) } } @IBAction func delAction(_ sender: UIButton) { if let address_id = model?.address_id { SJBRequestModel.push_fetchAddressDelData(params: ["id":String(address_id) as AnyObject]) { (response, status) in if status == 1{ self.Toast(content: "删除地址成功") self.navigationController?.popViewController(animated: true) } else { self.Toast(content: response as! String) } } } else { self.Toast(content: "删除失败") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - 按钮事件 extension KYAddAddressViewController { func saveResult(_ finished: @escaping BackClosure) { SaveResultClosure = finished } /// 保存 /// /// - Parameter sender: sender description @IBAction func saveAction(_ sender: UIButton) { if (nameT.text?.isEmpty)! { Toast(content: "收货人不能为空") return } if (addressAreaL.text?.isEmpty)! { Toast(content: "所在地区不能为空") return } if (addressT.text?.isEmpty)! { Toast(content: "详细地址不能为空") return } if (phoneT.text?.isEmpty)! { Toast(content: "手机号不能为空") return } if (codeT.text?.isEmpty)! { Toast(content: "邮政编码不能为空") return } if let text = SingleManager.instance.loginInfo?.user_id { params?["user_id"] = text as AnyObject params?["consignee"] = nameT.text as AnyObject params?["mobile"] = phoneT.text as AnyObject params?["address"] = addressT.text as AnyObject params?["zipcode"] = codeT.text as AnyObject params?["is_default"] = (isDefault ? "1" : "0") as AnyObject if isEdit { if let address_id = model?.address_id { params["address_id"] = String(address_id) as AnyObject } } if let dic = params { SJBRequestModel.push_fetchAddAddressData(params: dic) { (response, status) in if status == 1{ self.Toast(content: "保存地址成功") self.SaveResultClosure?() self.navigationController?.popViewController(animated: true) } else { self.Toast(content: response as! String) } } } else{ self.Toast(content: "保存地址失败") } } else { Toast(content: "未登录") } } /// 是否设置为默认 /// /// - Parameter sender: sender description @IBAction func setDafaultAction(_ sender: UITapGestureRecognizer) { defaultIV.image = isDefault ? UIImage(named: "cart_select_no") : UIImage(named: "cart_select_yes") isDefault = isDefault ? false : true } /// 地址选择器 /// /// - Parameter sender: sender description @IBAction func selectAddress(_ sender: UITapGestureRecognizer) { let chooseView = ChooseLocationView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - 300, width: SCREEN_WIDTH, height: 300)) chooseView.chooseFinish = {(result,address) in if let dic = result { self.params = dic as? [String:AnyObject] } if let text = address { self.addressAreaL.text = text } self.bgView.removeFromSuperview() } bgView.addSubview(chooseView) UIApplication.shared.keyWindow?.addSubview(bgView) } /// 显示隐藏侧滑菜单 func hide() { bgView.removeFromSuperview() } } extension KYAddAddressViewController:UIGestureRecognizerDelegate { /// 解决手势冲突 /// /// - Parameters: /// - gestureRecognizer: gestureRecognizer description /// - touch: touch description /// - Returns: return value description func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if (touch.view?.isEqual(bgView))! { return true } return false } }
mit
ae3eb2c494c3a0baceb667f9b021127e
31.533333
124
0.536117
4.740741
false
false
false
false
uasys/swift
test/decl/protocol/protocols.swift
1
18309
// RUN: %target-typecheck-verify-swift protocol EmptyProtocol { } protocol DefinitionsInProtocols { init() {} // expected-error {{protocol initializers may not have bodies}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } // Protocol decl. protocol Test { func setTitle(_: String) func erase() -> Bool var creator: String { get } var major : Int { get } var minor : Int { get } var subminor : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} static var staticProperty: Int // expected-error{{property in protocol must have explicit { get } or { get set } specifier}} } protocol Test2 { var property: Int { get } var title: String = "The Art of War" { get } // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} static var title2: String = "The Art of War" // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} associatedtype mytype associatedtype mybadtype = Int associatedtype V : Test = // expected-error {{expected type in associated type declaration}} {{28-28= <#type#>}} } func test1() { var v1: Test var s: String v1.setTitle(s) v1.creator = "Me" // expected-error {{cannot assign to property: 'creator' is a get-only property}} } protocol Bogus : Int {} // expected-error@-1{{inheritance from non-protocol type 'Int'}} // expected-error@-2{{type 'Self' constrained to non-protocol, non-class type 'Int'}} // Explicit conformance checks (successful). protocol CustomStringConvertible { func print() } // expected-note{{protocol requires function 'print()' with type '() -> ()'}} expected-note{{protocol requires}} expected-note{{protocol requires}} expected-note{{protocol requires}} struct TestFormat { } protocol FormattedPrintable : CustomStringConvertible { func print(format: TestFormat) } struct X0 : Any, CustomStringConvertible { func print() {} } class X1 : Any, CustomStringConvertible { func print() {} } enum X2 : Any { } extension X2 : CustomStringConvertible { func print() {} } // Explicit conformance checks (unsuccessful) struct NotPrintableS : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableS' does not conform to protocol 'CustomStringConvertible'}} class NotPrintableC : CustomStringConvertible, Any {} // expected-error{{type 'NotPrintableC' does not conform to protocol 'CustomStringConvertible'}} enum NotPrintableO : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableO' does not conform to protocol 'CustomStringConvertible'}} struct NotFormattedPrintable : FormattedPrintable { // expected-error{{type 'NotFormattedPrintable' does not conform to protocol 'CustomStringConvertible'}} func print(format: TestFormat) {} // expected-note{{candidate has non-matching type '(TestFormat) -> ()'}} } // Protocol compositions in inheritance clauses protocol Left { func l() // expected-note {{protocol requires function 'l()' with type '() -> ()'; do you want to add a stub?}} } protocol Right { func r() // expected-note {{protocol requires function 'r()' with type '() -> ()'; do you want to add a stub?}} } typealias Both = Left & Right protocol Up : Both { func u() } struct DoesNotConform : Up { // expected-error@-1 {{type 'DoesNotConform' does not conform to protocol 'Left'}} // expected-error@-2 {{type 'DoesNotConform' does not conform to protocol 'Right'}} func u() {} } // Circular protocols protocol CircleMiddle : CircleStart { func circle_middle() } // expected-error 2 {{circular protocol inheritance CircleMiddle}} // expected-error@-1{{circular protocol inheritance 'CircleMiddle' -> 'CircleStart' -> 'CircleEnd' -> 'CircleMiddle'}} // expected-error @+1 {{circular protocol inheritance CircleStart}} protocol CircleStart : CircleEnd { func circle_start() } // expected-error 2{{circular protocol inheritance CircleStart}} // expected-note@-1{{protocol 'CircleStart' declared here}} protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note{{protocol 'CircleEnd' declared here}} protocol CircleEntry : CircleTrivial { } protocol CircleTrivial : CircleTrivial { } // expected-error 2{{circular protocol inheritance CircleTrivial}} struct Circle { func circle_start() {} func circle_middle() {} func circle_end() {} } func testCircular(_ circle: Circle) { // FIXME: It would be nice if this failure were suppressed because the protocols // have circular definitions. _ = circle as CircleStart // expected-error{{'Circle' is not convertible to 'CircleStart'; did you mean to use 'as!' to force downcast?}} {{14-16=as!}} } // <rdar://problem/14750346> protocol Q : C, H { } protocol C : E { } protocol H : E { } protocol E { } //===----------------------------------------------------------------------===// // Associated types //===----------------------------------------------------------------------===// protocol SimpleAssoc { associatedtype Associated // expected-note{{protocol requires nested type 'Associated'}} } struct IsSimpleAssoc : SimpleAssoc { struct Associated {} } struct IsNotSimpleAssoc : SimpleAssoc {} // expected-error{{type 'IsNotSimpleAssoc' does not conform to protocol 'SimpleAssoc'}} protocol StreamWithAssoc { associatedtype Element func get() -> Element // expected-note{{protocol requires function 'get()' with type '() -> NotAStreamType.Element'}} } struct AnRange<Int> : StreamWithAssoc { typealias Element = Int func get() -> Int {} } // Okay: Word is a typealias for Int struct AWordStreamType : StreamWithAssoc { typealias Element = Int func get() -> Int {} } struct NotAStreamType : StreamWithAssoc { // expected-error{{type 'NotAStreamType' does not conform to protocol 'StreamWithAssoc'}} typealias Element = Float func get() -> Int {} // expected-note{{candidate has non-matching type '() -> Int'}} } // Okay: Infers Element == Int struct StreamTypeWithInferredAssociatedTypes : StreamWithAssoc { func get() -> Int {} } protocol SequenceViaStream { associatedtype SequenceStreamTypeType : IteratorProtocol // expected-note{{protocol requires nested type 'SequenceStreamTypeType'}} func makeIterator() -> SequenceStreamTypeType } struct IntIterator : IteratorProtocol /*, Sequence, ReplPrintable*/ { typealias Element = Int var min : Int var max : Int var stride : Int mutating func next() -> Int? { if min >= max { return .none } let prev = min min += stride return prev } typealias Generator = IntIterator func makeIterator() -> IntIterator { return self } } extension IntIterator : SequenceViaStream { typealias SequenceStreamTypeType = IntIterator } struct NotSequence : SequenceViaStream { // expected-error{{type 'NotSequence' does not conform to protocol 'SequenceViaStream'}} typealias SequenceStreamTypeType = Int // expected-note{{possibly intended match 'NotSequence.SequenceStreamTypeType' (aka 'Int') does not conform to 'IteratorProtocol'}} func makeIterator() -> Int {} } protocol GetATuple { associatedtype Tuple func getATuple() -> Tuple } struct IntStringGetter : GetATuple { typealias Tuple = (i: Int, s: String) func getATuple() -> Tuple {} } protocol ClassConstrainedAssocType { associatedtype T : class // expected-error@-1 {{'class' constraint can only appear on protocol declarations}} // expected-note@-2 {{did you mean to write an 'AnyObject' constraint?}}{{22-27=AnyObject}} } //===----------------------------------------------------------------------===// // Default arguments //===----------------------------------------------------------------------===// // FIXME: Actually make use of default arguments, check substitutions, etc. protocol ProtoWithDefaultArg { func increment(_ value: Int = 1) // expected-error{{default argument not permitted in a protocol method}} } struct HasNoDefaultArg : ProtoWithDefaultArg { func increment(_: Int) {} } //===----------------------------------------------------------------------===// // Variadic function requirements //===----------------------------------------------------------------------===// protocol IntMaxable { func intmax(first: Int, rest: Int...) -> Int // expected-note 2{{protocol requires function 'intmax(first:rest:)' with type '(Int, Int...) -> Int'}} } struct HasIntMax : IntMaxable { func intmax(first: Int, rest: Int...) -> Int {} } struct NotIntMax1 : IntMaxable { // expected-error{{type 'NotIntMax1' does not conform to protocol 'IntMaxable'}} func intmax(first: Int, rest: [Int]) -> Int {} // expected-note{{candidate has non-matching type '(Int, [Int]) -> Int'}} } struct NotIntMax2 : IntMaxable { // expected-error{{type 'NotIntMax2' does not conform to protocol 'IntMaxable'}} func intmax(first: Int, rest: Int) -> Int {} // expected-note{{candidate has non-matching type '(Int, Int) -> Int'}} } //===----------------------------------------------------------------------===// // 'Self' type //===----------------------------------------------------------------------===// protocol IsEqualComparable { func isEqual(other: Self) -> Bool // expected-note{{protocol requires function 'isEqual(other:)' with type '(WrongIsEqual) -> Bool'}} } struct HasIsEqual : IsEqualComparable { func isEqual(other: HasIsEqual) -> Bool {} } struct WrongIsEqual : IsEqualComparable { // expected-error{{type 'WrongIsEqual' does not conform to protocol 'IsEqualComparable'}} func isEqual(other: Int) -> Bool {} // expected-note{{candidate has non-matching type '(Int) -> Bool'}} } //===----------------------------------------------------------------------===// // Using values of existential type. //===----------------------------------------------------------------------===// func existentialSequence(_ e: Sequence) { // expected-error{{has Self or associated type requirements}} // FIXME: Weird diagnostic var x = e.makeIterator() // expected-error{{'Sequence' is not convertible to 'Sequence.Iterator'}} x.next() x.nonexistent() } protocol HasSequenceAndStream { associatedtype R : IteratorProtocol, Sequence func getR() -> R } func existentialSequenceAndStreamType(_ h: HasSequenceAndStream) { // expected-error{{has Self or associated type requirements}} // FIXME: Crummy diagnostics. var x = h.getR() // expected-error{{member 'getR' cannot be used on value of protocol type 'HasSequenceAndStream'; use a generic constraint instead}} x.makeIterator() x.next() x.nonexistent() } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol IntIntSubscriptable { subscript (i: Int) -> Int { get } } protocol IntSubscriptable { associatedtype Element subscript (i: Int) -> Element { get } } struct DictionaryIntInt { subscript (i: Int) -> Int { get { return i } } } func testSubscripting(_ iis: IntIntSubscriptable, i_s: IntSubscriptable) { // expected-error{{has Self or associated type requirements}} var i: Int = iis[17] var i2 = i_s[17] // expected-error{{member 'subscript' cannot be used on value of protocol type 'IntSubscriptable'; use a generic constraint instead}} } //===----------------------------------------------------------------------===// // Static methods //===----------------------------------------------------------------------===// protocol StaticP { static func f() } protocol InstanceP { func f() // expected-note{{protocol requires function 'f()' with type '() -> ()'}} } struct StaticS1 : StaticP { static func f() {} } struct StaticS2 : InstanceP { // expected-error{{type 'StaticS2' does not conform to protocol 'InstanceP'}} static func f() {} // expected-note{{candidate operates on a type, not an instance as required}} } struct StaticAndInstanceS : InstanceP { static func f() {} func f() {} } func StaticProtocolFunc() { let a: StaticP = StaticS1() a.f() // expected-error{{static member 'f' cannot be used on instance of type 'StaticP'}} } func StaticProtocolGenericFunc<t : StaticP>(_: t) { t.f() } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Eq { static func ==(lhs: Self, rhs: Self) -> Bool } extension Int : Eq { } // Matching prefix/postfix. prefix operator <> postfix operator <> protocol IndexValue { static prefix func <> (_ max: Self) -> Int static postfix func <> (min: Self) -> Int } prefix func <> (max: Int) -> Int { return 0 } postfix func <> (min: Int) -> Int { return 0 } extension Int : IndexValue {} //===----------------------------------------------------------------------===// // Class protocols //===----------------------------------------------------------------------===// protocol IntrusiveListNode : class { var next : Self { get } } final class ClassNode : IntrusiveListNode { var next : ClassNode = ClassNode() } struct StructNode : IntrusiveListNode { // expected-error{{non-class type 'StructNode' cannot conform to class protocol 'IntrusiveListNode'}} var next : StructNode // expected-error {{value type 'StructNode' cannot have a stored property that recursively contains it}} } final class ClassNodeByExtension { } struct StructNodeByExtension { } extension ClassNodeByExtension : IntrusiveListNode { var next : ClassNodeByExtension { get { return self } set {} } } extension StructNodeByExtension : IntrusiveListNode { // expected-error{{non-class type 'StructNodeByExtension' cannot conform to class protocol 'IntrusiveListNode'}} var next : StructNodeByExtension { get { return self } set {} } } final class GenericClassNode<T> : IntrusiveListNode { var next : GenericClassNode<T> = GenericClassNode() } struct GenericStructNode<T> : IntrusiveListNode { // expected-error{{non-class type 'GenericStructNode<T>' cannot conform to class protocol 'IntrusiveListNode'}} var next : GenericStructNode<T> // expected-error {{value type 'GenericStructNode<T>' cannot have a stored property that recursively contains it}} } // Refined protocols inherit class-ness protocol IntrusiveDListNode : IntrusiveListNode { var prev : Self { get } } final class ClassDNode : IntrusiveDListNode { var prev : ClassDNode = ClassDNode() var next : ClassDNode = ClassDNode() } struct StructDNode : IntrusiveDListNode { // expected-error{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveDListNode'}} // expected-error@-1{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveListNode'}} var prev : StructDNode // expected-error {{value type 'StructDNode' cannot have a stored property that recursively contains it}} var next : StructDNode } @objc protocol ObjCProtocol { func foo() // expected-note{{protocol requires function 'foo()' with type '() -> ()'}} } protocol NonObjCProtocol : class { //expected-note{{protocol 'NonObjCProtocol' declared here}} func bar() } class DoesntConformToObjCProtocol : ObjCProtocol { // expected-error{{type 'DoesntConformToObjCProtocol' does not conform to protocol 'ObjCProtocol'}} } @objc protocol ObjCProtocolRefinement : ObjCProtocol { } @objc protocol ObjCNonObjCProtocolRefinement : NonObjCProtocol { } //expected-error{{@objc protocol 'ObjCNonObjCProtocolRefinement' cannot refine non-@objc protocol 'NonObjCProtocol'}} // <rdar://problem/16079878> protocol P1 { associatedtype Assoc // expected-note 2{{protocol requires nested type 'Assoc'}} } protocol P2 { } struct X3<T : P1> where T.Assoc : P2 {} struct X4 : P1 { // expected-error{{type 'X4' does not conform to protocol 'P1'}} func getX1() -> X3<X4> { return X3() } } protocol ShouldntCrash { // rdar://16109996 let fullName: String { get } // expected-error {{'let' declarations cannot be computed properties}} {{3-6=var}} // <rdar://problem/17200672> Let in protocol causes unclear errors and crashes let fullName2: String // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} // <rdar://problem/16789886> Assert on protocol property requirement without a type var propertyWithoutType { get } // expected-error {{type annotation missing in pattern}} // expected-error@-1 {{computed property must have an explicit type}} {{26-26=: <# Type #>}} } // rdar://problem/18168866 protocol FirstProtocol { weak var delegate : SecondProtocol? { get } // expected-error{{'weak' may not be applied to non-class-bound 'SecondProtocol'; consider adding a protocol conformance that has a class bound}} } protocol SecondProtocol { func aMethod(_ object : FirstProtocol) } // <rdar://problem/19495341> Can't upcast to parent types of type constraints without forcing class C1 : P2 {} func f<T : C1>(_ x : T) { _ = x as P2 } class C2 {} func g<T : C2>(_ x : T) { x as P2 // expected-error{{'T' is not convertible to 'P2'; did you mean to use 'as!' to force downcast?}} {{5-7=as!}} } class C3 : P1 {} // expected-error{{type 'C3' does not conform to protocol 'P1'}} func h<T : C3>(_ x : T) { _ = x as P1 // expected-error{{protocol 'P1' can only be used as a generic constraint because it has Self or associated type requirements}} } protocol P4 { associatedtype T // expected-note {{protocol requires nested type 'T'}} } class C4 : P4 { // expected-error {{type 'C4' does not conform to protocol 'P4'}} associatedtype T = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}} {{3-17=typealias}} } // <rdar://problem/25185722> Crash with invalid 'let' property in protocol protocol LetThereBeCrash { let x: Int // expected-error@-1 {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} // expected-note@-2 {{change 'let' to 'var' to make it mutable}} } extension LetThereBeCrash { init() { x = 1 } // expected-error@-1 {{cannot assign to property: 'x' is a 'let' constant}} }
apache-2.0
b991aaf4b9f7725f2852b59f6a00ec2c
34.759766
232
0.653831
4.469971
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/src/Util/ParamParser.swift
1
4150
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation // A DSL for parsing expected and optional values from a Dictionary, appropriate for // validating a service response. // // Additionally it includes some helpers to DRY up common conversions. // // Rather than exhaustively enumerate accessors for types like `requireUInt32`, `requireInt64`, etc. // We instead leverage generics at the call site. // // do { // // Required // let name: String = try paramParser.required(key: "name") // let count: UInt32 = try paramParser.required(key: "count") // // // Optional // let last_seen: Date? = try paramParser.optional(key: "last_seen") // // return Foo(name: name, count: count, isNew: lastSeen == nil) // } catch { // handleInvalidResponse(error: error) // } // public class ParamParser { public typealias Key = AnyHashable let dictionary: Dictionary<Key, Any> public init(dictionary: Dictionary<Key, Any>) { self.dictionary = dictionary } public convenience init?(responseObject: Any?) { guard let responseDict = responseObject as? [String: AnyObject] else { return nil } self.init(dictionary: responseDict) } // MARK: Errors public enum ParseError: Error, CustomStringConvertible { case missingField(Key) case invalidFormat(Key) public var description: String { switch self { case .missingField(let key): return "ParseError: missing field for \(key)" case .invalidFormat(let key): return "ParseError: invalid format for \(key)" } } } private func invalid(key: Key) -> ParseError { return ParseError.invalidFormat(key) } private func missing(key: Key) -> ParseError { return ParseError.missingField(key) } // MARK: - Public API public func required<T>(key: Key) throws -> T { guard let value: T = try optional(key: key) else { throw missing(key: key) } return value } public func optional<T>(key: Key) throws -> T? { guard let someValue = dictionary[key] else { return nil } guard !(someValue is NSNull) else { return nil } guard let typedValue = someValue as? T else { throw invalid(key: key) } return typedValue } // MARK: FixedWidthIntegers (e.g. Int, Int32, UInt, UInt32, etc.) // You can't blindly cast accross Integer types, so we need to specify and validate which Int type we want. // In general, you'll find numeric types parsed into a Dictionary as `Int`. public func required<T>(key: Key) throws -> T where T: FixedWidthInteger { guard let value: T = try optional(key: key) else { throw missing(key: key) } return value } public func optional<T>(key: Key) throws -> T? where T: FixedWidthInteger { guard let someValue: Any = try optional(key: key) else { return nil } switch someValue { case let typedValue as T: return typedValue case let int as Int: guard int >= T.min, int <= T.max else { throw invalid(key: key) } return T(int) default: throw invalid(key: key) } } // MARK: Base64 Data public func requiredBase64EncodedData(key: Key) throws -> Data { guard let data: Data = try optionalBase64EncodedData(key: key) else { throw ParseError.missingField(key) } return data } public func optionalBase64EncodedData(key: Key) throws -> Data? { guard let encodedData: String = try self.optional(key: key) else { return nil } guard let data = Data(base64Encoded: encodedData) else { throw ParseError.invalidFormat(key) } guard data.count > 0 else { return nil } return data } }
gpl-3.0
6aadf029b457445478fb29a3d42ec541
26.483444
111
0.586506
4.438503
false
false
false
false
edragoev1/pdfjet
Sources/Example_05/main.swift
1
2661
import Foundation import PDFjet /** * Example_05.swift * */ public class Example_05 { public init() { if let stream = OutputStream(toFileAtPath: "Example_05.pdf", append: false) { let pdf = PDF(stream) let f1 = Font(pdf, CoreFont.HELVETICA_BOLD) f1.setItalic(true) let page = Page(pdf, Letter.PORTRAIT) var text = TextLine(f1).setLocation(300.0, 300.0) var i = 0 while i < 360 { text.setTextDirection(i) text.setUnderline(true) // text.setStrikeLine(true) text.setText(" Hello, World -- \(i) degrees.") text.drawOn(page) i += 15 } text = TextLine(f1, "WAVE AWAY") text.setLocation(70.0, 50.0) text.drawOn(page) f1.setKernPairs(true) text = TextLine(f1, "WAVE AWAY") text.setLocation(70.0, 70.0) text.drawOn(page) f1.setKernPairs(false) text = TextLine(f1, "WAVE AWAY") text.setLocation(70.0, 90.0) text.drawOn(page) f1.setSize(8.0) text = TextLine(f1, "-- font.setKernPairs(false);") text.setLocation(150.0, 50.0) text.drawOn(page) text.setLocation(150.0, 90.0) text.drawOn(page) text = TextLine(f1, "-- font.setKernPairs(true);") text.setLocation(150.0, 70.0) text.drawOn(page) Point(300.0, 300.0) .setShape(Point.CIRCLE) .setFillShape(true) .setColor(Color.blue) .setRadius(37.0) .drawOn(page) Point(300.0, 300.0) .setShape(Point.CIRCLE) .setFillShape(true) .setColor(Color.white) .setRadius(25.0) .drawOn(page) page.setPenWidth(1.0) page.drawEllipse(300.0, 600.0, 100.0, 50.0) f1.setSize(14.0) let unicode = "\u{20AC}\u{0020}\u{201A}\u{0192}\u{201E}\u{2026}\u{2020}\u{2021}\u{02C6}\u{2030}\u{0160}" text = TextLine(f1, unicode) text.setLocation(100.0, 700.0) text.drawOn(page) pdf.complete() } } } // End of Example_05.swift let time0 = Int64(Date().timeIntervalSince1970 * 1000) _ = Example_05() let time1 = Int64(Date().timeIntervalSince1970 * 1000) print("Example_05 => \(time1 - time0)")
mit
55a9249c4c655d07a67f402954878d93
28.566667
116
0.480646
3.790598
false
false
false
false
QuaereVeritatem/TopHackIncStartup
TopHackIncStartUp/RegisterViewController.swift
1
6082
// // RegisterViewController.swift // TopHackIncStartup // // Created on 9/4/16. // import UIKit class RegisterViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var passwordConfirmTextField: UITextField! @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var registerBtn: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! let backendless = Backendless.sharedInstance()! override func viewDidLoad() { super.viewDidLoad() emailTextField.addTarget(self, action: #selector(LoginViewController.textFieldChanged(textField:)), for: UIControlEvents.editingChanged) passwordTextField.addTarget(self, action: #selector(LoginViewController.textFieldChanged(textField:)), for: UIControlEvents.editingChanged) passwordConfirmTextField.addTarget(self, action: #selector(LoginViewController.textFieldChanged(textField:)), for: UIControlEvents.editingChanged) emailTextField.layer.cornerRadius = 5 passwordTextField.layer.cornerRadius = 5 passwordConfirmTextField.layer.cornerRadius = 5 registerBtn.layer.cornerRadius = 5 cancelButton.layer.cornerRadius = 5 NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } func keyboardWillShow(notification: NSNotification) { adjustingHeight(show: true, notification: notification) } func keyboardWillHide(notification: NSNotification) { adjustingHeight(show: false, notification: notification) } //this is getting extra calls between textfields, making it go higher on screen func adjustingHeight(show:Bool, notification:NSNotification) { // 1 Get notification information in an dictionary var userInfo = notification.userInfo! // 2 From information dictionary get keyboard’s size let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue // 3 Get the time required for keyboard pop up animation let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval // 4 Extract height of keyboard & add little space(40) between keyboard & text field. If bool is true then height is multiplied by 1 & if its false then height is multiplied by –1. This is short hand of if else statement. See complete list of short hand here. let changeInHeight = (keyboardFrame.height - 360) * (show ? 1 : -1) //5 Animation moving constraint at same speed of moving keyboard & change bottom constraint accordingly. UIView.animate(withDuration: animationDurarion, animations: { () -> Void in self.bottomConstraint.constant += changeInHeight }) } // this function is the reason why the first option in pickerview isnt selctable-FIX IT! func textFieldChanged(textField: UITextField) { if emailTextField.text == "" || passwordTextField.text == "" || passwordConfirmTextField.text == "" { registerBtn.isEnabled = false } else { registerBtn.isEnabled = true } } @IBAction func register(_ sender: UIButton) { if passwordTextField.text != passwordConfirmTextField.text { Utility.showAlert(viewController: self, title: "Registration Error", message: "Password confirmation failed. Plase enter your password try again.") return } if !Utility.isValidEmail(emailAddress: emailTextField.text!) { Utility.showAlert(viewController: self, title: "Registration Error", message: "Please enter a valid email address.") return } spinner.startAnimating() let email = emailTextField.text! let password = passwordTextField.text! BackendlessManager.sharedInstance.registerUser(email: email, password: password, completion: { BackendlessManager.sharedInstance.loginUser(email: email, password: password, completion: { self.spinner.stopAnimating() //heres where we load local database into backendless self.performSegue(withIdentifier: "gotoMenuFromRegister", sender: sender) }, error: { message in self.spinner.stopAnimating() Utility.showAlert(viewController: self, title: "Login Error", message: message) }) }, error: { message in self.spinner.stopAnimating() Utility.showAlert(viewController: self, title: "Register Error", message: message) }) } @IBAction func cancel(_ sender: UIButton) { spinner.stopAnimating() dismiss(animated: true, completion: nil) } }
mit
76fc358f88b4ff33a4a188e8642b8243
40.067568
267
0.641987
5.918208
false
false
false
false
vlfm/VFAppSecurityLockWindow
VFAppSecurityLockWindowDemo/VFAppSecurityLockWindowDemo/security/LockViewController.swift
1
943
import UIKit @objc class LockViewController: UIViewController { typealias LockViewControllerAction = (sender: LockViewController) -> () var unlockAction: LockViewControllerAction? @IBOutlet var passcodeTextField: UITextField! @IBOutlet var unlockButton: UIButton! override func viewDidLoad() { super.viewDidLoad() title = "Lock" setUnlockUiVisible(false) } func setUnlockUiVisible(isVisible: Bool) { passcodeTextField.hidden = !isVisible unlockButton.hidden = !isVisible } @IBAction func unlockButtonTap(sender: AnyObject) { unlockAction?(sender: self) } @IBAction func alertViewButtonTap(sender: AnyObject) { var alertView = UIAlertView(title: "UIAlertView", message: nil, delegate: nil, cancelButtonTitle: "Close") alertView.show() } deinit { NSLog("LockViewController deinit") } }
apache-2.0
1c383f9cd15cb9ed23cc47737cb4c9a8
26.764706
114
0.661718
5.097297
false
false
false
false
bitserf/OAuth2
OAuth2/NSURLRequest+Extensions.swift
1
1211
// // OAuth2 // Copyright (C) 2015 Leon Breedt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation extension NSURLRequest { func dumpHeadersAndBody() -> String { var result = "\(HTTPMethod!) \(URL!)\n" if let headers = allHTTPHeaderFields { for (name, value) in headers { result += "\(name): \(value)\n" } } if let bodyData = HTTPBody { if let bodyString = NSString(data: bodyData, encoding: NSUTF8StringEncoding) { result += "\n\(bodyString)\n" } else { result += "\n<\(bodyData.length) byte(s)>\n" } } return result } }
apache-2.0
a41700162bf3619ad26a619bad211022
31.72973
90
0.616846
4.356115
false
false
false
false
IT-Department-Projects/POP-II
iOS App/MapViewController.swift
1
6310
// // MapViewController.swift // notesNearby_iOS_final // // Created by Aiman Abdullah Anees on 11/03/17. // Copyright © 2017 Aiman Abdullah Anees. All rights reserved. // import UIKit import MapKit import CoreLocation import Firebase import FirebaseDatabase import FirebaseStorage import SVProgressHUD struct Firebasepull { let title1 : String! let note : String! let latitude : Double! let longitude : Double! let image_url : String! let key: String! } class MapViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet var open: UIBarButtonItem! @IBOutlet var Post: UILabel! @IBOutlet var AR: UILabel! var posts = [Firebasepull]() var imageURLS=[String]() let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() //Custom Appearance AR.layer.cornerRadius = AR.frame.size.width/2 AR.clipsToBounds=true AR.layer.borderColor = UIColor.darkGray.cgColor AR.layer.borderWidth=0.5 Post.layer.cornerRadius = Post.frame.size.width/2 Post.clipsToBounds=true Post.layer.borderColor = UIColor.darkGray.cgColor Post.layer.borderWidth=0.5 //Side-Panel Code open.target=revealViewController() open.action=Selector("revealToggle:") self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) //Map-Operations self.locationManager.delegate = self self.mapView.delegate=self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() self.mapView.showsUserLocation = true self.mapView.showsBuildings = true self.mapView.showsCompass = true self.mapView.showsScale = true //^^^^^Pushing Points^^^^^ DispatchQueue.global(qos:.background).async { do{ let databaseRef = FIRDatabase.database().reference() databaseRef.child("posts").queryOrderedByKey().observe(.childAdded, with: {(snapshot) in print(snapshot) if let dictionary = snapshot.value as? [String:AnyObject]{ let title1 = dictionary["title"] as? String let note = dictionary["note"] as? String let latitude = dictionary["latitude"] as? Double let longitude = dictionary["longitude"] as? Double let image_url=dictionary["image_url"] as? String let key=dictionary["key"] as? String self.posts.insert(Firebasepull(title1:title1,note:note,latitude:latitude,longitude:longitude,image_url:image_url,key:key), at: 0) } }, withCancel: nil) print("*********") } catch{ print("error") } } } /* func centerMapOnLocation(location:CLLocation){ let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2000, 2000) mapView.setRegion(coordinateRegion, animated: true) } */ func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last let center = CLLocationCoordinate2D(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!) /* let region=MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)) self.mapView.setRegion(region, animated: true) */ var i:Int = 0 while(i < self.posts.count){ let annotation = MKPointAnnotation() let anno_center = CLLocationCoordinate2DMake(self.posts[i].latitude, self.posts[i].longitude) annotation.coordinate = anno_center annotation.title = self.posts[i].title1 annotation.subtitle = self.posts[i].note imageURLS.append(self.posts[i].image_url) mapView.addAnnotation(annotation) i=i+1 } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } else { let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "annotationView") ?? MKAnnotationView() annotationView.image = UIImage(named: "location-map-flat") annotationView.frame.size=CGSize(width: 30.0, height: 30.0) annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) annotationView.canShowCallout = true return annotationView } } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { guard let annotation = view.annotation else { return } let urlString="https://www.google.com/maps?saddr=\(self.mapView.userLocation.coordinate.latitude),\(self.mapView.userLocation.coordinate.longitude)&daddr=\(annotation.coordinate.latitude),\(annotation.coordinate.longitude)" guard let url = URL(string: urlString) else { return } UIApplication.shared.openURL(url) } @IBAction func ARButtonTapped(_ sender: UIButton) { } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } }
mit
aeebc66936b003b724dc6afd09a16a09
30.38806
231
0.584245
5.55859
false
false
false
false
rad182/RADInfoBannerView
Example/RADInfoBannerView/ViewController.swift
1
2102
// // ViewController.swift // RADInfoBannerView // // Created by Royce Dy on 12/23/2015. // Copyright (c) 2015 Royce Dy. All rights reserved. // import UIKit import RADInfoBannerView class ViewController: UIViewController { @IBOutlet weak var navigationBarSwitch: UISwitch! @IBOutlet weak var activityIndicatorSwitch: UISwitch! @IBOutlet weak var messageText: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "didTapView") self.view.addGestureRecognizer(tapGestureRecognizer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Methods func didTapView() { // hide keyboard self.messageText.resignFirstResponder() } // MARK: IBActions @IBAction func navigationBarSwitchValueDidChange() { self.navigationController?.setNavigationBarHidden(!self.navigationBarSwitch.on, animated: true) } @IBAction func didTapShowInfoBannerViewButton() { if let text = self.messageText.text where text.isEmpty == false { RADInfoBannerView.showInfoBannerView(text, showActivityIndicatorView: self.activityIndicatorSwitch.on, hideAfter: 3.0) } } @IBAction func didTapShowCustomInfoBannerViewColorButton() { if let text = self.messageText.text where text.isEmpty == false { let infoBannerView = RADInfoBannerView(text: text, showActivityIndicatorView: self.activityIndicatorSwitch.on) infoBannerView.backgroundColor = .redColor() infoBannerView.textLabel.textColor = .yellowColor() infoBannerView.show().hide(afterDelay: 3.0) } } } extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
5239e3f16bef690f3840f02d1eb93dfe
31.84375
130
0.694577
5.190123
false
false
false
false
qblu/ModelForm
ModelForm/PropertyTypeFormFields/BoolTypFormField.swift
1
2015
// // BoolTypFormField.swift // ModelForm // // Created by Rusty Zarse on 7/28/15. // Copyright (c) 2015 LeVous. All rights reserved. // import UIKit public struct BoolTypeFormField: PropertyTypeFormField { public init(){} public func createFormField(fieldName: String, value: Any) -> UIControl { let field = UISwitch() if let castValue = value as? Bool { field.on = castValue } return field } public func getValueFromFormField(formField: UIControl, forPropertyNamed propertyName: String) -> (validationResult: ModelFormValidationResult, value: Any) { if let field = formField as? UISwitch { let switchIsOn: Bool = field.on return (validationResult: ModelFormValidationResult.validResult(), value: switchIsOn) } else { Logger.logWarning("Unexpected form field type:[\(formField.dynamicType)] sent to BoolTypeFormField.getValueFromFormField()") return (validationResult:ModelFormValidationResult(invalidPropertyName: propertyName, validationMessage: "The form field provided for update was of the wrong type. Expected a UISwitch."), value: false) } } public func updateValue(value: Any, onFormField formField: UIControl, forPropertyNamed name: String) -> ModelFormValidationResult { if let field = formField as? UISwitch, castValue = value as? Bool { field.setOn(castValue, animated: true) return ModelFormValidationResult.validResult() } else { Logger.logWarning("Unexpected form field type:[\(formField.dynamicType)] or value type:[\(value.dynamicType)] sent to BoolTypeFormField.updateValue()") var validationresult = ModelFormValidationResult() validationresult.recordValidationViolation(name, validationMessage: "The form field used for update was not of the correct type. Expected a UISwitch.") return validationresult } } }
mit
7c00c53eae8f88f0d909f2725869cd7b
41.87234
214
0.679404
5.206718
false
false
false
false
thyagostall/ios-playground
MyPlayground.playground/Contents.swift
1
1020
//: Playground - noun: a place where people can play import UIKit /** * Optionals */ func optionalsExplicitAndImplicit() { var explicitOptional: Int? var implicitOptional: Int! implicitOptional = 2 explicitOptional = 5 let explicitSum = 1 + explicitOptional! let implicitSum = 2 + implicitOptional print("This the explicit optional: \(explicitSum)") print("This the implicit optional: \(implicitSum)") } func optionalBinding(name: String?) { if let n = name where n.hasPrefix("T") { print("Howdy, \(n)") } } /** * * Class with a failure initializer * */ class Circle { var radius: Double init?(radius: Double) { self.radius = radius if radius <= 0 { return nil } } func printArea() { let area = 3.1415 * radius * radius print("\(area)") } } var c = Circle(radius: 10) if let circle = c { c?.printArea() } else { print("Circle was not initialized correctly.") }
gpl-2.0
44d124b8a6d99f55555b2bf80facf2e3
17.907407
55
0.593137
4.015748
false
false
false
false
simplyzhao/ForecastIO
ForecastIO/DataPoint.swift
1
4037
// // DataPoint.swift // Weather // // Created by Alex Zhao on 11/25/15. // Copyright © 2015 Alex Zhao. All rights reserved. // import Foundation public enum PrecipType: String { case Rain = "rain" case Snow = "snow" case Sleet = "sleet" case Hail = "hail" } public struct DataPoint { public let time: NSTimeInterval? public let summary: String? public let icon: Icon? public let sunriseTime: NSTimeInterval? public let sunsetTime: NSTimeInterval? public let moonPhase: Double? public let nearestStormDistance: Double? public let nearestStormBearing: Double? public let precipIntensity: Double? public let precipIntensityMax: Double? public let precipIntensityMaxTime: NSTimeInterval? public let precipProbability: Double? public let precipType: PrecipType? public let precipAccumulation: Double? public let temperature: Double? public let temperatureMin: Double? public let temperatureMinTime: NSTimeInterval? public let temperatureMax: Double? public let temperatureMaxTime: NSTimeInterval? public let apparentTemperature: Double? public let apparentTemperatureMin: Double? public let apparentTemperatureMinTime: NSTimeInterval? public let apparentTemperatureMax: Double? public let apparentTemperatureMaxTime: NSTimeInterval? public let dewPoint: Double? public let windSpeed: Double? public let windBearing: Double? public let cloudCover: Double? public let humidity: Double? public let pressure: Double? public let visibility: Double? public let ozone: Double? init(data: [String: AnyObject]) { self.time = data["time"] as? NSTimeInterval self.summary = data["summary"] as? String if let icon = data["icon"] as? String { self.icon = Icon(rawValue: icon) } else { self.icon = nil } self.sunriseTime = data["sunriseTime"] as? NSTimeInterval self.sunsetTime = data["sunsetTime"] as? NSTimeInterval self.moonPhase = data["moonPhase"] as? Double self.nearestStormDistance = data["nearestStormDistance"] as? Double self.nearestStormBearing = data["nearestStormBearing"] as? Double self.precipIntensity = data["precipIntensity"] as? Double self.precipIntensityMax = data["precipIntensityMax"] as? Double self.precipIntensityMaxTime = data["precipIntensityMaxTime"] as? NSTimeInterval self.precipProbability = data["precipProbability"] as? Double if let precipType = data["recipType"] as? String { self.precipType = PrecipType(rawValue: precipType) } else { self.precipType = nil } self.precipAccumulation = data["precipAccumulation"] as? Double self.temperature = data["temperature"] as? Double self.temperatureMin = data["temperatureMin"] as? Double self.temperatureMinTime = data["temperatureMinTime"] as? NSTimeInterval self.temperatureMax = data["temperatureMax"] as? Double self.temperatureMaxTime = data["temperatureMaxTime"] as? NSTimeInterval self.apparentTemperature = data["apparentTemperature"] as? Double self.apparentTemperatureMin = data["apparentTemperatureMin"] as? Double self.apparentTemperatureMinTime = data["apparentTemperatureMinTime"] as? NSTimeInterval self.apparentTemperatureMax = data["apparentTemperatureMax"] as? Double self.apparentTemperatureMaxTime = data["apparentTemperatureMaxTime"] as? NSTimeInterval self.dewPoint = data["dewPoint"] as? Double self.windSpeed = data["windSpeed"] as? Double self.windBearing = data["windBearing"] as? Double self.cloudCover = data["cloudCover"] as? Double self.humidity = data["humidity"] as? Double self.pressure = data["pressure"] as? Double self.visibility = data["visibility"] as? Double self.ozone = data["ozone"] as? Double } }
mit
46a1db85211036c78d2c940d9a69faf1
40.193878
95
0.687314
4.759434
false
false
false
false
irlabs/ActionKit
ActionKit/UIControl+ActionKit.swift
1
17035
// // UIControl+ActionKit.swift // ActionKit // // Created by Kevin Choi, Benjamin Hendricks on 7/17/14. // Licensed under the terms of the MIT license // import Foundation import UIKit public protocol ActionKitControl {} public extension ActionKitControl where Self: UIControl { func addControlEvent(_ controlEvents: UIControl.Event, closureWithControl: @escaping (Self) -> ()) { _addControlEvent(controlEvents, closure: { [weak self] () -> () in guard let strongSelf = self else { return } closureWithControl(strongSelf) }) } func addControlEvent(_ controlEvents: UIControl.Event, closure: @escaping () -> ()) { _addControlEvent(controlEvents, closure: closure) } } extension UIControl: ActionKitControl {} public extension UIControl { fileprivate struct AssociatedKeys { static var ControlTouchDownClosure = 0 static var ControlTouchDownRepeatClosure = 0 static var ControlTouchDragInsideClosure = 0 static var ControlTouchDragOutsideClosure = 0 static var ControlTouchDragEnterClosure = 0 static var ControlTouchDragExitClosure = 0 static var ControlTouchUpInsideClosure = 0 static var ControlTouchUpOutsideClosure = 0 static var ControlTouchCancelClosure = 0 static var ControlValueChangedClosure = 0 static var ControlEditingDidBeginClosure = 0 static var ControlEditingChangedClosure = 0 static var ControlEditingDidEndClosure = 0 static var ControlEditingDidEndOnExitClosure = 0 static var ControlAllTouchEventsClosure = 0 static var ControlAllEditingEventsClosure = 0 static var ControlApplicationReservedClosure = 0 static var ControlSystemReservedClosure = 0 static var ControlAllEventsClosure = 0 } fileprivate func get(_ key: UnsafeRawPointer) -> ActionKitVoidClosure? { return (objc_getAssociatedObject(self, key) as? ActionKitVoidClosureWrapper)?.closure } fileprivate func set(_ key: UnsafeRawPointer, action: ActionKitVoidClosure?) { objc_setAssociatedObject(self, key, ActionKitVoidClosureWrapper(action), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } fileprivate var TouchDownClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchDownClosure) } set { set(&AssociatedKeys.ControlTouchDownClosure, action: newValue)} } fileprivate var TouchDownRepeatClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchDownRepeatClosure) } set { set(&AssociatedKeys.ControlTouchDownRepeatClosure, action: newValue)} } fileprivate var TouchDragInsideClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchDragInsideClosure) } set { set(&AssociatedKeys.ControlTouchDragInsideClosure, action: newValue)} } fileprivate var TouchDragOutsideClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchDragOutsideClosure) } set { set(&AssociatedKeys.ControlTouchDragOutsideClosure, action: newValue)} } fileprivate var TouchDragEnterClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchDragEnterClosure) } set { set(&AssociatedKeys.ControlTouchDragEnterClosure, action: newValue)} } fileprivate var TouchDragExitClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchDragExitClosure) } set { set(&AssociatedKeys.ControlTouchDragExitClosure, action: newValue)} } fileprivate var TouchUpInsideClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchUpInsideClosure) } set { set(&AssociatedKeys.ControlTouchUpInsideClosure, action: newValue)} } fileprivate var TouchUpOutsideClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchUpOutsideClosure) } set { set(&AssociatedKeys.ControlTouchUpOutsideClosure, action: newValue)} } fileprivate var TouchCancelClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlTouchCancelClosure) } set { set(&AssociatedKeys.ControlTouchCancelClosure, action: newValue)} } fileprivate var ValueChangedClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlValueChangedClosure) } set { set(&AssociatedKeys.ControlValueChangedClosure, action: newValue)} } fileprivate var EditingDidBeginClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlEditingDidBeginClosure) } set { set(&AssociatedKeys.ControlEditingDidBeginClosure, action: newValue)} } fileprivate var EditingChangedClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlEditingChangedClosure) } set { set(&AssociatedKeys.ControlEditingChangedClosure, action: newValue)} } fileprivate var EditingDidEndClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlEditingDidEndClosure) } set { set(&AssociatedKeys.ControlEditingDidEndClosure, action: newValue)} } fileprivate var EditingDidEndOnExitClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlEditingDidEndOnExitClosure) } set { set(&AssociatedKeys.ControlEditingDidEndOnExitClosure, action: newValue)} } fileprivate var AllTouchEventsClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlAllTouchEventsClosure) } set { set(&AssociatedKeys.ControlAllTouchEventsClosure, action: newValue)} } fileprivate var AllEditingEventsClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlAllEditingEventsClosure) } set { set(&AssociatedKeys.ControlAllEditingEventsClosure, action: newValue)} } fileprivate var ApplicationReservedClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlApplicationReservedClosure) } set { set(&AssociatedKeys.ControlApplicationReservedClosure, action: newValue)} } fileprivate var SystemReservedClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlSystemReservedClosure) } set { set(&AssociatedKeys.ControlSystemReservedClosure, action: newValue)} } fileprivate var AllEventsClosure: ActionKitVoidClosure? { get { return get(&AssociatedKeys.ControlAllEventsClosure) } set { set(&AssociatedKeys.ControlAllEventsClosure, action: newValue)} } @objc fileprivate func runClosureTouchDown() { TouchDownClosure?() } @objc fileprivate func runClosureTouchDownRepeat() { TouchDownRepeatClosure?() } @objc fileprivate func runClosureTouchDragInside() { TouchDragInsideClosure?() } @objc fileprivate func runClosureTouchDragOutside() { TouchDragOutsideClosure?() } @objc fileprivate func runClosureTouchDragEnter() { TouchDragEnterClosure?() } @objc fileprivate func runClosureTouchDragExit() { TouchDragExitClosure?() } @objc fileprivate func runClosureTouchUpInside() { TouchUpInsideClosure?() } @objc fileprivate func runClosureTouchUpOutside() { TouchUpOutsideClosure?() } @objc fileprivate func runClosureTouchCancel() { TouchCancelClosure?() } @objc fileprivate func runClosureValueChanged() { ValueChangedClosure?() } @objc fileprivate func runClosureEditingDidBegin() { EditingDidBeginClosure?() } @objc fileprivate func runClosureEditingChanged() { EditingChangedClosure?() } @objc fileprivate func runClosureEditingDidEnd() { EditingDidEndClosure?() } @objc fileprivate func runClosureEditingDidEndOnExit() { EditingDidEndOnExitClosure?() } @objc fileprivate func runClosureAllTouchEvents() { AllTouchEventsClosure?() } @objc fileprivate func runClosureAllEditingEvents() { AllEditingEventsClosure?() } @objc fileprivate func runClosureApplicationReserved() { ApplicationReservedClosure?() } @objc fileprivate func runClosureSystemReserved() { SystemReservedClosure?() } @objc fileprivate func runClosureAllEvents() { AllEventsClosure?() } fileprivate func _addControlEvent(_ controlEvents: UIControl.Event, closure: @escaping ActionKitVoidClosure) { switch controlEvents { case let x where x.contains(.touchDown): self.TouchDownClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchDown), for: controlEvents) case let x where x.contains(.touchDownRepeat): self.TouchDownRepeatClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchDownRepeat), for: controlEvents) case let x where x.contains(.touchDragInside): self.TouchDragInsideClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchDragInside), for: controlEvents) case let x where x.contains(.touchDragOutside): self.TouchDragOutsideClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchDragOutside), for: controlEvents) case let x where x.contains(.touchDragEnter): self.TouchDragEnterClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchDragEnter), for: controlEvents) case let x where x.contains(.touchDragExit): self.TouchDragExitClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchDragExit), for: controlEvents) case let x where x.contains(.touchUpInside): self.TouchUpInsideClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchUpInside), for: controlEvents) case let x where x.contains(.touchUpOutside): self.TouchUpOutsideClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchUpOutside), for: controlEvents) case let x where x.contains(.touchCancel): self.TouchCancelClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchCancel), for: controlEvents) case let x where x.contains(.valueChanged): self.ValueChangedClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureValueChanged), for: controlEvents) case let x where x.contains(.editingDidBegin): self.EditingDidBeginClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureEditingDidBegin), for: controlEvents) case let x where x.contains(.editingChanged): self.EditingChangedClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureEditingChanged), for: controlEvents) case let x where x.contains(.editingDidEnd): self.EditingDidEndClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureEditingDidEnd), for: controlEvents) case let x where x.contains(.editingDidEndOnExit): self.EditingDidEndOnExitClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureEditingDidEndOnExit), for: controlEvents) case let x where x.contains(.allTouchEvents): self.AllTouchEventsClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureAllTouchEvents), for: controlEvents) case let x where x.contains(.allEditingEvents): self.AllEditingEventsClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureAllEditingEvents), for: controlEvents) case let x where x.contains(.applicationReserved): self.ApplicationReservedClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureApplicationReserved), for: controlEvents) case let x where x.contains(.systemReserved): self.SystemReservedClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureSystemReserved), for: controlEvents) case let x where x.contains(.allEvents): self.AllEventsClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureAllEvents), for: controlEvents) default: self.TouchUpInsideClosure = closure self.addTarget(self, action: #selector(UIControl.runClosureTouchUpInside), for: controlEvents) } } func removeControlEvent(_ controlEvents: UIControl.Event) { switch controlEvents { case let x where x.contains(.touchDown): self.TouchDownClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchDown), for: controlEvents) case let x where x.contains(.touchDownRepeat): self.TouchDownRepeatClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchDownRepeat), for: controlEvents) case let x where x.contains(.touchDragInside): self.TouchDragInsideClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchDragInside), for: controlEvents) case let x where x.contains(.touchDragOutside): self.TouchDragOutsideClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchDragOutside), for: controlEvents) case let x where x.contains(.touchDragEnter): self.TouchDragEnterClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchDragEnter), for: controlEvents) case let x where x.contains(.touchDragExit): self.TouchDragExitClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchDragExit), for: controlEvents) case let x where x.contains(.touchUpInside): self.TouchUpInsideClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchUpInside), for: controlEvents) case let x where x.contains(.touchUpOutside): self.TouchUpOutsideClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchUpOutside), for: controlEvents) case let x where x.contains(.touchCancel): self.TouchCancelClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchCancel), for: controlEvents) case let x where x.contains(.valueChanged): self.ValueChangedClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureValueChanged), for: controlEvents) case let x where x.contains(.editingDidBegin): self.EditingDidBeginClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureEditingDidBegin), for: controlEvents) case let x where x.contains(.editingChanged): self.EditingChangedClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureEditingChanged), for: controlEvents) case let x where x.contains(.editingDidEnd): self.EditingDidEndClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureEditingDidEnd), for: controlEvents) case let x where x.contains(.editingDidEndOnExit): self.EditingDidEndOnExitClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureEditingDidEndOnExit), for: controlEvents) case let x where x.contains(.allTouchEvents): self.AllTouchEventsClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureAllTouchEvents), for: controlEvents) case let x where x.contains(.allEditingEvents): self.AllEditingEventsClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureAllEditingEvents), for: controlEvents) case let x where x.contains(.applicationReserved): self.ApplicationReservedClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureApplicationReserved), for: controlEvents) case let x where x.contains(.systemReserved): self.SystemReservedClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureSystemReserved), for: controlEvents) case let x where x.contains(.allEvents): self.AllEventsClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureAllEvents), for: controlEvents) default: self.TouchUpInsideClosure = nil self.removeTarget(self, action: #selector(UIControl.runClosureTouchUpInside), for: controlEvents) } } }
mit
ce6a023678957d2d92da0b8dbec87122
51.739938
128
0.709011
5.57428
false
false
false
false
superk589/DereGuide
DereGuide/View/CGSSSearchBar.swift
2
1621
// // CGSSSearchBar.swift // DereGuide // // Created by zzk on 2017/1/14. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit class CGSSSearchBar: UISearchBar { override init(frame: CGRect) { super.init(frame: frame) // 为了避免push/pop时闪烁,searchBar的背景图设置为透明的 for sub in self.subviews.first!.subviews { if let iv = sub as? UIImageView { iv.alpha = 0 } } autocapitalizationType = .none autocorrectionType = .no returnKeyType = .search enablesReturnKeyAutomatically = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { // fix a layout issue in iOS 11 if #available(iOS 11.0, *) { return UIView.layoutFittingExpandedSize } else { return super.intrinsicContentSize } } } class SearchBarWrapper: UIView { let searchBar: CGSSSearchBar init(searchBar: CGSSSearchBar) { self.searchBar = searchBar super.init(frame: .zero) addSubview(searchBar) searchBar.snp.makeConstraints { (make) in make.height.equalTo(44) make.edges.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { return UIView.layoutFittingExpandedSize } }
mit
24273a43d6afd6f59f23f81fbfe7bca0
23.4
59
0.600252
4.664706
false
false
false
false
paritoshmmmec/IBM-Ready-App-for-Healthcare
iOS/ReadyAppPT/DataSources/RoutineDataManager.swift
2
2574
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit /** Enum to report the state of the login attempt. */ enum RoutineResultType { case Success case Failure case Unknown } /** Data Manager is a wrapper to the database connection */ class RoutineDataManager: NSObject, WLDataDelegate { private(set) var routines : [Routine]! typealias RoutineCallback = (RoutineResultType)->Void var routineCallback: RoutineCallback! //Class variable that will return a singleton when requested class var routineDataManager : RoutineDataManager{ struct Singleton { static let instance = RoutineDataManager() } return Singleton.instance } /** Delgate method for WorkLight. Called when connection and return is successful :param: response Response from WorkLight */ func onSuccess(response: WLResponse!) { let responseJson = response.getResponseJson() as NSDictionary println("---routinesDataManager onSuccess") println(response.responseText) // on success, call utils method to format data routines = Utils.getRoutines(responseJson) routineCallback(RoutineResultType.Success) } /** Delgate method for WorkLight. Called when connection or return is unsuccessful :param: response Response from WorkLight */ func onFailure(response: WLFailResponse!) { println("---routinesDataManager onFailure") println(response.responseText) routineCallback(RoutineResultType.Failure) } /** Delgate method for WorkLight. Task to do before executing a call. */ func onPreExecute() { } /** Delgate method for WorkLight. Task to do after executing a call. */ func onPostExecute() { } /** Method called to get routines from the server :param: userID the user ID to get routine data for :param: callback callback for when we have a result */ func getRoutines(userID: String!, callback: (RoutineResultType)->()) { routineCallback = callback let adapterName : String = "ReadyAppsAdapter" let procedureName : String = "getRoutines" let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName, dataDelegate: self) let params : [String] = [userID] caller.invokeWithResponse(self, params: params) var userExists = false } }
epl-1.0
c7457c042d948a2003b6185c27268651
27.6
115
0.662262
5.294239
false
false
false
false
STT-Ocean/iOS_WB
iOS_WB/iOS_WB/Class/Tools/NSDate+Extension.swift
1
1809
// // NSDate+Extension.swift // iOS_WB // // Created by Alpha on 18/08/2017. // Copyright © 2017 STT. All rights reserved. // import UIKit extension Date{ static func createDate(_ timeStr :String , _ formatterStr : String) -> Date{ let formmat = DateFormatter() formmat.dateFormat = formatterStr formmat.locale = Locale.init(identifier: "en") let createDate = formmat.date(from: timeStr) return createDate! } // 生成当前时间对应的字符串 func descriptionStr() -> String{ let formatter = DateFormatter() formatter.locale = Locale.init(identifier: "en") var textStr = "" var formtterStr = "HH:mm" let calendar = NSCalendar.current if calendar.isDateInToday(self){ let interVal = Int(Date().timeIntervalSince(self)) if interVal < 60 { return "刚刚" }else if interVal < 60 * 60 { return "\(interVal/60)一分钟以前" }else if interVal < 60 * 60 * 24 { return "\(interVal/60/60/24)小时前" } }else if calendar.isDateInYesterday(self){ formtterStr = "昨天 :" + formtterStr }else{ // 获取两个时间 相差的 let comps = calendar.dateComponents([Calendar.Component.year,Calendar.Component.month,Calendar.Component.day], from: self, to: Date()) if comps.year! >= 1 { formtterStr = "yyyy-MM-dd " + formtterStr }else{ // 1 formtterStr = "MM-dd" + formtterStr } } formatter.dateFormat = formtterStr textStr = formatter.string(from: self) return textStr } }
mit
2d99e55c5217d487ee34d484dfa80c22
28.525424
148
0.543054
4.301235
false
false
false
false
SeraZheng/GitHouse.swift
3rd/KRProgressHUD/KRProgressHUD.swift
1
17184
// // KRProgressHUD.swift // KRProgressHUD // // Copyright © 2016年 Krimpedance. All rights reserved. // import UIKit /** Type of KRProgressHUD's background view. - **Clear:** `UIColor.clearColor`. - **White:** `UIColor(white: 1, alpho: 0.2)`. - **Black:** `UIColor(white: 0, alpho: 0.2)`. Default type. */ public enum KRProgressHUDMaskType { case Clear, White, Black } /** Style of KRProgressHUD. - **Black:** HUD's backgroundColor is `.blackColor()`. HUD's text color is `.whiteColor()`. - **White:** HUD's backgroundColor is `.whiteColor()`. HUD's text color is `.blackColor()`. Default style. - **BlackColor:** same `.Black` and confirmation glyphs become original color. - **WhiteColor:** same `.Black` and confirmation glyphs become original color. */ public enum KRProgressHUDStyle { case Black, White, BlackColor, WhiteColor } /** KRActivityIndicatorView style. (KRProgressHUD uses only large style.) - **Black:** the color is `.blackColor()`. Default style. - **White:** the color is `.blackColor()`. - **Color(startColor, endColor):** the color is a gradation to `endColor` from `startColor`. */ public enum KRProgressHUDActivityIndicatorStyle { case Black, White, Color(UIColor, UIColor) } /** * KRProgressHUD is a beautiful and easy-to-use progress HUD. */ public final class KRProgressHUD { private static let view = KRProgressHUD() /// Shared instance. KRProgressHUD is created as singleton. public class func sharedView() -> KRProgressHUD { return view } private let window = UIWindow(frame: UIScreen.mainScreen().bounds) private let progressHUDView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) private let iconView = UIView(frame: CGRect(x: 0,y: 0,width: 50,height: 50)) private let activityIndicatorView = KRActivityIndicatorView(position: CGPointZero, activityIndicatorStyle: .LargeBlack) private let drawView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) private let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 20)) private var maskType: KRProgressHUDMaskType { willSet { switch newValue { case .Clear: window.backgroundColor = UIColor.clearColor() case .White: window.backgroundColor = UIColor(white: 1, alpha: 0.2) case .Black: window.backgroundColor = UIColor(white: 0, alpha: 0.2) } } } private var progressHUDStyle: KRProgressHUDStyle { willSet { switch newValue { case .Black, .BlackColor: progressHUDView.backgroundColor = UIColor.blackColor() messageLabel.textColor = UIColor.whiteColor() case .White, .WhiteColor: progressHUDView.backgroundColor = UIColor.whiteColor() messageLabel.textColor = UIColor.blackColor() } } } private var activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle { willSet { switch newValue { case .Black: activityIndicatorView.activityIndicatorViewStyle = .LargeBlack case .White: activityIndicatorView.activityIndicatorViewStyle = .LargeWhite case let .Color(sc, ec): activityIndicatorView.activityIndicatorViewStyle = .LargeColor(sc, ec) } } } private var defaultStyle: KRProgressHUDStyle = .White { willSet { progressHUDStyle = newValue } } private var defaultMaskType: KRProgressHUDMaskType = .Black { willSet { maskType = newValue } } private var defaultActivityIndicatorStyle: KRProgressHUDActivityIndicatorStyle = .Black { willSet { activityIndicatorStyle = newValue } } private var defaultMessageFont = UIFont(name: "HiraginoSans-W3", size: 13) ?? UIFont.systemFontOfSize(13) { willSet { messageLabel.font = newValue } } private init() { window.windowLevel = UIWindowLevelNormal window.backgroundColor = UIColor(white: 0, alpha: 0.4) maskType = .Black progressHUDStyle = .White activityIndicatorStyle = .Black configureProgressHUDView() } private func configureProgressHUDView() { let screenFrame = UIScreen.mainScreen().bounds progressHUDView.center = CGPoint(x: screenFrame.width/2, y: screenFrame.height/2) progressHUDView.backgroundColor = UIColor.whiteColor() progressHUDView.layer.cornerRadius = 10 window.addSubview(progressHUDView) iconView.backgroundColor = UIColor.clearColor() iconView.center = CGPoint(x: 50, y: 50) progressHUDView.addSubview(iconView) activityIndicatorView.hidden = false iconView.addSubview(activityIndicatorView) drawView.backgroundColor = UIColor.clearColor() drawView.hidden = true iconView.addSubview(drawView) messageLabel.center = CGPoint(x: 150/2, y: 90) messageLabel.backgroundColor = UIColor.clearColor() messageLabel.font = defaultMessageFont messageLabel.textAlignment = .Center messageLabel.adjustsFontSizeToFitWidth = true messageLabel.minimumScaleFactor = 0.5 messageLabel.text = nil messageLabel.hidden = true progressHUDView.addSubview(messageLabel) } } /** * KRProgressHUD Setter -------------------------- */ extension KRProgressHUD { /// Set default mask type. /// - parameter type: `KRProgressHUDMaskType` public class func setDefaultMaskType(type type: KRProgressHUDMaskType) { KRProgressHUD.sharedView().defaultMaskType = type } /// Set default HUD style /// - parameter style: `KRProgressHUDStyle` public class func setDefaultStyle(style style: KRProgressHUDStyle) { KRProgressHUD.sharedView().defaultStyle = style } /// Set default KRActivityIndicatorView style. /// - parameter style: `KRProgresHUDActivityIndicatorStyle` public class func setDefaultActivityIndicatorStyle(style style: KRProgressHUDActivityIndicatorStyle) { KRProgressHUD.sharedView().defaultActivityIndicatorStyle = style } /// Set default HUD text font. /// - parameter font: text font public class func setDefaultFont(font font: UIFont) { KRProgressHUD.sharedView().defaultMessageFont = font } } /** * KRProgressHUD Show & Dismiss -------------------------- */ extension KRProgressHUD { /** Showing HUD with some args. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressStyle KRProgressHUDStyle - parameter type KRProgressHUDMaskType - parameter indicatorStyle KRProgressHUDActivityIndicatorStyle - parameter font HUD's message font - parameter message HUD's message - parameter image image that Alternative to confirmation glyph. */ public class func show( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type:KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil, image: UIImage? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(image: image) KRProgressHUD.sharedView().show() } /** Showing HUD with success glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressStyle KRProgressHUDStyle - parameter type KRProgressHUDMaskType - parameter indicatorStyle KRProgressHUDActivityIndicatorStyle - parameter font HUD's message font - parameter message HUD's message */ public class func showSuccess( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type:KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .Success) KRProgressHUD.sharedView().show() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { sleep(1) KRProgressHUD.dismiss() } } /** Showing HUD with information glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressStyle KRProgressHUDStyle - parameter type KRProgressHUDMaskType - parameter indicatorStyle KRProgressHUDActivityIndicatorStyle - parameter font HUD's message font - parameter message HUD's message */ public class func showInfo( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type:KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .Info) KRProgressHUD.sharedView().show() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { sleep(1) KRProgressHUD.dismiss() } } /** Showing HUD with warning glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressStyle KRProgressHUDStyle - parameter type KRProgressHUDMaskType - parameter indicatorStyle KRProgressHUDActivityIndicatorStyle - parameter font HUD's message font - parameter message HUD's message */ public class func showWarning( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type:KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .Warning) KRProgressHUD.sharedView().show() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { sleep(1) KRProgressHUD.dismiss() } } /** Showing HUD with error glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressStyle KRProgressHUDStyle - parameter type KRProgressHUDMaskType - parameter indicatorStyle KRProgressHUDActivityIndicatorStyle - parameter font HUD's message font - parameter message HUD's message */ public class func showError( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type:KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font: font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(iconType: .Error) KRProgressHUD.sharedView().show() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { sleep(1) KRProgressHUD.dismiss() } } /** Dismissing HUD. */ public class func dismiss() { dispatch_async(dispatch_get_main_queue()) { () -> Void in UIView.animateWithDuration(0.5, animations: { KRProgressHUD.sharedView().window.alpha = 0 }) { _ in KRProgressHUD.sharedView().window.hidden = true KRProgressHUD.sharedView().activityIndicatorView.stopAnimating() KRProgressHUD.sharedView().progressHUDStyle = KRProgressHUD.sharedView().defaultStyle KRProgressHUD.sharedView().maskType = KRProgressHUD.sharedView().defaultMaskType KRProgressHUD.sharedView().activityIndicatorStyle = KRProgressHUD.sharedView().defaultActivityIndicatorStyle KRProgressHUD.sharedView().messageLabel.font = KRProgressHUD.sharedView().defaultMessageFont } } } } /** * KRProgressHUD update style method -------------------------- */ private extension KRProgressHUD { func show() { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.window.alpha = 0 self.window.makeKeyAndVisible() UIView.animateWithDuration(0.5) { KRProgressHUD.sharedView().window.alpha = 1 } } } func updateStyles(progressHUDStyle progressStyle: KRProgressHUDStyle?, maskType type:KRProgressHUDMaskType?, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle?) { if let style = progressStyle { KRProgressHUD.sharedView().progressHUDStyle = style } if let type = type { KRProgressHUD.sharedView().maskType = type } if let style = indicatorStyle { KRProgressHUD.sharedView().activityIndicatorStyle = style } } func updateProgressHUDViewText(font font: UIFont?, message: String?) { if let text = message { let center = progressHUDView.center var frame = progressHUDView.frame frame.size = CGSize(width: 150, height: 110) progressHUDView.frame = frame progressHUDView.center = center iconView.center = CGPoint(x: 150/2, y: 40) messageLabel.hidden = false messageLabel.text = text messageLabel.font = font ?? defaultMessageFont } else { let center = progressHUDView.center var frame = progressHUDView.frame frame.size = CGSize(width: 100, height: 100) progressHUDView.frame = frame progressHUDView.center = center iconView.center = CGPoint(x: 50, y: 50) messageLabel.hidden = true } } func updateProgressHUDViewIcon(iconType iconType: KRProgressHUDIconType? = nil, image: UIImage? = nil) { drawView.subviews.forEach{ $0.removeFromSuperview() } drawView.layer.sublayers?.forEach{ $0.removeFromSuperlayer() } switch (iconType, image) { case (nil, nil): drawView.hidden = true activityIndicatorView.hidden = false activityIndicatorView.startAnimating() case let (nil, image): activityIndicatorView.hidden = true activityIndicatorView.stopAnimating() drawView.hidden = false let imageView = UIImageView(image: image) imageView.frame = KRProgressHUD.sharedView().drawView.bounds imageView.contentMode = .ScaleAspectFit drawView.addSubview(imageView) case let (type, _): drawView.hidden = false activityIndicatorView.hidden = true activityIndicatorView.stopAnimating() let pathLayer = CAShapeLayer() pathLayer.frame = drawView.layer.bounds pathLayer.lineWidth = 0 pathLayer.path = type!.getPath() switch progressHUDStyle { case .Black: pathLayer.fillColor = UIColor.whiteColor().CGColor case .White: pathLayer.fillColor = UIColor.blackColor().CGColor default: pathLayer.fillColor = type!.getColor() } drawView.layer.addSublayer(pathLayer) } } }
mit
8344842e0a4c5440034bc274274bc431
40.203837
191
0.655957
5.609207
false
false
false
false
contentful/contentful.swift
Sources/Contentful/ContentfulLogger.swift
1
2563
// // ContentfulLogger.swift // Contentful // // Created by JP Wright on 12/11/18. // Copyright © 2018 Contentful GmbH. All rights reserved. // import Foundation /// Implement this protocol in order to provide your own custom logger for the SDK to log messages to. /// Your `CustomLogger` instance will only be passed message it should log according the set log level. public protocol CustomLogger { /// Logs a message if the message being logged has a log level less than the level configured on the Logger instance. Logging with LogType `none` does nothing. func log(message: String) } /// A logger for outputting status messages to the console from Contentful SDK. public enum ContentfulLogger { #if os(iOS) || os(tvOS) || os(watchOS) || os(macOS) /// The type of logger used to log messages; defaults to `NSLog` on iOS, tvOS, watchOS, macOS. Defaults to `print` on other platforms. public static var logType: LogType = .nsLog #else /// The type of logger used to log messages; defaults to `NSLog` on iOS, tvOS, watchOS, macOS. Defaults to `print` on other platforms. public static var logType: LogType = .print #endif /// The highest order of message types that should be logged. Defaults to `LogLevel.error`. public static var logLevel: LogLevel = .error /// An enum describing the types of messages to be logged. public enum LogLevel: Int { /// Log nothing to the console. case none = 0 /// Only log errors to the console. case error /// Log messages when requests are sent, and when responses are received, as well as other useful information. case info } /// The type of logger to use. public enum LogType { /// Log using simple Swift print statements case print /// Log using NSLog. case nsLog /// Log using a custom logger. case custom(CustomLogger) } internal static func log(_ level: LogLevel, message: String) { guard level.rawValue <= self.logLevel.rawValue && level != .none else { return } var formattedMessage = "[Contentful] " switch level { case .error: formattedMessage += "Error: " default: break } formattedMessage += message switch self.logType { case .print: Swift.print(formattedMessage) case .nsLog: NSLog(formattedMessage) case .custom(let customLogger): customLogger.log(message: formattedMessage) } } }
mit
238b418345a8e96551ddd5675e84a275
34.583333
163
0.652225
4.591398
false
false
false
false
TZLike/GiftShow
GiftShow/GiftShow/Classes/HomePage/Model/LeeBannerModel.swift
1
1645
// // LeeBannerModel.swift // GiftShow // // Created by admin on 16/8/9. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit class LeeBannerModel: LeeBaseModel { var ad_monitors:[String]? var channel:String? var id:NSNumber? var image_url:String?{ didSet{ if let url = image_url { imageURL = URL(string: url) } } } var imageURL:URL? var order:NSNumber? var status:NSNumber? var target_id:NSNumber? var target_type:NSNumber? var target_url:String? var type:NSNumber? var webp_url:String? var target:[String:AnyObject]? init(dict:[String:AnyObject]) { super.init() setValuesForKeys(dict) } // static func loadBanner(finished:(modals:[LeeBannerModel]?,error:NSError?)->()){ // let dict = ["channel":"iOS"] // LeeGiftNetworkTool.shareInstance() .GET("v2/banners", parameters: dict, success: { (_, JSON) ->Void in // //转换成模型 // // var dd = JSON["data"]! as! [String:AnyObject] // let array = dd["banners"] as! [[String : AnyObject]] // let arrs = Json2Modal(array) // finished(modals: arrs,error:nil) // // }) { (_, error) -> Void in // finished(modals: nil,error: error) // } // // } // class func Json2Modal(lists:[[String:AnyObject]]) -> [LeeBannerModel]{ // var arr = [LeeBannerModel]() //初始化一个数组 // for dict in lists{ // arr .append(LeeBannerModel(dict: dict)) // } // return arr // } }
apache-2.0
160360e49aad33b7397619c6e59374aa
25.096774
112
0.54759
3.644144
false
false
false
false
gregomni/swift
test/Constraints/mutating_members_compat.swift
10
1896
// RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s protocol P {} struct Foo { mutating func boom() {} } let x = Foo.boom // expected-warning{{cannot reference 'mutating' method as function value; calling the function has undefined behavior and will be an error in future Swift versions}} var y = Foo() let z0 = y.boom // expected-error{{cannot reference 'mutating' method as function value}} let z1 = Foo.boom(&y) // expected-error{{cannot reference 'mutating' method as function value}} func fromLocalContext() -> (inout Foo) -> () -> () { return Foo.boom // expected-warning{{cannot reference 'mutating' method as function value; calling the function has undefined behavior and will be an error in future Swift versions}} } func fromLocalContext2(x: inout Foo, y: Bool) -> () -> () { if y { return x.boom // expected-error{{cannot reference 'mutating' method as function value}} } else { return Foo.boom(&x) // expected-error{{cannot reference 'mutating' method as function value}} } } func bar() -> P.Type { fatalError() } func bar() -> Foo.Type { fatalError() } _ = bar().boom // expected-warning{{cannot reference 'mutating' method as function value; calling the function has undefined behavior and will be an error in future Swift versions}} _ = bar().boom(&y) // expected-error{{cannot reference 'mutating' method as function value}} _ = bar().boom(&y)() // expected-error{{cannot reference 'mutating' method as function value}} func foo(_ foo: Foo.Type) { _ = foo.boom // expected-warning{{cannot reference 'mutating' method as function value; calling the function has undefined behavior and will be an error in future Swift versions}} _ = foo.boom(&y) // expected-error{{cannot reference 'mutating' method as function value}} _ = foo.boom(&y)() // expected-error{{cannot reference 'mutating' method as function value}} }
apache-2.0
ad0a2b4713217dd75eabed86de89adc6
51.666667
187
0.704114
3.983193
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch15/15.2.3构造器继承.playground/section-1.swift
1
1592
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] import Foundation class Person { var name : String var age : Int func description() -> String { return "\(name) 年龄是: \(age)" } convenience init () { self.init(name: "Tony") self.age = 18 } convenience init (name : String) { self.init(name: name, age: 18) } init (name : String, age : Int) { self.name = name self.age = age } } class Student : Person { var school : String init (name : String, age : Int, school : String) { self.school = school super.init(name : name, age : age) } convenience override init (name : String, age : Int) { self.init(name : name, age : age, school : "清华大学") } } class Graduate : Student { var special : String = "" } let student1 = Student() let student2 = Student(name : "Tom") let student3 = Student(name : "Tom", age : 28) let student4 = Student(name : "Ben", age : 20, school : "香港大学") let gstudent1 = Graduate() let gstudent2 = Graduate(name : "Tom") let gstudent3 = Graduate(name : "Tom", age : 28) let gstudent4 = Graduate(name : "Ben", age : 20, school : "香港大学")
gpl-2.0
751a9bfc1b70ed446de0a063fee5c586
24.75
65
0.605409
3.068085
false
false
false
false
isnine/HutHelper-Open
HutHelper/SwiftApp/Third/FWPopupView/FWPopupWindow.swift
1
3762
// // FWPopupWindow.swift // FWPopupView // // Created by xfg on 2018/3/19. // Copyright © 2018年 xfg. All rights reserved. // 弹窗window /** ************************************************ github地址:https://github.com/choiceyou/FWPopupView bug反馈、交流群:670698309 *************************************************** */ import Foundation import UIKit public func kPV_RGBA (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor { return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } open class FWPopupWindow: UIWindow, UIGestureRecognizerDelegate { /// 单例模式 @objc public class var sharedInstance: FWPopupWindow { struct Static { static let kbManager = FWPopupWindow(frame: UIScreen.main.bounds) } // if #available(iOS 13.0, *) { // if Static.kbManager.windowScene == nil { // let windowScene = UIApplication.shared.connectedScenes.filter{$0.activationState == .foregroundActive}.first // Static.kbManager.windowScene = windowScene as? UIWindowScene // } // } return Static.kbManager } // 默认false,当为true时:用户点击外部遮罩层页面可以消失 @objc open var touchWildToHide: Bool = false // 默认false,当为true时:用户拖动外部遮罩层页面可以消失 @objc open var panWildToHide: Bool = false /// 被隐藏的视图队列(A视图正在显示,接着B视图显示,此时就把A视图隐藏同时放入该队列) open var hiddenViews: [UIView] = [] /// 将要展示的视图队列(A视图的显示或者隐藏动画正在进行中时,此时如果B视图要显示,则把B视图放入该队列,等动画结束从该队列中拿出来显示) open var willShowingViews: [UIView] = [] public override init(frame: CGRect) { super.init(frame: frame) let rootVC = FWPopupRootViewController() rootVC.view.backgroundColor = UIColor.clear self.rootViewController = rootVC self.windowLevel = UIWindow.Level.statusBar + 1 let tapGest = UITapGestureRecognizer(target: self, action: #selector(tapGesClick(tap:))) // tapGest.cancelsTouchesInView = false tapGest.delegate = self self.addGestureRecognizer(tapGest) let panGest = UIPanGestureRecognizer(target: self, action: #selector(panGesClick(pan:))) self.addGestureRecognizer(panGest) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension FWPopupWindow { @objc func tapGesClick(tap: UIGestureRecognizer) { if self.touchWildToHide && !self.attachView()!.fwBackgroundAnimating { for view in (self.attachView()?.fwMaskView.subviews)! { if view.isKind(of: FWPopupView.self) && !self.hiddenViews.contains(view) { let popupView = view as! FWPopupView if popupView.currentPopupViewState == .didAppear || popupView.currentPopupViewState == .didAppearAgain { popupView.hide() } } } } } @objc func panGesClick(pan: UIGestureRecognizer) { if self.panWildToHide { self.tapGesClick(tap: pan) } } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view == self.attachView()?.fwMaskView } public func attachView() -> UIView? { if self.rootViewController != nil { return self.rootViewController?.view } else { return nil } } }
lgpl-2.1
1a366c6331470d1b9aa265f1af024c1d
31.084112
126
0.615205
4.186585
false
false
false
false
BellAppLab/Defines
Sources/Defines/Defines.swift
1
24463
/* 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 } } }
mit
122ef5c798f95804c5f92ce5044153fe
45.779693
139
0.576314
4.17633
false
false
false
false
CoolCodeFactory/Antidote
AntidoteArchitectureExample/MasterDetailFlowCoordinator.swift
1
1655
// // Master-DetailFlowCoordinator.swift // AntidoteArchitectureExample // // Created by Dmitriy Utmanov on 16/09/16. // Copyright © 2016 Dmitry Utmanov. All rights reserved. // import UIKit class MasterDetailFlowCoordinator: ModalCoordinatorProtocol { var childCoordinators: [CoordinatorProtocol] = [] weak var navigationController: NavigationViewController! var closeHandler: () -> () = { fatalError() } let viewControllersFactory = MasterDetailViewControllersFactory() weak var masterDetailViewController: UISplitViewController! weak var presentingViewController: UIViewController! required init(presentingViewController: UIViewController) { self.presentingViewController = presentingViewController } func start(animated: Bool) { masterDetailViewController = viewControllersFactory.masterDetailViewController() let userFlowCoordinator = UserMasterDetailFlowCoordinator(splitViewController: masterDetailViewController) addChildCoordinator(userFlowCoordinator) userFlowCoordinator.closeHandler = { [unowned userFlowCoordinator] in userFlowCoordinator.finish(animated: animated) self.removeChildCoordinator(userFlowCoordinator) self.closeHandler() } userFlowCoordinator.start(animated: animated) presentingViewController.present(masterDetailViewController, animated: animated, completion: nil) } func finish(animated: Bool) { removeAllChildCoordinators() masterDetailViewController.dismiss(animated: animated, completion: nil) } }
mit
f0e90d6abb025ec7d08e46e17bc97b0a
32.08
114
0.729746
6.080882
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Delegate List/DelegateTableViewCell.swift
1
5165
// Copyright (c) 2016 Ark // // 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 SwiftyArk class DelegateTableViewCell: UITableViewCell { var delegate : Delegate? var rankLabel : UILabel! var nameLabel : UILabel! var approvalLabel : UILabel! var productivityLabel : UILabel! var seperator : UIView! public func update(_ delegate: Delegate) { self.delegate = delegate rankLabel.text = String(delegate.rate) nameLabel.text = delegate.username approvalLabel.text = String(delegate.approval) + "%" productivityLabel.text = String(delegate.productivity) + "%" if delegate.publicKey == ArkDataManager.currentVote?.publicKey { rankLabel.textColor = ArkPalette.accentColor nameLabel.textColor = ArkPalette.accentColor approvalLabel.textColor = ArkPalette.accentColor productivityLabel.textColor = ArkPalette.accentColor } else { rankLabel.textColor = ArkPalette.highlightedTextColor nameLabel.textColor = ArkPalette.highlightedTextColor approvalLabel.textColor = ArkPalette.highlightedTextColor productivityLabel.textColor = ArkPalette.highlightedTextColor } backgroundColor = ArkPalette.backgroundColor seperator.backgroundColor = ArkPalette.tertiaryBackgroundColor } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = ArkPalette.backgroundColor selectionStyle = .none rankLabel = UILabel() rankLabel.textColor = ArkPalette.accentColor rankLabel.textAlignment = .center rankLabel.font = UIFont.systemFont(ofSize: 15.0, weight: .semibold) addSubview(rankLabel) rankLabel.snp.makeConstraints { (make) in make.top.bottom.left.equalToSuperview() make.width.equalToSuperview().multipliedBy(0.16) } nameLabel = UILabel() nameLabel.textColor = ArkPalette.highlightedTextColor nameLabel.adjustsFontSizeToFitWidth = true nameLabel.textAlignment = .center nameLabel.font = UIFont.systemFont(ofSize: 15.0, weight: .semibold) addSubview(nameLabel) nameLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(rankLabel.snp.right) make.width.equalToSuperview().multipliedBy(0.28) } approvalLabel = UILabel() approvalLabel.textColor = ArkPalette.highlightedTextColor approvalLabel.textAlignment = .center approvalLabel.font = UIFont.systemFont(ofSize: 15.0, weight: .semibold) addSubview(approvalLabel) approvalLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(nameLabel.snp.right) make.width.equalToSuperview().multipliedBy(0.28) } productivityLabel = UILabel() productivityLabel.textColor = ArkPalette.highlightedTextColor productivityLabel.textAlignment = .center productivityLabel.font = UIFont.systemFont(ofSize: 15.0, weight: .semibold) addSubview(productivityLabel) productivityLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(approvalLabel.snp.right) make.width.equalToSuperview().multipliedBy(0.28) } seperator = UIView() seperator.backgroundColor = ArkPalette.secondaryBackgroundColor addSubview(seperator) seperator.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(0.5) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
5dd1f7066db3d79d811d998a4c0446d4
42.771186
137
0.666021
5.431125
false
false
false
false
vimeo/VimeoUpload
VimeoUpload/Upload/Extensions/AVAsset+Extensions.swift
1
2217
// // AVAsset+Extensions.swift // VimeoUpload // // Created by Alfred Hanssen on 11/1/15. // Copyright © 2015 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import AVFoundation @objc public extension AVAsset { func approximateFileSize(completion: @escaping DoubleBlock) { DispatchQueue.global(qos: .default).async { () -> Void in var approximateSize: Double = 0 let tracks = self.tracks // Accessing the tracks property is slow, maybe synchronous below the hood, so dispatching to bg thread for track in tracks { let dataRate: Float = track.estimatedDataRate let bytesPerSecond = Double(dataRate / 8) let seconds: Double = CMTimeGetSeconds(track.timeRange.duration) approximateSize += seconds * bytesPerSecond } assert(approximateSize > 0, "Unable to calculate approximate fileSize") DispatchQueue.main.async(execute: { () -> Void in completion(approximateSize) }) } } }
mit
3e76253d695eeedc47d08f50ac12df6b
40.811321
140
0.67509
4.817391
false
false
false
false
grandiere/box
box/View/GridVisorMatch/VGridVisorMatchBaseButton.swift
1
1409
import UIKit class VGridVisorMatchBaseButton:UIButton { init(image:UIImage, tintColor:UIColor) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor(white:1, alpha:0.2) translatesAutoresizingMaskIntoConstraints = false setImage( image.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.normal) setImage( image.withRenderingMode(UIImageRenderingMode.alwaysTemplate), for:UIControlState.highlighted) imageView!.tintColor = tintColor imageView!.clipsToBounds = true imageView!.contentMode = UIViewContentMode.center } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let width_2:CGFloat = width / 2.0 layer.cornerRadius = width_2 super.layoutSubviews() } //MARK: public func deactivate(image:UIImage) { isUserInteractionEnabled = false backgroundColor = UIColor.gridOrange setImage( image.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.normal) setImage( image.withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.highlighted) } }
mit
db655853bcf8d060e011c1dcb03ab176
27.755102
73
0.64088
5.658635
false
false
false
false
evermeer/PassportScanner
Pod/MRZTD3.swift
1
9710
// // MRZ.swift // PassportScanner // // Created by Edwin Vermeer on 12/5/14. // Copyright (c) 2015. All rights reserved. // import Foundation @objc(MRZTD3) open class MRZTD3: MRZParser { // check data with http://en.wikipedia.org/wiki/Machine-readable_passport /// Was the last scan valid. A value of 1 is for when all validations are OK private var _isValid: Float = 0 /// Do you want to see debug messages? Set to true (see init) to see what's going on. private var _debug = false /// The document type from the 1st line of the MRZ. (start 1, len 1) @objc public var documentType: String = "" /// The document sub type from the 1st line of the MRZ. (start 2, len 1) @objc public var documentSubType: String = "" /// The country code from the 1st line of the MRZ (start 3, len 3) @objc public var countryCode: String = "" /// The last name from the 1st line of the MRZ (start 6, len 39, until first <<) @objc public var lastName: String = "" /// The firstname from the 1st line of the MRZ (start 6, len 39, after first <<) @objc public var firstName: String = "" /// The passport number from the 2nd line of the MRZ. (start 1, len 9) @objc public var passportNumber: String = "" /// start 10, len 1 - validating the passportNumber private var passportNumberIsValid = false /// The nationality from the 2nd line of the MRZ. (start 11, len 3) @objc public var nationality: String = "" /// The date of birth from the 2nd line of the MRZ (start 14, len 6) @objc public var dateOfBirth: Date? /// start 20, len 1 - validating the dateOfBirth private var dateOfBirthIsValid = false /// The sex from the 2nd line of the MRZ. (start 21, len 1) @objc public var sex: String = "" /// The expiration date from the 2nd line of the MRZ. (start 22, len 6) @objc public var expirationDate: Date? /// start 28, len 1 - validating the expirationDate private var expirationDateIsValid = false /// The personal number from the 2nd line of the MRZ. (start 29, len 14 @objc public var personalNumber: String = "" /// start 43, len 1 - validating the personalNumber private var personalNumberIsValid = false // start 44, len 1 - validating passport number, date of birth, expiration date private var dataIsValid = false /** Convenience method for getting all data in a dictionary :returns: Return all fields in a dictionary */ @objc public override func data() -> Dictionary<String, Any> { return ["documentType" : documentType, "documentSubType" : documentSubType, "countryCode" : countryCode, "lastName" : lastName, "firstName" : firstName, "passportNumber" : passportNumber, "nationality" : nationality, "dateOfBirth" : MRZTD3.stringFromDate(dateOfBirth), "sex" : sex, "expirationDate" : MRZTD3.stringFromDate(expirationDate), "personalNumber" : personalNumber] } /** Get the description of the MRZ :returns: a string with all fields plus field name (each field on a new line) */ @objc open override var description: String { get { return self.data().map {"\($0) = \($1)"}.reduce("") {"\($0)\n\($1)"} } } /** Initiate the MRZ object with the scanned data. :param: scan the scanned string :param: debug true if you want to see debug messages. :returns: Instance of MRZ */ @objc public override init(scan: String, debug: Bool = false) { super.init(scan: scan, debug: debug) _debug = debug let lines: [String] = scan.split(separator: "\n").map({String($0)}) var longLines: [String] = [] for line in lines { let cleaned = line.replace(target: " ", with: "") if cleaned.count > 43 { longLines.append(line) } } if longLines.count < 2 { return } if longLines.count == 2 { process(l1: longLines[0].replace(target: " ", with: ""), l2: longLines[1].replace(target: " ", with: "")) } else if longLines.last?.components(separatedBy: "<").count ?? 0 > 1 { process(l1: longLines[longLines.count-2], l2: longLines[longLines.count-1]) } else { process(l1: longLines[longLines.count-3].replace(target: " ", with: ""), l2: longLines[longLines.count-2].replace(target: " ", with: "")) } } /** Do you want to see the progress in the log :param: line The data that will be logged */ fileprivate func debugLog(_ line: String) { if _debug { print(line) } } @objc override func isValid() -> Float {return _isValid} /** Process the 2 MRZ lines :param: l1 First line :param: l2 Second line */ fileprivate func process(l1: String, l2: String) { let line1 = MRZTD3.cleanup(line: l1) let line2 = MRZTD3.cleanup(line: l2) debugLog("Processing line 1 : \(line1)") debugLog("Processing line 2 : \(line2)") // Line 1 parsing documentType = line1.subString(0, to: 0) debugLog("Document type : \(documentType)") documentSubType = line1.subString(1, to: 1) countryCode = line1.subString(2, to: 4).replace(target: "<", with: " ") debugLog("Country code : \(countryCode)") let name = line1.subString(5, to: 43).replace(target: "0", with: "O") let nameArray = name.components(separatedBy: "<<") lastName = nameArray[0].replace(target: "<", with: " ") debugLog("Last name : \(lastName)") firstName = nameArray.count > 1 ? nameArray[1].replace(target: "<", with: " ") : "" debugLog("First name : \(firstName)") // Line 2 parsing passportNumber = line2.subString(0, to: 1) + line2.subString(2, to: 8).toNumber() debugLog("passportNumber : \(passportNumber)") let passportNumberCheck = line2.subString(9, to: 9).toNumber() nationality = line2.subString(10, to: 12).replace(target: "<", with: " ") debugLog("nationality : \(nationality)") let birth = line2.subString(13, to: 18).toNumber() let birthValidation = line2.subString(19, to: 19).toNumber() dateOfBirth = MRZTD3.dateFromString(birth, inThePast: true) debugLog("date of birth : \(dateOfBirth.debugDescription)") sex = line2.subString(20, to: 20) debugLog("sex : \(sex)") let expiration = line2.subString(21, to: 26).toNumber() expirationDate = MRZTD3.dateFromString(expiration) debugLog("date of expiration : \(expirationDate)") let expirationValidation = line2.subString(27, to: 27).toNumber() personalNumber = line2.subString(28, to: 41).toNumber() debugLog("personal number : \(personalNumber)") let personalNumberValidation = line2.subString(42, to: 42).toNumber() let data = "\(passportNumber)\(passportNumberCheck)\(birth)\(birthValidation)\(expiration)\(expirationValidation)\(personalNumber)\(personalNumberValidation)" let dataValidation = line2.subString(43, to: 43).toNumber() // Validation _isValid = 1 passportNumberIsValid = MRZTD3.validate(passportNumber, check: passportNumberCheck) if !passportNumberIsValid { print("--> PassportNumber is invalid") } _isValid = _isValid * (passportNumberIsValid ? 1 : 0.9) dateOfBirthIsValid = MRZTD3.validate(birth, check: birthValidation) if !dateOfBirthIsValid { print("--> DateOfBirth is invalid") } _isValid = _isValid * (dateOfBirthIsValid ? 1 : 0.9) _isValid = _isValid * (MRZTD3.validate(expiration, check: expirationValidation) ? 1 : 0.9) personalNumberIsValid = MRZTD3.validate(personalNumber, check: personalNumberValidation) if !personalNumberIsValid { print("--> PersonalNumber is invalid") } _isValid = _isValid * (personalNumberIsValid ? 1 : 0.9) dataIsValid = MRZTD3.validate(data, check: dataValidation) if !dataIsValid { print("--> Date is invalid") } _isValid = _isValid * (dataIsValid ? 1 : 0.9) // Final cleaning up documentSubType = documentSubType.replace(target: "<", with: "") personalNumber = personalNumber.replace(target: "<", with: "") } /** Cleanup a line of text :param: line The line that needs to be cleaned up :returns: Returns the cleaned up text */ fileprivate class func cleanup(line: String) -> String { let t = line.components(separatedBy: " ") if t.count > 1 { // are there extra characters added for p in t { if p.count == 44 { return p } } // was there one or more extra space added if "\(t[0])\(t[1])".count == 44 { return "\(t[0])\(t[1])" } else if "\(t[t.count-2])\(t[t.count-1])".count == 44 { return "\(t[t.count-2])\(t[t.count-1])" } else { return line.replace(target: " ", with: "") } } return line // assume the garbage characters are at the end } }
bsd-3-clause
921e231c0f0aede07f08c18d2e81d014
39.798319
166
0.582904
4.346464
false
false
false
false
clappr/clappr-ios
Sources/Clappr/Classes/View/DragDetectorView.swift
1
1366
import UIKit open class DragDetectorView: UIView { public enum State { case began, moved, ended, canceled, idle } fileprivate(set) open var touchState: State = .idle @objc fileprivate(set) open var currentTouch: UITouch? @objc open weak var target: AnyObject? @objc open var selector: Selector! open override func touchesBegan(_ touches: Set<UITouch>, with _: UIEvent?) { if let touch = touches.first { touchState = .began currentTouch = touch _ = target?.perform(selector, with: self) } } open override func touchesMoved(_ touches: Set<UITouch>, with _: UIEvent?) { if let touch = touches.first { touchState = .moved currentTouch = touch _ = target?.perform(selector, with: self) } } open override func touchesEnded(_ touches: Set<UITouch>, with _: UIEvent?) { if let touch = touches.first { touchState = .ended currentTouch = touch _ = target?.perform(selector, with: self) } } open override func touchesCancelled(_ touches: Set<UITouch>, with _: UIEvent?) { if let touch = touches.first { touchState = .canceled currentTouch = touch _ = target?.perform(selector, with: self) } } }
bsd-3-clause
118ebbaef23cdf0fc24e41ad9fea3699
27.458333
84
0.579795
4.776224
false
false
false
false
alexito4/Error-Handling-Script-Rust-Swift
main.swift
1
3421
#!/usr/bin/env xcrun swift -F ./Rome/ -framework Swiftline -framework Commander -framework CSwiftV import Foundation import Swiftline import Commander import CSwiftV /* Example: ./main.swift ./world.csv Ordino Searching Population of Ordino in ./world.csv The population of Ordino, AD is 2553 */ struct Row { let country: String let city: String let accent_city: String let region: String // Not every row has data for the population, latitude or longitude! // So we express them as `Option` types, which admits the possibility of // absence. The CSV parser will fill in the correct value for us. let population: Int? let latitude: Int? let longitude: Int? // Country,City,AccentCity,Region,Population,Latitude,Longitude init?(row: [String]) { guard row.count == 7 else { self.country = "" self.city = "" self.accent_city = "" self.region = "" self.population = nil self.latitude = nil self.longitude = nil return nil } self.country = row[0] self.city = row[1] self.accent_city = row[2] self.region = row[3] if let population = Int(row[4]) { self.population = population } else { self.population = nil } if let latitude = Int(row[5]) { self.latitude = latitude } else { self.latitude = nil } if let longitude = Int(row[6]) { self.longitude = longitude } else { self.longitude = nil } } } struct PopulationCount { let city: String let country: String // This is no longer an `Option` because values of this type are only // constructed if they have a population count. let count: Int } enum CliError: ErrorType { case IO case CSV case NotFound } func search(atPath path: NSURL, city: String) throws -> Array<PopulationCount> { let content: String do { content = try String(contentsOfURL: path) } catch { throw CliError.IO } let csv = CSwiftV(String: content) // this could fail but the lib doesn't throw. var found: Array<PopulationCount> = [] for r in csv.rows { guard let row = Row(row: r) else { throw CliError.CSV } switch row.population { case .Some(let population) where row.city == city: found.append( PopulationCount( city: row.city, country: row.country, count: population ) ) case .None, .Some: break // Skip it } } if found.isEmpty { throw CliError.NotFound } return found } let main = command { (file: String, city: String) in print("Searching Population of \(city) in \(file)...".f.Green) let path = NSURL(fileURLWithPath: file) do { let found = try search(atPath: path, city: city.lowercaseString) for pop in found { print("The population of \(city), \(pop.country.uppercaseString) is \(pop.count).".f.Blue) } } catch CliError.NotFound { print("\(city) population not found") } catch let error { fatalError(String(error)) } } main.run()
mit
0831b76763957cc700629ec77b3bd190
24.340741
102
0.562701
4.270911
false
false
false
false
wizages/Swift-Volume-Controller---iOS-8-9
TrueVolumeControls/ViewController.swift
1
1496
// // ViewController.swift // TrueVolumeControls // // Created by wizage on 5/4/16. // Copyright © 2016 wizage. All rights reserved. // import UIKit import MediaPlayer class ViewController: UIViewController { @IBOutlet weak var label : UILabel! override func viewDidLoad() { super.viewDidLoad() let vc = VolumeControl.sharedInstance /* This dispatch after is because the application is adding the volume control and not allowing enought time for the system to get the actual volume so it returns 0.0 which is incorrect. */ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.01*Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { self.label.text = String(format: "Current Volume: %.3f", vc.getCurrentVolume()) } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func turnUp() { let vc = VolumeControl.sharedInstance vc.turnUp() label.text = String(format: "Current Volume: %.3f", vc.getCurrentVolume()) } @IBAction func turnDown() { let vc = VolumeControl.sharedInstance vc.turnDown() label.text = String(format: "Current Volume: %.3f", vc.getCurrentVolume()) } }
mit
dac49b9af2ab61b3f71b78ad66d79340
26.181818
117
0.62408
4.476048
false
false
false
false
KeithPiTsui/Pavers
Pavers/Sources/UI/Styles/lenses/UITextViewLenses.swift
1
1841
import PaversFRP import UIKit public protocol UITextViewProtocol: UIScrollViewProtocol, UITextInputTraitsProtocol { #if os(iOS) var dataDetectorTypes: UIDataDetectorTypes { get set } #endif var font: UIFont? { get set } var text: String! { get set } var textAlignment: NSTextAlignment { get set } var textColor: UIColor? { get set } var textContainer: NSTextContainer { get } var textContainerInset: UIEdgeInsets { get set } } extension UITextView: UITextViewProtocol {} public extension LensHolder where Object: UITextViewProtocol { #if os(iOS) var dataDetectorTypes: Lens<Object, UIDataDetectorTypes> { return Lens( view: { $0.dataDetectorTypes }, set: { $1.dataDetectorTypes = $0; return $1 } ) } #endif var font: Lens<Object, UIFont?> { return Lens( view: { $0.font }, set: { $1.font = $0; return $1 } ) } var text: Lens<Object, String> { return Lens( view: { $0.text ?? "" }, set: { $1.text = $0; return $1 } ) } var textAlignment: Lens<Object, NSTextAlignment> { return Lens( view: { $0.textAlignment }, set: { $1.textAlignment = $0; return $1 } ) } var textColor: Lens<Object, UIColor?> { return Lens( view: { $0.textColor }, set: { $1.textColor = $0; return $1 } ) } var textContainer: Lens<Object, NSTextContainer> { return Lens( view: { $0.textContainer }, set: { $1 } ) } var textContainerInset: Lens<Object, UIEdgeInsets> { return Lens( view: { $0.textContainerInset }, set: { $1.textContainerInset = $0; return $1 } ) } } extension Lens where Whole: UITextViewProtocol, Part == NSTextContainer { public var lineFragmentPadding: Lens<Whole, CGFloat> { return Whole.lens.textContainer>>>Part.lens.lineFragmentPadding } }
mit
5a50880e84cce26a690edab27bb1a20f
23.223684
85
0.634438
3.900424
false
false
false
false
xasos/Swiftiris
Swiftiris/Shape.swift
1
5158
// // Shape.swift // Swiftiris // // Created by Niraj on 10/31/14. // Copyright (c) 2014 Niraj. All rights reserved. // import SpriteKit let NumOrientations: UInt32 = 4 enum Orientation: Int, Printable { case Zero = 0, Ninety, OneEighty, TwoSeventy var description: String { switch self { case .Zero: return "0" case .Ninety: return "90" case .OneEighty: return "180" case .TwoSeventy: return "270" } } static func random() -> Orientation { return Orientation(rawValue: Int(arc4random_uniform(NumOrientations)))! } static func rotate(orientation:Orientation, clockwise: Bool) -> Orientation { var rotated = orientation.rawValue + (clockwise ? 1 : -1) if rotated > Orientation.TwoSeventy.rawValue { rotated = Orientation.Zero.rawValue } else if rotated < 0 { rotated = Orientation.TwoSeventy.rawValue } return Orientation(rawValue: rotated)! } } let NumShapeTypes: UInt32 = 7 let FirstBlockIdx: Int = 0 let SecondBlockIdx: Int = 1 let ThirdBlockIdx: Int = 2 let FourthBlockIdx: Int = 3 class Shape: Hashable { let color:BlockColor var blocks = Array<Block>() var orientation: Orientation var column, row:Int var blockRowColumnPositions: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] { return [:] } var bottomBlocksForOrientations: [Orientation: Array<Block>] { return [:] } var bottomBlocks:Array<Block> { if let bottomBlocks = bottomBlocksForOrientations[orientation] { return bottomBlocks } return [] } var hashValue:Int { return reduce(blocks, 0) { $0.hashValue ^ $1.hashValue } } init(column:Int, row:Int, color:BlockColor, orientation: Orientation) { self.color = color self.column = column self.row = row self.orientation = orientation initializeBlocks() } convenience init(column:Int, row:Int) { self.init(column:column, row:row, color:BlockColor.random(), orientation:Orientation.random()) } final func initializeBlocks() { if let blockRowColumnTranslations = blockRowColumnPositions[orientation] { for i in 0..<blockRowColumnTranslations.count { let blockRow = row + blockRowColumnTranslations[i].rowDiff let blockColumn = column + blockRowColumnTranslations[i].columnDiff let newBlock = Block(column: blockColumn, row: blockRow, color: color) blocks.append(newBlock) } } } final func rotateBlocks(orientation: Orientation) { if let blockRowColumnTranslation:Array<(columnDiff: Int, rowDiff: Int)> = blockRowColumnPositions[orientation] { // #1 for (idx, (columnDiff:Int, rowDiff:Int)) in enumerate(blockRowColumnTranslation) { blocks[idx].column = column + columnDiff blocks[idx].row = row + rowDiff } } } final func rotateClockwise() { let newOrientation = Orientation.rotate(orientation, clockwise: true) rotateBlocks(newOrientation) orientation = newOrientation } final func rotateCounterClockwise() { let newOrientation = Orientation.rotate(orientation, clockwise: false) rotateBlocks(newOrientation) orientation = newOrientation } final func lowerShapeByOneRow() { shiftBy(0, rows:1) } final func raiseShapeByOneRow() { shiftBy(0, rows:-1) } final func shiftRightByOneColumn() { shiftBy(1, rows:0) } final func shiftLeftByOneColumn() { shiftBy(-1, rows:0) } // #2 final func shiftBy(columns: Int, rows: Int) { self.column += columns self.row += rows for block in blocks { block.column += columns block.row += rows } } // #3 final func moveTo(column: Int, row:Int) { self.column = column self.row = row rotateBlocks(orientation) } final class func random(startingColumn:Int, startingRow:Int) -> Shape { switch Int(arc4random_uniform(NumShapeTypes)) { // #4 case 0: return SquareShape(column:startingColumn, row:startingRow) case 1: return LineShape(column:startingColumn, row:startingRow) case 2: return TShape(column:startingColumn, row:startingRow) case 3: return LShape(column:startingColumn, row:startingRow) case 4: return JShape(column:startingColumn, row:startingRow) case 5: return SShape(column:startingColumn, row:startingRow) default: return ZShape(column:startingColumn, row:startingRow) } } } func ==(lhs: Shape, rhs:Shape) -> Bool { return lhs.row == rhs.row && lhs.column == rhs.column }
mit
36dfbd5d82cef6e89667078f0f01b10b
27.032609
120
0.594223
4.642664
false
false
false
false
CybercomPoland/ViperSideDrawer
ViperSideDrawer/RevealPresentationAnimator.swift
1
2904
// // RevealPresentationAnimator.swift // ViperSideDrawer // // Created by Aleksander Maj on 06/07/2017. // Copyright © 2017 Aleksander Maj. All rights reserved. // import UIKit final class RevealPresentationAnimator: NSObject { // MARK: - Properties let direction: SideDrawerPresentationDirection let isPresentation: Bool init(direction: SideDrawerPresentationDirection, isPresentation: Bool) { self.direction = direction self.isPresentation = isPresentation super.init() } } // MARK: - UIViewControllerAnimatedTransitioning extension RevealPresentationAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let parentVCKey = isPresentation ? UITransitionContextViewControllerKey.from : UITransitionContextViewControllerKey.to let childVCKey = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from let parentVC = transitionContext.viewController(forKey: parentVCKey)! let childVC = transitionContext.viewController(forKey: childVCKey)! if isPresentation { transitionContext.containerView.addSubview(childVC.view) } let childPresentedFrame = transitionContext.finalFrame(for: childVC) var childDismissedFrame = childPresentedFrame let parentDismissedFrame = transitionContext.finalFrame(for: parentVC) var parentPresentedFrame = parentDismissedFrame switch direction { case .left: childDismissedFrame.origin.x = -childPresentedFrame.width parentPresentedFrame.origin.x = childPresentedFrame.width case .right: childDismissedFrame.origin.x = transitionContext.containerView.frame.size.width parentPresentedFrame.origin.x = -childPresentedFrame.width } let childInitialFrame = isPresentation ? childDismissedFrame : childPresentedFrame let childFinalFrame = isPresentation ? childPresentedFrame : childDismissedFrame let parentInitialFrame = isPresentation ? parentDismissedFrame : parentPresentedFrame let parentFinalFrame = isPresentation ? parentPresentedFrame : parentDismissedFrame let animationDuration = transitionDuration(using: transitionContext) childVC.view.frame = childInitialFrame parentVC.view.frame = parentInitialFrame UIView.animate(withDuration: animationDuration, animations: { childVC.view.frame = childFinalFrame parentVC.view.frame = parentFinalFrame }) { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
mit
3ae1a0b503d06b0d0d335418efa3c8c7
37.706667
126
0.734757
6.366228
false
false
false
false
TENDIGI/Obsidian-UI-iOS
src/UITableViewExtensions.swift
1
1702
// // UITableViewExtensions.swift // Alfredo // // Created by Nick Lee on 8/24/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation extension UITableView { // MARK: Nib Registration /** Registers a cell nib of the passed name, using the name as its reuse identifier - parameter name: The name of the .nib file, which will also be used as the cell's reuse identifier */ public func registerCellNib(_ name: String) { let nib = NibCache[name] ?? UINib(nibName: name, bundle: Bundle.main) NibCache[name] = nib register(nib, forCellReuseIdentifier: name) } /// Adds an empty footer view. This has the effect of hiding extra cell separators. public func addEmptyFooterView() { let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 320, height: 1)) let view = UIView(frame: frame) tableFooterView = view } // MARK: Reloading /** Reloads the passed sections, with or without animation - parameter animated: Whether or not the transition should be animated - parameter sections: The sections to reload */ public func refreshSections(_ animated: Bool = false, _ sections: [Int]) { let indexSet = NSMutableIndexSet() for index in sections { indexSet.add(index) } let animations = { () -> () in let animation: UITableViewRowAnimation = animated ? .automatic : .none self.reloadSections(indexSet as IndexSet, with: animation) } if animated { animations() } else { UIView.performWithoutAnimation(animations) } } }
mit
5b92ca67c94a835d4dfa88ffc9e056a1
25.59375
103
0.628672
4.587601
false
false
false
false
Cin316/X-Schedule
X Schedule/AppDelegate.swift
1
3681
// // AppDelegate.swift // X Schedule // // Created by Nicholas Reichert on 2/13/15. // Copyright (c) 2015 Nicholas Reichert. // import UIKit import XScheduleKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var tabBarDelegate: MainTabBarDelegate? var applicationHasBeenActive: Bool = false func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { XLogger.redirectLogToFile() NSLog("[AppDelegate] Entering application didFinishLaunchingWithOptions") setUpTabBarDelegate() UnusualScheduleNotificationManager.requestAuthorizationForNotifications() UnusualScheduleNotificationManager.setUpBackgroundFetch() UnusualScheduleNotificationManager.loadScheduleTitles() return true } private func setUpTabBarDelegate() { //Allow delegate to control tab bar. if let tabBar = self.window?.rootViewController as? UITabBarController { tabBarDelegate = MainTabBarDelegate() tabBar.delegate = tabBarDelegate } } func applicationDidBecomeActive(_ application: UIApplication) { NSLog("[AppDelegate] Entering applicationDidBecomeActive") possiblyRefreshCache() } // The first time that the application enters the foreground, refresh the schedule cache. func possiblyRefreshCache() { NSLog("[AppDelegate] Possibly refreshing the cache...") if (!applicationHasBeenActive) { NSLog("[AppDelegate] Will be refreshing the cache.") applicationHasBeenActive = true CacheManager.refreshCache() } } func applicationWillEnterForeground(_ application: UIApplication) { NSLog("[AppDelegate] Entering applicationWillEnterForeground") refreshSchedule() } func refreshSchedule() { let scheduleViewController: ScheduleViewController = getScheduleViewController()! scheduleViewController.refreshSchedule() if let pageView = scheduleViewController as? SwipeDataViewController { pageView.pageController().flipPageInDirection(UIPageViewController.NavigationDirection.forward, withDate: pageView.scheduleDate) } } private func getScheduleSwitcherViewController() -> ScheduleSwitcherViewController? { var returnController: ScheduleSwitcherViewController? let tabBarController: UITabBarController = self.window!.rootViewController! as! UITabBarController for controller in tabBarController.viewControllers! { let viewController = controller if let switcher = viewController as? ScheduleSwitcherViewController { returnController = switcher } } return returnController } private func getScheduleViewController() -> ScheduleViewController? { let switcher = getScheduleSwitcherViewController()! var returnController: ScheduleViewController? if let currentView = switcher.currentView { if let scheduleView = currentView as? ScheduleViewController { returnController = scheduleView } } return returnController } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { NSLog("[AppDelegate] Entering application performFetchWithCompletionHandler") UnusualScheduleNotificationManager.backgroundAppRefresh(completionHandler) } }
mit
5d4113d538ca846a96c92ca8b0d0af73
38.580645
150
0.704971
6.480634
false
false
false
false
meteochu/DecisionKitchen
iOS/DecisionKitchen/UserHeaderCell.swift
1
2231
// // UserHeaderCell.swift // DecisionKitchen // // Created by Andy Liang on 2017-07-29. // Copyright © 2017 Andy Liang. All rights reserved. // import UIKit class UserHeaderCell: UICollectionViewCell { var user: User! { didSet { if let user = user { imageView.setImage(with: user.img, validator: { [weak self] in self != nil && self!.user.name == user.name }) nameLabel.text = user.firstName } self.layoutIfNeeded() } } // ui elements private let imageView = UIImageView() private let nameLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override func layoutSubviews() { super.layoutSubviews() imageView.layer.cornerRadius = imageView.bounds.width/2 } func commonInit() { imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true nameLabel.font = .systemFont(ofSize: 13) nameLabel.textColor = .darkText nameLabel.textAlignment = .center contentView.addSubview(imageView) contentView.addSubview(nameLabel) contentView.translatesAutoresizingMaskIntoConstraints = false imageView.translatesAutoresizingMaskIntoConstraints = false nameLabel.translatesAutoresizingMaskIntoConstraints = false imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true imageView.widthAnchor.constraint(equalToConstant: 64).isActive = true imageView.heightAnchor.constraint(equalToConstant: 64).isActive = true imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true nameLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 8).isActive = true nameLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 4).isActive = true nameLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -4).isActive = true } }
apache-2.0
dd238cb81e6504fba570c608352df079
31.318841
125
0.653363
5.21028
false
false
false
false
parkera/swift-corelibs-foundation
TestFoundation/FixtureValues.swift
1
6135
// This source file is part of the Swift.org open source project // // Copyright (c) 2019 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 // Please keep this import statement as-is; this file is also used by the GenerateTestFixtures project, which doesn't have TestImports.swift. #if DEPLOYMENT_RUNTIME_SWIFT && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) import SwiftFoundation #else import Foundation #endif // ----- enum Fixtures { static let mutableAttributedString = TypedFixture<NSMutableAttributedString>("NSMutableAttributedString") { let string = NSMutableAttributedString(string: "0123456789") // Should have: .xyyzzxyx. let attrs1: [NSAttributedString.Key: Any] = [.init("Font"): "Helvetica", .init("Size"): 123] let attrs2: [NSAttributedString.Key: Any] = [.init("Font"): "Times", .init("Size"): 456] let attrs3NS = attrs2 as NSDictionary let attrs3Maybe: [NSAttributedString.Key: Any]? if let attrs3Swift = attrs3NS as? [String: Any] { attrs3Maybe = Dictionary(attrs3Swift.map { (NSAttributedString.Key($0.key), $0.value) }, uniquingKeysWith: { $1 }) } else { attrs3Maybe = nil } let attrs3 = try attrs3Maybe.unwrapped() string.setAttributes(attrs1, range: NSMakeRange(1, string.length - 2)) string.setAttributes(attrs2, range: NSMakeRange(2, 2)) string.setAttributes(attrs3, range: NSMakeRange(4, 2)) string.setAttributes(attrs2, range: NSMakeRange(8, 1)) return string } static let attributedString = TypedFixture<NSAttributedString>("NSAttributedString") { return NSAttributedString(attributedString: try Fixtures.mutableAttributedString.make()) } // ===== ByteCountFormatter ===== static let byteCountFormatterDefault = TypedFixture<ByteCountFormatter>("ByteCountFormatter-Default") { return ByteCountFormatter() } static let byteCountFormatterAllFieldsSet = TypedFixture<ByteCountFormatter>("ByteCountFormatter-AllFieldsSet") { let f = ByteCountFormatter() f.allowedUnits = [.useBytes, .useKB] f.countStyle = .decimal f.formattingContext = .beginningOfSentence f.zeroPadsFractionDigits = true f.includesCount = true f.allowsNonnumericFormatting = false f.includesUnit = false f.includesCount = false f.isAdaptive = false return f } // ===== Fixture list ===== static let all: [AnyFixture] = [ AnyFixture(Fixtures.mutableAttributedString), AnyFixture(Fixtures.attributedString), AnyFixture(Fixtures.byteCountFormatterDefault), AnyFixture(Fixtures.byteCountFormatterAllFieldsSet), ] } // ----- // Support for the above: enum FixtureVariant: String, CaseIterable { case macOS10_14 = "macOS-10.14" func url(fixtureRepository: URL) -> URL { return URL(fileURLWithPath: self.rawValue, relativeTo: fixtureRepository) } } protocol Fixture { associatedtype ValueType var identifier: String { get } func make() throws -> ValueType var supportsSecureCoding: Bool { get } } struct TypedFixture<ValueType: NSObject & NSCoding>: Fixture { var identifier: String private var creationHandler: () throws -> ValueType init(_ identifier: String, creationHandler: @escaping () throws -> ValueType) { self.identifier = identifier self.creationHandler = creationHandler } func make() throws -> ValueType { return try creationHandler() } var supportsSecureCoding: Bool { return (ValueType.self as? NSSecureCoding.Type)?.supportsSecureCoding == true } } struct AnyFixture: Fixture { var identifier: String private var creationHandler: () throws -> NSObject & NSCoding let supportsSecureCoding: Bool init<T: Fixture>(_ fixture: T) { self.identifier = fixture.identifier self.creationHandler = { return try fixture.make() as! (NSObject & NSCoding) } self.supportsSecureCoding = fixture.supportsSecureCoding } func make() throws -> NSObject & NSCoding { return try creationHandler() } } enum FixtureError: Error { case noneFound } extension Fixture where ValueType: NSObject & NSCoding { func load(fixtureRepository: URL, variant: FixtureVariant) throws -> ValueType? { let data = try Data(contentsOf: url(inFixtureRepository: fixtureRepository, variant: variant)) let unarchiver = NSKeyedUnarchiver(forReadingWith: data) unarchiver.requiresSecureCoding = self.supportsSecureCoding let value = unarchiver.decodeObject(of: ValueType.self, forKey: NSKeyedArchiveRootObjectKey) if let error = unarchiver.error { throw error } return value } func url(inFixtureRepository fixtureRepository: URL, variant: FixtureVariant) -> URL { return variant.url(fixtureRepository: fixtureRepository) .appendingPathComponent(identifier) .appendingPathExtension("archive") } func loadEach(fixtureRepository: URL, handler: (ValueType, FixtureVariant) throws -> Void) throws { var foundAny = false for variant in FixtureVariant.allCases { let fileURL = url(inFixtureRepository: fixtureRepository, variant: variant) guard (try? fileURL.checkResourceIsReachable()) == true else { continue } foundAny = true if let value = try load(fixtureRepository: fixtureRepository, variant: variant) { try handler(value, variant) } } guard foundAny else { throw FixtureError.noneFound } } }
apache-2.0
6f8a95a027109a89796cf9543fbc0be8
34.057143
141
0.652812
4.983753
false
false
false
false
fizx/jane
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Core/CallResult.swift
2
2700
/* * Copyright 2016, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if SWIFT_PACKAGE import CgRPC import Dispatch #endif import Foundation public struct CallResult: CustomStringConvertible { public let success: Bool public let statusCode: StatusCode public let statusMessage: String? public let resultData: Data? public let initialMetadata: Metadata? public let trailingMetadata: Metadata? init(_ op: OperationGroup) { success = op.success if let statusCodeRawValue = op.receivedStatusCode(), let statusCode = StatusCode(rawValue: statusCodeRawValue) { self.statusCode = statusCode } else { statusCode = .unknown } statusMessage = op.receivedStatusMessage() resultData = op.receivedMessage()?.data() initialMetadata = op.receivedInitialMetadata() trailingMetadata = op.receivedTrailingMetadata() } fileprivate init(success: Bool, statusCode: StatusCode, statusMessage: String?, resultData: Data?, initialMetadata: Metadata?, trailingMetadata: Metadata?) { self.success = success self.statusCode = statusCode self.statusMessage = statusMessage self.resultData = resultData self.initialMetadata = initialMetadata self.trailingMetadata = trailingMetadata } public var description: String { var result = "\(success ? "successful" : "unsuccessful"), status \(statusCode)" if let statusMessage = self.statusMessage { result += ": " + statusMessage } if let resultData = self.resultData { result += "\nresultData: " result += resultData.description } if let initialMetadata = self.initialMetadata { result += "\ninitialMetadata: " result += initialMetadata.dictionaryRepresentation.description } if let trailingMetadata = self.trailingMetadata { result += "\ntrailingMetadata: " result += trailingMetadata.dictionaryRepresentation.description } return result } static let fakeOK = CallResult(success: true, statusCode: .ok, statusMessage: "OK", resultData: nil, initialMetadata: nil, trailingMetadata: nil) }
mit
9722909f52c1cf5ecf39045599fad409
34.526316
102
0.707778
4.972376
false
false
false
false
ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev
iOS/Pods/BMSPush/Source/BMSPushUrlBuilder.swift
4
11403
/* *     Copyright 2016 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import UIKit import BMSCore #if swift(>=3.0) internal class BMSPushUrlBuilder: NSObject { internal let FORWARDSLASH = "/"; internal let IMFPUSH = "imfpush"; internal let V1 = "v1"; internal let APPS = "apps"; internal let AMPERSAND = "&"; internal let QUESTIONMARK = "?"; internal let SUBZONE = "subzone"; internal let EQUALTO = "="; internal let SUBSCRIPTIONS = "subscriptions"; internal let MESSAGES = "messages"; internal let TAGS = "tags"; internal let DEVICES = "devices"; internal let TAGNAME = "tagName"; internal let DEVICEID = "deviceId"; internal let defaultProtocol = "https"; internal final var pwUrl_ = String() internal final var reWritedomain = String() internal final var clientSecretHeader = String() init(applicationID:String, clientSecret:String) { if !(clientSecret.isEmpty) { clientSecretHeader = clientSecret } if(!BMSPushClient.overrideServerHost.isEmpty){ pwUrl_ += BMSPushClient.overrideServerHost } else { pwUrl_ += defaultProtocol pwUrl_ += "://" if BMSClient.sharedInstance.bluemixRegion?.contains("stage1-test") == true || BMSClient.sharedInstance.bluemixRegion?.contains("stage1-dev") == true { pwUrl_ += IMFPUSH pwUrl_ += ".stage1.mybluemix.net" if BMSClient.sharedInstance.bluemixRegion?.contains("stage1-test") == true { reWritedomain = "stage1-test.ng.bluemix.net" } else{ reWritedomain = "stage1-dev.ng.bluemix.net" } } else{ pwUrl_ += IMFPUSH pwUrl_ += BMSClient.sharedInstance.bluemixRegion! reWritedomain = "" } } pwUrl_ += FORWARDSLASH pwUrl_ += IMFPUSH pwUrl_ += FORWARDSLASH pwUrl_ += V1 pwUrl_ += FORWARDSLASH pwUrl_ += APPS pwUrl_ += FORWARDSLASH pwUrl_ += applicationID pwUrl_ += FORWARDSLASH } func addHeader() -> [String: String] { if reWritedomain.isEmpty { if(clientSecretHeader.isEmpty){ return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON] } return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON, IMFPUSH_CLIENT_SECRET:clientSecretHeader] } else{ if clientSecretHeader.isEmpty { return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON, IMFPUSH_X_REWRITE_DOMAIN:reWritedomain] } return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON, IMFPUSH_X_REWRITE_DOMAIN:reWritedomain, IMFPUSH_CLIENT_SECRET:clientSecretHeader] } } func getSubscribedDevicesUrl(devID:String) -> String { var deviceIdUrl:String = getDevicesUrl() deviceIdUrl += FORWARDSLASH deviceIdUrl += devID return deviceIdUrl } func getDevicesUrl() -> String { return getCollectionUrl(collectionName: DEVICES) } func getTagsUrl() -> String { return getCollectionUrl(collectionName: TAGS) } func getSubscriptionsUrl() -> String { return getCollectionUrl(collectionName: SUBSCRIPTIONS) } func getAvailableSubscriptionsUrl(deviceId : String) -> String { var subscriptionURL = getCollectionUrl(collectionName: SUBSCRIPTIONS) subscriptionURL += QUESTIONMARK subscriptionURL += "deviceId=\(deviceId)" return subscriptionURL; } func getUnSubscribetagsUrl() -> String { var unSubscriptionURL = getCollectionUrl(collectionName: SUBSCRIPTIONS) unSubscriptionURL += QUESTIONMARK unSubscriptionURL += IMFPUSH_ACTION_DELETE return unSubscriptionURL } func getUnregisterUrl (deviceId : String) -> String { var deviceUnregisterUrl:String = getDevicesUrl() deviceUnregisterUrl += FORWARDSLASH deviceUnregisterUrl += deviceId return deviceUnregisterUrl } func getSendMessageDeliveryStatus (messageId : String) -> String { var sendMessageDeliveryStatusUrl:String = getCollectionUrl(collectionName: MESSAGES) sendMessageDeliveryStatusUrl += FORWARDSLASH sendMessageDeliveryStatusUrl += messageId return sendMessageDeliveryStatusUrl } internal func getCollectionUrl (collectionName:String) -> String { var collectionUrl:String = pwUrl_ collectionUrl += collectionName return collectionUrl } } #else internal class BMSPushUrlBuilder: NSObject { internal let FORWARDSLASH = "/"; internal let IMFPUSH = "imfpush"; internal let V1 = "v1"; internal let APPS = "apps"; internal let AMPERSAND = "&"; internal let QUESTIONMARK = "?"; internal let SUBZONE = "subzone"; internal let EQUALTO = "="; internal let SUBSCRIPTIONS = "subscriptions"; internal let MESSAGES = "messages"; internal let TAGS = "tags"; internal let DEVICES = "devices"; internal let TAGNAME = "tagName"; internal let DEVICEID = "deviceId"; internal let defaultProtocol = "https"; internal final var pwUrl_ = String() internal final var reWritedomain = String() internal final var clientSecretHeader = String() init(applicationID:String, clientSecret:String) { if !(clientSecret.isEmpty) { clientSecretHeader = clientSecret } if(!BMSPushClient.overrideServerHost.isEmpty){ pwUrl_ += BMSPushClient.overrideServerHost } else { pwUrl_ += defaultProtocol pwUrl_ += "://" if BMSClient.sharedInstance.bluemixRegion?.containsString("stage1-test") == true || BMSClient.sharedInstance.bluemixRegion?.containsString("stage1-dev") == true { pwUrl_ += IMFPUSH pwUrl_ += ".stage1.mybluemix.net" if BMSClient.sharedInstance.bluemixRegion?.containsString("stage1-test") == true { reWritedomain = "stage1-test.ng.bluemix.net" } else{ reWritedomain = "stage1-dev.ng.bluemix.net" } } else{ pwUrl_ += IMFPUSH pwUrl_ += BMSClient.sharedInstance.bluemixRegion! reWritedomain = "" } } pwUrl_ += FORWARDSLASH pwUrl_ += IMFPUSH pwUrl_ += FORWARDSLASH pwUrl_ += V1 pwUrl_ += FORWARDSLASH pwUrl_ += APPS pwUrl_ += FORWARDSLASH pwUrl_ += applicationID pwUrl_ += FORWARDSLASH } func addHeader() -> [String: String] { if reWritedomain.isEmpty { if(clientSecretHeader.isEmpty){ return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON] } return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON, IMFPUSH_CLIENT_SECRET:clientSecretHeader] } else{ if clientSecretHeader.isEmpty { return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON, IMFPUSH_X_REWRITE_DOMAIN:reWritedomain] } return [IMFPUSH_CONTENT_TYPE_KEY:IMFPUSH_CONTENT_TYPE_JSON, IMFPUSH_X_REWRITE_DOMAIN:reWritedomain, IMFPUSH_CLIENT_SECRET:clientSecretHeader] } } func getSubscribedDevicesUrl(devID:String) -> String { var deviceIdUrl:String = getDevicesUrl() deviceIdUrl += FORWARDSLASH deviceIdUrl += devID return deviceIdUrl } func getDevicesUrl() -> String { return getCollectionUrl(DEVICES) } func getTagsUrl() -> String { return getCollectionUrl(TAGS) } func getSubscriptionsUrl() -> String { return getCollectionUrl(SUBSCRIPTIONS) } func getAvailableSubscriptionsUrl(deviceId : String) -> String { var subscriptionURL = getCollectionUrl(SUBSCRIPTIONS) subscriptionURL += QUESTIONMARK subscriptionURL += "deviceId=\(deviceId)" return subscriptionURL; } func getUnSubscribetagsUrl() -> String { var unSubscriptionURL = getCollectionUrl(SUBSCRIPTIONS) unSubscriptionURL += QUESTIONMARK unSubscriptionURL += IMFPUSH_ACTION_DELETE return unSubscriptionURL } func getUnregisterUrl (deviceId : String) -> String { var deviceUnregisterUrl:String = getDevicesUrl() deviceUnregisterUrl += FORWARDSLASH deviceUnregisterUrl += deviceId return deviceUnregisterUrl } func getSendMessageDeliveryStatus (messageId : String) -> String { var sendMessageDeliveryStatusUrl:String = getCollectionUrl(MESSAGES) sendMessageDeliveryStatusUrl += FORWARDSLASH sendMessageDeliveryStatusUrl += messageId return sendMessageDeliveryStatusUrl } internal func getCollectionUrl (collectionName:String) -> String { var collectionUrl:String = pwUrl_ collectionUrl += collectionName return collectionUrl } } #endif
apache-2.0
7d94f5cbf2964ada7440c66cdcf6b22b
34.429907
178
0.540227
6.03983
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+ToArrayTests.swift
13
4606
// // Observable+ToArrayTests.swift // Tests // // Created by Krunoslav Zaher on 4/29/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxTest class ObservableToArrayTest : RxTest { } extension ObservableToArrayTest { func test_ToArrayWithSingleItem_Return() { let scheduler = TestScheduler(initialClock: 0) let xs: TestableObservable<Int> = scheduler.createColdObservable([ next(10, 1), completed(20) ]) let res = scheduler.start { return xs.toArray().map { EquatableArray($0) } } let correctMessages = [ next(220, EquatableArray([1])), completed(220) ] let correctSubscriptions = [ Subscription(200, 220) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_ToArrayWithMultipleItems_Return() { let scheduler = TestScheduler(initialClock: 0) let xs: TestableObservable<Int> = scheduler.createColdObservable([ next(10, 1), next(20, 2), next(30, 3), next(40, 4), completed(50) ]) let res = scheduler.start { return xs.toArray().map { EquatableArray($0) } } let correctMessages = [ next(250, EquatableArray([1,2,3,4])), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_ToArrayWithNoItems_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs: TestableObservable<Int> = scheduler.createColdObservable([ completed(50) ]) let res = scheduler.start { return xs.toArray().map { EquatableArray($0) } } let correctMessages = [ next(250, EquatableArray([Int]())), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_ToArrayWithSingleItem_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1) ]) let res = scheduler.start { return xs.toArray().map { EquatableArray($0) } } let correctMessages: [Recorded<Event<EquatableArray<Int>>>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_ToArrayWithImmediateError_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs: TestableObservable<Int> = scheduler.createColdObservable([ error(10, testError) ]) let res = scheduler.start { return xs.toArray().map { EquatableArray($0) } } let correctMessages = [ error(210, testError, EquatableArray<Int>.self) ] let correctSubscriptions = [ Subscription(200, 210) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func test_ToArrayWithMultipleItems_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs: TestableObservable<Int> = scheduler.createColdObservable([ next(10, 1), next(20, 2), next(30, 3), next(40, 4), error(50, testError) ]) let res = scheduler.start { return xs.toArray().map { EquatableArray($0) } } let correctMessages = [ error(250, testError, EquatableArray<Int>.self) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } #if TRACE_RESOURCES func testToArrayReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).toArray().subscribe() } func testToArrayReleasesResourcesOnError() { _ = Observable<Int>.just(1).toArray().subscribe() } #endif }
mit
cc9761d794076e49135d9e31703b4ed0
24.870787
74
0.57937
5.027293
false
true
false
false
bull-xu-stride/MaterialDesignIcons.Swift
MaterialDesignIconsSwift/Enum.swift
1
91705
// // Enum.swift // MaterialDesignIconsSwift // // Created by Bull Xu on 8/09/2016. // Copyright © 2016 Stride Solutions. All rights reserved. // import Foundation /// version 2.8.94 on 20 Sep 2018 /// https://materialdesignicons.com/history public enum MaterialDesignIcons: String { case accessPoint = "\u{F002}" case accessPointNetwork = "\u{F003}" case account = "\u{F004}" case accountAlert = "\u{F005}" case accountBox = "\u{F006}" case accountBoxMultiple = "\u{F933}" case accountBoxOutline = "\u{F007}" case accountCardDetails = "\u{F5D2}" case accountCheck = "\u{F008}" case accountChild = "\u{FA88}" case accountChildCircle = "\u{FA89}" case accountCircle = "\u{F009}" case accountConvert = "\u{F00A}" case accountDetails = "\u{F631}" case accountEdit = "\u{F6BB}" case accountGroup = "\u{F848}" case accountHeart = "\u{F898}" case accountKey = "\u{F00B}" case accountLocation = "\u{F00C}" case accountMinus = "\u{F00D}" case accountMinusOutline = "\u{FAEB}" case accountMultiple = "\u{F00E}" case accountMultipleCheck = "\u{F8C4}" case accountMultipleMinus = "\u{F5D3}" case accountMultipleOutline = "\u{F00F}" case accountMultiplePlus = "\u{F010}" case accountMultiplePlusOutline = "\u{F7FF}" case accountNetwork = "\u{F011}" case accountOff = "\u{F012}" case accountOutline = "\u{F013}" case accountPlus = "\u{F014}" case accountPlusOutline = "\u{F800}" case accountRemove = "\u{F015}" case accountRemoveOutline = "\u{FAEC}" case accountSearch = "\u{F016}" case accountSearchOutline = "\u{F934}" case accountSettings = "\u{F630}" case accountStar = "\u{F017}" case accountSupervisor = "\u{FA8A}" case accountSupervisorCircle = "\u{FA8B}" case accountSwitch = "\u{F019}" case accusoft = "\u{F849}" case adjust = "\u{F01A}" case adobe = "\u{F935}" case airConditioner = "\u{F01B}" case airballoon = "\u{F01C}" case airplane = "\u{F01D}" case airplaneLanding = "\u{F5D4}" case airplaneOff = "\u{F01E}" case airplaneTakeoff = "\u{F5D5}" case airplay = "\u{F01F}" case airport = "\u{F84A}" case alarm = "\u{F020}" case alarmBell = "\u{F78D}" case alarmCheck = "\u{F021}" case alarmLight = "\u{F78E}" case alarmMultiple = "\u{F022}" case alarmOff = "\u{F023}" case alarmPlus = "\u{F024}" case alarmSnooze = "\u{F68D}" case album = "\u{F025}" case alert = "\u{F026}" case alertBox = "\u{F027}" case alertCircle = "\u{F028}" case alertCircleOutline = "\u{F5D6}" case alertDecagram = "\u{F6BC}" case alertOctagon = "\u{F029}" case alertOctagram = "\u{F766}" case alertOutline = "\u{F02A}" case alien = "\u{F899}" case allInclusive = "\u{F6BD}" case alpha = "\u{F02B}" case alphaA = "\u{41}" case alphaABox = "\u{FAED}" case alphaB = "\u{42}" case alphaBBox = "\u{FAEE}" case alphaC = "\u{43}" case alphaCBox = "\u{FAEF}" case alphaD = "\u{44}" case alphaDBox = "\u{FAF0}" case alphaE = "\u{45}" case alphaEBox = "\u{FAF1}" case alphaF = "\u{46}" case alphaFBox = "\u{FAF2}" case alphaG = "\u{47}" case alphaGBox = "\u{FAF3}" case alphaH = "\u{48}" case alphaHBox = "\u{FAF4}" case alphaI = "\u{49}" case alphaIBox = "\u{FAF5}" case alphaJ = "\u{4A}" case alphaJBox = "\u{FAF6}" case alphaK = "\u{4B}" case alphaKBox = "\u{FAF7}" case alphaL = "\u{4C}" case alphaLBox = "\u{FAF8}" case alphaM = "\u{4D}" case alphaMBox = "\u{FAF9}" case alphaN = "\u{4E}" case alphaNBox = "\u{FAFA}" case alphaO = "\u{4F}" case alphaOBox = "\u{FAFB}" case alphaP = "\u{50}" case alphaPBox = "\u{FAFC}" case alphaQ = "\u{51}" case alphaQBox = "\u{FAFD}" case alphaR = "\u{52}" case alphaRBox = "\u{FAFE}" case alphaS = "\u{53}" case alphaSBox = "\u{FAFF}" case alphaT = "\u{54}" case alphaTBox = "\u{FB00}" case alphaU = "\u{55}" case alphaUBox = "\u{FB01}" case alphaV = "\u{56}" case alphaVBox = "\u{FB02}" case alphaW = "\u{57}" case alphaWBox = "\u{FB03}" case alphaX = "\u{58}" case alphaXBox = "\u{FB04}" case alphaY = "\u{59}" case alphaYBox = "\u{FB05}" case alphaZ = "\u{5A}" case alphaZBox = "\u{FB06}" case alphabetical = "\u{F02C}" case altimeter = "\u{F5D7}" case amazon = "\u{F02D}" case amazonAlexa = "\u{F8C5}" case amazonDrive = "\u{F02E}" case ambulance = "\u{F02F}" case ampersand = "\u{FA8C}" case amplifier = "\u{F030}" case anchor = "\u{F031}" case android = "\u{F032}" case androidAuto = "\u{FA8D}" case androidDebugBridge = "\u{F033}" case androidHead = "\u{F78F}" case androidStudio = "\u{F034}" case angleAcute = "\u{F936}" case angleObtuse = "\u{F937}" case angleRight = "\u{F938}" case angular = "\u{F6B1}" case angularjs = "\u{F6BE}" case animation = "\u{F5D8}" case animationOutline = "\u{FA8E}" case animationPlay = "\u{F939}" case animationPlayOutline = "\u{FA8F}" case anvil = "\u{F89A}" case apple = "\u{F035}" case appleFinder = "\u{F036}" case appleIcloud = "\u{F038}" case appleIos = "\u{F037}" case appleKeyboardCaps = "\u{F632}" case appleKeyboardCommand = "\u{F633}" case appleKeyboardControl = "\u{F634}" case appleKeyboardOption = "\u{F635}" case appleKeyboardShift = "\u{F636}" case appleSafari = "\u{F039}" case application = "\u{F614}" case apps = "\u{F03B}" case arch = "\u{F8C6}" case archive = "\u{F03C}" case arrangeBringForward = "\u{F03D}" case arrangeBringToFront = "\u{F03E}" case arrangeSendBackward = "\u{F03F}" case arrangeSendToBack = "\u{F040}" case arrowAll = "\u{F041}" case arrowBottomLeft = "\u{F042}" case arrowBottomLeftBoldOutline = "\u{F9B6}" case arrowBottomLeftThick = "\u{F9B7}" case arrowBottomRight = "\u{F043}" case arrowBottomRightBoldOutline = "\u{F9B8}" case arrowBottomRightThick = "\u{F9B9}" case arrowCollapse = "\u{F615}" case arrowCollapseAll = "\u{F044}" case arrowCollapseDown = "\u{F791}" case arrowCollapseHorizontal = "\u{F84B}" case arrowCollapseLeft = "\u{F792}" case arrowCollapseRight = "\u{F793}" case arrowCollapseUp = "\u{F794}" case arrowCollapseVertical = "\u{F84C}" case arrowDecision = "\u{F9BA}" case arrowDecisionAuto = "\u{F9BB}" case arrowDecisionAutoOutline = "\u{F9BC}" case arrowDecisionOutline = "\u{F9BD}" case arrowDown = "\u{F045}" case arrowDownBold = "\u{F72D}" case arrowDownBoldBox = "\u{F72E}" case arrowDownBoldBoxOutline = "\u{F72F}" case arrowDownBoldCircle = "\u{F047}" case arrowDownBoldCircleOutline = "\u{F048}" case arrowDownBoldHexagonOutline = "\u{F049}" case arrowDownBoldOutline = "\u{F9BE}" case arrowDownBox = "\u{F6BF}" case arrowDownDropCircle = "\u{F04A}" case arrowDownDropCircleOutline = "\u{F04B}" case arrowDownThick = "\u{F046}" case arrowExpand = "\u{F616}" case arrowExpandAll = "\u{F04C}" case arrowExpandDown = "\u{F795}" case arrowExpandHorizontal = "\u{F84D}" case arrowExpandLeft = "\u{F796}" case arrowExpandRight = "\u{F797}" case arrowExpandUp = "\u{F798}" case arrowExpandVertical = "\u{F84E}" case arrowLeft = "\u{F04D}" case arrowLeftBold = "\u{F730}" case arrowLeftBoldBox = "\u{F731}" case arrowLeftBoldBoxOutline = "\u{F732}" case arrowLeftBoldCircle = "\u{F04F}" case arrowLeftBoldCircleOutline = "\u{F050}" case arrowLeftBoldHexagonOutline = "\u{F051}" case arrowLeftBoldOutline = "\u{F9BF}" case arrowLeftBox = "\u{F6C0}" case arrowLeftDropCircle = "\u{F052}" case arrowLeftDropCircleOutline = "\u{F053}" case arrowLeftRightBoldOutline = "\u{F9C0}" case arrowLeftThick = "\u{F04E}" case arrowRight = "\u{F054}" case arrowRightBold = "\u{F733}" case arrowRightBoldBox = "\u{F734}" case arrowRightBoldBoxOutline = "\u{F735}" case arrowRightBoldCircle = "\u{F056}" case arrowRightBoldCircleOutline = "\u{F057}" case arrowRightBoldHexagonOutline = "\u{F058}" case arrowRightBoldOutline = "\u{F9C1}" case arrowRightBox = "\u{F6C1}" case arrowRightDropCircle = "\u{F059}" case arrowRightDropCircleOutline = "\u{F05A}" case arrowRightThick = "\u{F055}" case arrowSplitHorizontal = "\u{F93A}" case arrowSplitVertical = "\u{F93B}" case arrowTopLeft = "\u{F05B}" case arrowTopLeftBoldOutline = "\u{F9C2}" case arrowTopLeftThick = "\u{F9C3}" case arrowTopRight = "\u{F05C}" case arrowTopRightBoldOutline = "\u{F9C4}" case arrowTopRightThick = "\u{F9C5}" case arrowUp = "\u{F05D}" case arrowUpBold = "\u{F736}" case arrowUpBoldBox = "\u{F737}" case arrowUpBoldBoxOutline = "\u{F738}" case arrowUpBoldCircle = "\u{F05F}" case arrowUpBoldCircleOutline = "\u{F060}" case arrowUpBoldHexagonOutline = "\u{F061}" case arrowUpBoldOutline = "\u{F9C6}" case arrowUpBox = "\u{F6C2}" case arrowUpDownBoldOutline = "\u{F9C7}" case arrowUpDropCircle = "\u{F062}" case arrowUpDropCircleOutline = "\u{F063}" case arrowUpThick = "\u{F05E}" case artist = "\u{F802}" case aspectRatio = "\u{FA23}" case assistant = "\u{F064}" case asterisk = "\u{F6C3}" case at = "\u{F065}" case atlassian = "\u{F803}" case atom = "\u{F767}" case attachment = "\u{F066}" case audioVideo = "\u{F93C}" case audiobook = "\u{F067}" case augmentedReality = "\u{F84F}" case autoFix = "\u{F068}" case autoUpload = "\u{F069}" case autorenew = "\u{F06A}" case avTimer = "\u{F06B}" case axe = "\u{F8C7}" case azure = "\u{F804}" case babel = "\u{FA24}" case baby = "\u{F06C}" case babyBuggy = "\u{F68E}" case backburger = "\u{F06D}" case backspace = "\u{F06E}" case backupRestore = "\u{F06F}" case badminton = "\u{F850}" case balloon = "\u{FA25}" case ballot = "\u{F9C8}" case ballotOutline = "\u{F9C9}" case bandcamp = "\u{F674}" case bank = "\u{F070}" case bankTransfer = "\u{FA26}" case bankTransferIn = "\u{FA27}" case bankTransferOut = "\u{FA28}" case barcode = "\u{F071}" case barcodeScan = "\u{F072}" case barley = "\u{F073}" case barrel = "\u{F074}" case baseball = "\u{F851}" case baseballBat = "\u{F852}" case basecamp = "\u{F075}" case basket = "\u{F076}" case basketFill = "\u{F077}" case basketUnfill = "\u{F078}" case basketball = "\u{F805}" case battery = "\u{F079}" case battery10 = "\u{F07A}" case battery10Bluetooth = "\u{F93D}" case battery20 = "\u{F07B}" case battery20Bluetooth = "\u{F93E}" case battery30 = "\u{F07C}" case battery30Bluetooth = "\u{F93F}" case battery40 = "\u{F07D}" case battery40Bluetooth = "\u{F940}" case battery50 = "\u{F07E}" case battery50Bluetooth = "\u{F941}" case battery60 = "\u{F07F}" case battery60Bluetooth = "\u{F942}" case battery70 = "\u{F080}" case battery70Bluetooth = "\u{F943}" case battery80 = "\u{F081}" case battery80Bluetooth = "\u{F944}" case battery90 = "\u{F082}" case battery90Bluetooth = "\u{F945}" case batteryAlert = "\u{F083}" case batteryAlertBluetooth = "\u{F946}" case batteryBluetooth = "\u{F947}" case batteryBluetoothVariant = "\u{F948}" case batteryCharging = "\u{F084}" case batteryCharging10 = "\u{F89B}" case batteryCharging100 = "\u{F085}" case batteryCharging20 = "\u{F086}" case batteryCharging30 = "\u{F087}" case batteryCharging40 = "\u{F088}" case batteryCharging50 = "\u{F89C}" case batteryCharging60 = "\u{F089}" case batteryCharging70 = "\u{F89D}" case batteryCharging80 = "\u{F08A}" case batteryCharging90 = "\u{F08B}" case batteryChargingOutline = "\u{F89E}" case batteryChargingWireless = "\u{F806}" case batteryChargingWireless10 = "\u{F807}" case batteryChargingWireless20 = "\u{F808}" case batteryChargingWireless30 = "\u{F809}" case batteryChargingWireless40 = "\u{F80A}" case batteryChargingWireless50 = "\u{F80B}" case batteryChargingWireless60 = "\u{F80C}" case batteryChargingWireless70 = "\u{F80D}" case batteryChargingWireless80 = "\u{F80E}" case batteryChargingWireless90 = "\u{F80F}" case batteryChargingWirelessAlert = "\u{F810}" case batteryChargingWirelessOutline = "\u{F811}" case batteryMinus = "\u{F08C}" case batteryNegative = "\u{F08D}" case batteryOutline = "\u{F08E}" case batteryPlus = "\u{F08F}" case batteryPositive = "\u{F090}" case batteryUnknown = "\u{F091}" case batteryUnknownBluetooth = "\u{F949}" case beach = "\u{F092}" case beaker = "\u{F68F}" case beats = "\u{F097}" case bedEmpty = "\u{F89F}" case beer = "\u{F098}" case behance = "\u{F099}" case bell = "\u{F09A}" case bellOff = "\u{F09B}" case bellOffOutline = "\u{FA90}" case bellOutline = "\u{F09C}" case bellPlus = "\u{F09D}" case bellPlusOutline = "\u{FA91}" case bellRing = "\u{F09E}" case bellRingOutline = "\u{F09F}" case bellSleep = "\u{F0A0}" case bellSleepOutline = "\u{FA92}" case beta = "\u{F0A1}" case betamax = "\u{F9CA}" case bible = "\u{F0A2}" case bike = "\u{F0A3}" case bing = "\u{F0A4}" case binoculars = "\u{F0A5}" case bio = "\u{F0A6}" case biohazard = "\u{F0A7}" case bitbucket = "\u{F0A8}" case bitcoin = "\u{F812}" case blackMesa = "\u{F0A9}" case blackberry = "\u{F0AA}" case blender = "\u{F0AB}" case blinds = "\u{F0AC}" case blockHelper = "\u{F0AD}" case blogger = "\u{F0AE}" case bluetooth = "\u{F0AF}" case bluetoothAudio = "\u{F0B0}" case bluetoothConnect = "\u{F0B1}" case bluetoothOff = "\u{F0B2}" case bluetoothSettings = "\u{F0B3}" case bluetoothTransfer = "\u{F0B4}" case blur = "\u{F0B5}" case blurLinear = "\u{F0B6}" case blurOff = "\u{F0B7}" case blurRadial = "\u{F0B8}" case bomb = "\u{F690}" case bombOff = "\u{F6C4}" case bone = "\u{F0B9}" case book = "\u{F0BA}" case bookLock = "\u{F799}" case bookLockOpen = "\u{F79A}" case bookMinus = "\u{F5D9}" case bookMultiple = "\u{F0BB}" case bookMultipleMinus = "\u{FA93}" case bookMultiplePlus = "\u{FA94}" case bookMultipleRemove = "\u{FA95}" case bookMultipleVariant = "\u{F0BC}" case bookOpen = "\u{F0BD}" case bookOpenPageVariant = "\u{F5DA}" case bookOpenVariant = "\u{F0BE}" case bookPlus = "\u{F5DB}" case bookRemove = "\u{FA96}" case bookVariant = "\u{F0BF}" case bookmark = "\u{F0C0}" case bookmarkCheck = "\u{F0C1}" case bookmarkMinus = "\u{F9CB}" case bookmarkMinusOutline = "\u{F9CC}" case bookmarkMusic = "\u{F0C2}" case bookmarkOff = "\u{F9CD}" case bookmarkOffOutline = "\u{F9CE}" case bookmarkOutline = "\u{F0C3}" case bookmarkPlus = "\u{F0C5}" case bookmarkPlusOutline = "\u{F0C4}" case bookmarkRemove = "\u{F0C6}" case boombox = "\u{F5DC}" case bootstrap = "\u{F6C5}" case borderAll = "\u{F0C7}" case borderAllVariant = "\u{F8A0}" case borderBottom = "\u{F0C8}" case borderBottomVariant = "\u{F8A1}" case borderColor = "\u{F0C9}" case borderHorizontal = "\u{F0CA}" case borderInside = "\u{F0CB}" case borderLeft = "\u{F0CC}" case borderLeftVariant = "\u{F8A2}" case borderNone = "\u{F0CD}" case borderNoneVariant = "\u{F8A3}" case borderOutside = "\u{F0CE}" case borderRight = "\u{F0CF}" case borderRightVariant = "\u{F8A4}" case borderStyle = "\u{F0D0}" case borderTop = "\u{F0D1}" case borderTopVariant = "\u{F8A5}" case borderVertical = "\u{F0D2}" case bottleWine = "\u{F853}" case bowTie = "\u{F677}" case bowl = "\u{F617}" case bowling = "\u{F0D3}" case box = "\u{F0D4}" case boxCutter = "\u{F0D5}" case boxShadow = "\u{F637}" case braille = "\u{F9CF}" case brain = "\u{F9D0}" case bridge = "\u{F618}" case briefcase = "\u{F0D6}" case briefcaseCheck = "\u{F0D7}" case briefcaseDownload = "\u{F0D8}" case briefcaseEdit = "\u{FA97}" case briefcaseMinus = "\u{FA29}" case briefcaseOutline = "\u{F813}" case briefcasePlus = "\u{FA2A}" case briefcaseRemove = "\u{FA2B}" case briefcaseSearch = "\u{FA2C}" case briefcaseUpload = "\u{F0D9}" case brightness1 = "\u{F0DA}" case brightness2 = "\u{F0DB}" case brightness3 = "\u{F0DC}" case brightness4 = "\u{F0DD}" case brightness5 = "\u{F0DE}" case brightness6 = "\u{F0DF}" case brightness7 = "\u{F0E0}" case brightnessAuto = "\u{F0E1}" case broom = "\u{F0E2}" case brush = "\u{F0E3}" case buddhism = "\u{F94A}" case buffer = "\u{F619}" case bug = "\u{F0E4}" case bugCheck = "\u{FA2D}" case bugCheckOutline = "\u{FA2E}" case bugOutline = "\u{FA2F}" case bulldozer = "\u{FB07}" case bulletinBoard = "\u{F0E5}" case bullhorn = "\u{F0E6}" case bullhornOutline = "\u{FB08}" case bullseye = "\u{F5DD}" case bullseyeArrow = "\u{F8C8}" case bus = "\u{F0E7}" case busAlert = "\u{FA98}" case busArticulatedEnd = "\u{F79B}" case busArticulatedFront = "\u{F79C}" case busClock = "\u{F8C9}" case busDoubleDecker = "\u{F79D}" case busSchool = "\u{F79E}" case busSide = "\u{F79F}" case cached = "\u{F0E8}" case cake = "\u{F0E9}" case cakeLayered = "\u{F0EA}" case cakeVariant = "\u{F0EB}" case calculator = "\u{F0EC}" case calculatorVariant = "\u{FA99}" case calendar = "\u{F0ED}" case calendarAlert = "\u{FA30}" case calendarBlank = "\u{F0EE}" case calendarCheck = "\u{F0EF}" case calendarClock = "\u{F0F0}" case calendarEdit = "\u{F8A6}" case calendarExport = "\u{FB09}" case calendarHeart = "\u{F9D1}" case calendarImport = "\u{FB0A}" case calendarMultiple = "\u{F0F1}" case calendarMultipleCheck = "\u{F0F2}" case calendarMultiselect = "\u{FA31}" case calendarPlus = "\u{F0F3}" case calendarQuestion = "\u{F691}" case calendarRange = "\u{F678}" case calendarRemove = "\u{F0F4}" case calendarSearch = "\u{F94B}" case calendarStar = "\u{F9D2}" case calendarText = "\u{F0F5}" case calendarToday = "\u{F0F6}" case calendarWeek = "\u{FA32}" case calendarWeekBegin = "\u{FA33}" case callMade = "\u{F0F7}" case callMerge = "\u{F0F8}" case callMissed = "\u{F0F9}" case callReceived = "\u{F0FA}" case callSplit = "\u{F0FB}" case camcorder = "\u{F0FC}" case camcorderBox = "\u{F0FD}" case camcorderBoxOff = "\u{F0FE}" case camcorderOff = "\u{F0FF}" case camera = "\u{F100}" case cameraAccount = "\u{F8CA}" case cameraBurst = "\u{F692}" case cameraEnhance = "\u{F101}" case cameraFront = "\u{F102}" case cameraFrontVariant = "\u{F103}" case cameraGopro = "\u{F7A0}" case cameraImage = "\u{F8CB}" case cameraIris = "\u{F104}" case cameraMeteringCenter = "\u{F7A1}" case cameraMeteringMatrix = "\u{F7A2}" case cameraMeteringPartial = "\u{F7A3}" case cameraMeteringSpot = "\u{F7A4}" case cameraOff = "\u{F5DF}" case cameraPartyMode = "\u{F105}" case cameraRear = "\u{F106}" case cameraRearVariant = "\u{F107}" case cameraSwitch = "\u{F108}" case cameraTimer = "\u{F109}" case cancel = "\u{F739}" case candle = "\u{F5E2}" case candycane = "\u{F10A}" case cannabis = "\u{F7A5}" case capsLock = "\u{FA9A}" case car = "\u{F10B}" case carBattery = "\u{F10C}" case carConnected = "\u{F10D}" case carConvertible = "\u{F7A6}" case carEstate = "\u{F7A7}" case carHatchback = "\u{F7A8}" case carLimousine = "\u{F8CC}" case carPickup = "\u{F7A9}" case carSide = "\u{F7AA}" case carSports = "\u{F7AB}" case carWash = "\u{F10E}" case caravan = "\u{F7AC}" case cards = "\u{F638}" case cardsClub = "\u{F8CD}" case cardsDiamond = "\u{F8CE}" case cardsHeart = "\u{F8CF}" case cardsOutline = "\u{F639}" case cardsPlayingOutline = "\u{F63A}" case cardsSpade = "\u{F8D0}" case cardsVariant = "\u{F6C6}" case carrot = "\u{F10F}" case cart = "\u{F110}" case cartOff = "\u{F66B}" case cartOutline = "\u{F111}" case cartPlus = "\u{F112}" case caseSensitiveAlt = "\u{F113}" case cash = "\u{F114}" case cash100 = "\u{F115}" case cashMultiple = "\u{F116}" case cashRefund = "\u{FA9B}" case cashUsd = "\u{F117}" case cassette = "\u{F9D3}" case cast = "\u{F118}" case castConnected = "\u{F119}" case castOff = "\u{F789}" case castle = "\u{F11A}" case cat = "\u{F11B}" case cctv = "\u{F7AD}" case ceilingLight = "\u{F768}" case cellphone = "\u{F11C}" case cellphoneAndroid = "\u{F11D}" case cellphoneArrowDown = "\u{F9D4}" case cellphoneBasic = "\u{F11E}" case cellphoneDock = "\u{F11F}" case cellphoneErase = "\u{F94C}" case cellphoneIphone = "\u{F120}" case cellphoneKey = "\u{F94D}" case cellphoneLink = "\u{F121}" case cellphoneLinkOff = "\u{F122}" case cellphoneLock = "\u{F94E}" case cellphoneMessage = "\u{F8D2}" case cellphoneOff = "\u{F94F}" case cellphoneScreenshot = "\u{FA34}" case cellphoneSettings = "\u{F123}" case cellphoneSettingsVariant = "\u{F950}" case cellphoneSound = "\u{F951}" case cellphoneText = "\u{F8D1}" case cellphoneWireless = "\u{F814}" case certificate = "\u{F124}" case chairSchool = "\u{F125}" case chartArc = "\u{F126}" case chartAreaspline = "\u{F127}" case chartBar = "\u{F128}" case chartBarStacked = "\u{F769}" case chartBubble = "\u{F5E3}" case chartDonut = "\u{F7AE}" case chartDonutVariant = "\u{F7AF}" case chartGantt = "\u{F66C}" case chartHistogram = "\u{F129}" case chartLine = "\u{F12A}" case chartLineStacked = "\u{F76A}" case chartLineVariant = "\u{F7B0}" case chartMultiline = "\u{F8D3}" case chartPie = "\u{F12B}" case chartScatterplotHexbin = "\u{F66D}" case chartTimeline = "\u{F66E}" case check = "\u{F12C}" case checkAll = "\u{F12D}" case checkCircle = "\u{F5E0}" case checkCircleOutline = "\u{F5E1}" case checkDecagram = "\u{F790}" case checkOutline = "\u{F854}" case checkbook = "\u{FA9C}" case checkboxBlank = "\u{F12E}" case checkboxBlankCircle = "\u{F12F}" case checkboxBlankCircleOutline = "\u{F130}" case checkboxBlankOutline = "\u{F131}" case checkboxIntermediate = "\u{F855}" case checkboxMarked = "\u{F132}" case checkboxMarkedCircle = "\u{F133}" case checkboxMarkedCircleOutline = "\u{F134}" case checkboxMarkedOutline = "\u{F135}" case checkboxMultipleBlank = "\u{F136}" case checkboxMultipleBlankCircle = "\u{F63B}" case checkboxMultipleBlankCircleOutline = "\u{F63C}" case checkboxMultipleBlankOutline = "\u{F137}" case checkboxMultipleMarked = "\u{F138}" case checkboxMultipleMarkedCircle = "\u{F63D}" case checkboxMultipleMarkedCircleOutline = "\u{F63E}" case checkboxMultipleMarkedOutline = "\u{F139}" case checkerboard = "\u{F13A}" case chemicalWeapon = "\u{F13B}" case chessBishop = "\u{F85B}" case chessKing = "\u{F856}" case chessKnight = "\u{F857}" case chessPawn = "\u{F858}" case chessQueen = "\u{F859}" case chessRook = "\u{F85A}" case chevronDoubleDown = "\u{F13C}" case chevronDoubleLeft = "\u{F13D}" case chevronDoubleRight = "\u{F13E}" case chevronDoubleUp = "\u{F13F}" case chevronDown = "\u{F140}" case chevronDownBox = "\u{F9D5}" case chevronDownBoxOutline = "\u{F9D6}" case chevronDownCircle = "\u{FB0B}" case chevronDownCircleOutline = "\u{FB0C}" case chevronLeft = "\u{F141}" case chevronLeftBox = "\u{F9D7}" case chevronLeftBoxOutline = "\u{F9D8}" case chevronLeftCircle = "\u{FB0D}" case chevronLeftCircleOutline = "\u{FB0E}" case chevronRight = "\u{F142}" case chevronRightBox = "\u{F9D9}" case chevronRightBoxOutline = "\u{F9DA}" case chevronRightCircle = "\u{FB0F}" case chevronRightCircleOutline = "\u{FB10}" case chevronUp = "\u{F143}" case chevronUpBox = "\u{F9DB}" case chevronUpBoxOutline = "\u{F9DC}" case chevronUpCircle = "\u{FB11}" case chevronUpCircleOutline = "\u{FB12}" case chiliHot = "\u{F7B1}" case chiliMedium = "\u{F7B2}" case chiliMild = "\u{F7B3}" case chip = "\u{F61A}" case christianity = "\u{F952}" case church = "\u{F144}" case circle = "\u{F764}" case circleEditOutline = "\u{F8D4}" case circleMedium = "\u{F9DD}" case circleOutline = "\u{F765}" case circleSlice1 = "\u{FA9D}" case circleSlice2 = "\u{FA9E}" case circleSlice3 = "\u{FA9F}" case circleSlice4 = "\u{FAA0}" case circleSlice5 = "\u{FAA1}" case circleSlice6 = "\u{FAA2}" case circleSlice7 = "\u{FAA3}" case circleSlice8 = "\u{FAA4}" case circleSmall = "\u{F9DE}" case ciscoWebex = "\u{F145}" case city = "\u{F146}" case cityVariant = "\u{FA35}" case cityVariantOutline = "\u{FA36}" case clipboard = "\u{F147}" case clipboardAccount = "\u{F148}" case clipboardAlert = "\u{F149}" case clipboardArrowDown = "\u{F14A}" case clipboardArrowLeft = "\u{F14B}" case clipboardCheck = "\u{F14C}" case clipboardCheckOutline = "\u{F8A7}" case clipboardFlow = "\u{F6C7}" case clipboardOutline = "\u{F14D}" case clipboardPlus = "\u{F750}" case clipboardPulse = "\u{F85C}" case clipboardPulseOutline = "\u{F85D}" case clipboardText = "\u{F14E}" case clipboardTextOutline = "\u{FA37}" case clippy = "\u{F14F}" case clock = "\u{F953}" case clockAlert = "\u{F954}" case clockAlertOutline = "\u{F5CE}" case clockEnd = "\u{F151}" case clockFast = "\u{F152}" case clockIn = "\u{F153}" case clockOut = "\u{F154}" case clockOutline = "\u{F150}" case clockStart = "\u{F155}" case close = "\u{F156}" case closeBox = "\u{F157}" case closeBoxOutline = "\u{F158}" case closeCircle = "\u{F159}" case closeCircleOutline = "\u{F15A}" case closeNetwork = "\u{F15B}" case closeOctagon = "\u{F15C}" case closeOctagonOutline = "\u{F15D}" case closeOutline = "\u{F6C8}" case closedCaption = "\u{F15E}" case cloud = "\u{F15F}" case cloudAlert = "\u{F9DF}" case cloudBraces = "\u{F7B4}" case cloudCheck = "\u{F160}" case cloudCircle = "\u{F161}" case cloudDownload = "\u{F162}" case cloudOffOutline = "\u{F164}" case cloudOutline = "\u{F163}" case cloudPrint = "\u{F165}" case cloudPrintOutline = "\u{F166}" case cloudQuestion = "\u{FA38}" case cloudSearch = "\u{F955}" case cloudSearchOutline = "\u{F956}" case cloudSync = "\u{F63F}" case cloudTags = "\u{F7B5}" case cloudUpload = "\u{F167}" case clover = "\u{F815}" case codeArray = "\u{F168}" case codeBraces = "\u{F169}" case codeBrackets = "\u{F16A}" case codeEqual = "\u{F16B}" case codeGreaterThan = "\u{F16C}" case codeGreaterThanOrEqual = "\u{F16D}" case codeLessThan = "\u{F16E}" case codeLessThanOrEqual = "\u{F16F}" case codeNotEqual = "\u{F170}" case codeNotEqualVariant = "\u{F171}" case codeParentheses = "\u{F172}" case codeString = "\u{F173}" case codeTags = "\u{F174}" case codeTagsCheck = "\u{F693}" case codepen = "\u{F175}" case coffee = "\u{F176}" case coffeeOutline = "\u{F6C9}" case coffeeToGo = "\u{F177}" case cogs = "\u{F8D5}" case coin = "\u{F178}" case coins = "\u{F694}" case collage = "\u{F640}" case collapseAll = "\u{FAA5}" case collapseAllOutline = "\u{FAA6}" case colorHelper = "\u{F179}" case comment = "\u{F17A}" case commentAccount = "\u{F17B}" case commentAccountOutline = "\u{F17C}" case commentAlert = "\u{F17D}" case commentAlertOutline = "\u{F17E}" case commentArrowLeft = "\u{F9E0}" case commentArrowLeftOutline = "\u{F9E1}" case commentArrowRight = "\u{F9E2}" case commentArrowRightOutline = "\u{F9E3}" case commentCheck = "\u{F17F}" case commentCheckOutline = "\u{F180}" case commentEye = "\u{FA39}" case commentEyeOutline = "\u{FA3A}" case commentMultiple = "\u{F85E}" case commentMultipleOutline = "\u{F181}" case commentOutline = "\u{F182}" case commentPlus = "\u{F9E4}" case commentPlusOutline = "\u{F183}" case commentProcessing = "\u{F184}" case commentProcessingOutline = "\u{F185}" case commentQuestion = "\u{F816}" case commentQuestionOutline = "\u{F186}" case commentRemove = "\u{F5DE}" case commentRemoveOutline = "\u{F187}" case commentSearch = "\u{FA3B}" case commentSearchOutline = "\u{FA3C}" case commentText = "\u{F188}" case commentTextMultiple = "\u{F85F}" case commentTextMultipleOutline = "\u{F860}" case commentTextOutline = "\u{F189}" case compare = "\u{F18A}" case compass = "\u{F18B}" case compassOutline = "\u{F18C}" case console = "\u{F18D}" case consoleLine = "\u{F7B6}" case consoleNetwork = "\u{F8A8}" case contactMail = "\u{F18E}" case contacts = "\u{F6CA}" case contain = "\u{FA3D}" case containEnd = "\u{FA3E}" case containStart = "\u{FA3F}" case contentCopy = "\u{F18F}" case contentCut = "\u{F190}" case contentDuplicate = "\u{F191}" case contentPaste = "\u{F192}" case contentSave = "\u{F193}" case contentSaveAll = "\u{F194}" case contentSaveOutline = "\u{F817}" case contentSaveSettings = "\u{F61B}" case contentSaveSettingsOutline = "\u{FB13}" case contrast = "\u{F195}" case contrastBox = "\u{F196}" case contrastCircle = "\u{F197}" case cookie = "\u{F198}" case copyright = "\u{F5E6}" case cordova = "\u{F957}" case corn = "\u{F7B7}" case counter = "\u{F199}" case cow = "\u{F19A}" case crane = "\u{F861}" case creation = "\u{F1C9}" case creditCard = "\u{F19B}" case creditCardMultiple = "\u{F19C}" case creditCardOff = "\u{F5E4}" case creditCardPlus = "\u{F675}" case creditCardRefund = "\u{FAA7}" case creditCardScan = "\u{F19D}" case creditCardSettings = "\u{F8D6}" case crop = "\u{F19E}" case cropFree = "\u{F19F}" case cropLandscape = "\u{F1A0}" case cropPortrait = "\u{F1A1}" case cropRotate = "\u{F695}" case cropSquare = "\u{F1A2}" case crosshairs = "\u{F1A3}" case crosshairsGps = "\u{F1A4}" case crown = "\u{F1A5}" case cryengine = "\u{F958}" case crystalBall = "\u{FB14}" case cube = "\u{F1A6}" case cubeOutline = "\u{F1A7}" case cubeSend = "\u{F1A8}" case cubeUnfolded = "\u{F1A9}" case cup = "\u{F1AA}" case cupOff = "\u{F5E5}" case cupWater = "\u{F1AB}" case cupcake = "\u{F959}" case curling = "\u{F862}" case currencyBdt = "\u{F863}" case currencyBtc = "\u{F1AC}" case currencyChf = "\u{F7B8}" case currencyCny = "\u{F7B9}" case currencyEth = "\u{F7BA}" case currencyEur = "\u{F1AD}" case currencyGbp = "\u{F1AE}" case currencyInr = "\u{F1AF}" case currencyJpy = "\u{F7BB}" case currencyKrw = "\u{F7BC}" case currencyKzt = "\u{F864}" case currencyNgn = "\u{F1B0}" case currencyPhp = "\u{F9E5}" case currencyRub = "\u{F1B1}" case currencySign = "\u{F7BD}" case currencyTry = "\u{F1B2}" case currencyTwd = "\u{F7BE}" case currencyUsd = "\u{F1B3}" case currencyUsdOff = "\u{F679}" case currentAc = "\u{F95A}" case currentDc = "\u{F95B}" case cursorDefault = "\u{F1B4}" case cursorDefaultOutline = "\u{F1B5}" case cursorMove = "\u{F1B6}" case cursorPointer = "\u{F1B7}" case cursorText = "\u{F5E7}" case database = "\u{F1B8}" case databaseCheck = "\u{FAA8}" case databaseExport = "\u{F95D}" case databaseImport = "\u{F95C}" case databaseLock = "\u{FAA9}" case databaseMinus = "\u{F1B9}" case databasePlus = "\u{F1BA}" case databaseSearch = "\u{F865}" case deathStar = "\u{F8D7}" case deathStarVariant = "\u{F8D8}" case debian = "\u{F8D9}" case debugStepInto = "\u{F1BB}" case debugStepOut = "\u{F1BC}" case debugStepOver = "\u{F1BD}" case decagram = "\u{F76B}" case decagramOutline = "\u{F76C}" case decimalDecrease = "\u{F1BE}" case decimalIncrease = "\u{F1BF}" case delete = "\u{F1C0}" case deleteCircle = "\u{F682}" case deleteEmpty = "\u{F6CB}" case deleteForever = "\u{F5E8}" case deleteOutline = "\u{F9E6}" case deleteRestore = "\u{F818}" case deleteSweep = "\u{F5E9}" case deleteVariant = "\u{F1C1}" case delta = "\u{F1C2}" case deskLamp = "\u{F95E}" case deskphone = "\u{F1C3}" case desktopClassic = "\u{F7BF}" case desktopMac = "\u{F1C4}" case desktopMacDashboard = "\u{F9E7}" case desktopTower = "\u{F1C5}" case desktopTowerMonitor = "\u{FAAA}" case details = "\u{F1C6}" case developerBoard = "\u{F696}" case deviantart = "\u{F1C7}" case dialpad = "\u{F61C}" case diamond = "\u{F1C8}" case dice1 = "\u{F1CA}" case dice2 = "\u{F1CB}" case dice3 = "\u{F1CC}" case dice4 = "\u{F1CD}" case dice5 = "\u{F1CE}" case dice6 = "\u{F1CF}" case diceD10 = "\u{F76E}" case diceD12 = "\u{F866}" case diceD20 = "\u{F5EA}" case diceD4 = "\u{F5EB}" case diceD6 = "\u{F5EC}" case diceD8 = "\u{F5ED}" case diceMultiple = "\u{F76D}" case dictionary = "\u{F61D}" case dipSwitch = "\u{F7C0}" case directions = "\u{F1D0}" case directionsFork = "\u{F641}" case disc = "\u{F5EE}" case discAlert = "\u{F1D1}" case discPlayer = "\u{F95F}" case discord = "\u{F66F}" case dishwasher = "\u{FAAB}" case disqus = "\u{F1D2}" case disqusOutline = "\u{F1D3}" case division = "\u{F1D4}" case divisionBox = "\u{F1D5}" case dlna = "\u{FA40}" case dna = "\u{F683}" case dns = "\u{F1D6}" case doNotDisturb = "\u{F697}" case doNotDisturbOff = "\u{F698}" case docker = "\u{F867}" case doctor = "\u{FA41}" case dog = "\u{FA42}" case dogService = "\u{FAAC}" case dogSide = "\u{FA43}" case dolby = "\u{F6B2}" case domain = "\u{F1D7}" case donkey = "\u{F7C1}" case door = "\u{F819}" case doorClosed = "\u{F81A}" case doorOpen = "\u{F81B}" case doorbellVideo = "\u{F868}" case dotNet = "\u{FAAD}" case dotsHorizontal = "\u{F1D8}" case dotsHorizontalCircle = "\u{F7C2}" case dotsVertical = "\u{F1D9}" case dotsVerticalCircle = "\u{F7C3}" case douban = "\u{F699}" case download = "\u{F1DA}" case downloadMultiple = "\u{F9E8}" case downloadNetwork = "\u{F6F3}" case drag = "\u{F1DB}" case dragHorizontal = "\u{F1DC}" case dragVertical = "\u{F1DD}" case drawing = "\u{F1DE}" case drawingBox = "\u{F1DF}" case dribbble = "\u{F1E0}" case dribbbleBox = "\u{F1E1}" case drone = "\u{F1E2}" case dropbox = "\u{F1E3}" case drupal = "\u{F1E4}" case duck = "\u{F1E5}" case dumbbell = "\u{F1E6}" case earHearing = "\u{F7C4}" case earHearingOff = "\u{FA44}" case earth = "\u{F1E7}" case earthBox = "\u{F6CC}" case earthBoxOff = "\u{F6CD}" case earthOff = "\u{F1E8}" case edge = "\u{F1E9}" case egg = "\u{FAAE}" case eggEaster = "\u{FAAF}" case eightTrack = "\u{F9E9}" case eject = "\u{F1EA}" case elephant = "\u{F7C5}" case elevationDecline = "\u{F1EB}" case elevationRise = "\u{F1EC}" case elevator = "\u{F1ED}" case email = "\u{F1EE}" case emailAlert = "\u{F6CE}" case emailCheck = "\u{FAB0}" case emailCheckOutline = "\u{FAB1}" case emailLock = "\u{F1F1}" case emailOpen = "\u{F1EF}" case emailOpenOutline = "\u{F5EF}" case emailOutline = "\u{F1F0}" case emailPlus = "\u{F9EA}" case emailPlusOutline = "\u{F9EB}" case emailSearch = "\u{F960}" case emailSearchOutline = "\u{F961}" case emailVariant = "\u{F5F0}" case ember = "\u{FB15}" case emby = "\u{F6B3}" case emoticon = "\u{F1F2}" case emoticonCool = "\u{F1F3}" case emoticonDead = "\u{F69A}" case emoticonDevil = "\u{F1F4}" case emoticonExcited = "\u{F69B}" case emoticonHappy = "\u{F1F5}" case emoticonNeutral = "\u{F1F6}" case emoticonPoop = "\u{F1F7}" case emoticonSad = "\u{F1F8}" case emoticonTongue = "\u{F1F9}" case engine = "\u{F1FA}" case engineOff = "\u{FA45}" case engineOffOutline = "\u{FA46}" case engineOutline = "\u{F1FB}" case equal = "\u{F1FC}" case equalBox = "\u{F1FD}" case eraser = "\u{F1FE}" case eraserVariant = "\u{F642}" case escalator = "\u{F1FF}" case et = "\u{FAB2}" case ethereum = "\u{F869}" case ethernet = "\u{F200}" case ethernetCable = "\u{F201}" case ethernetCableOff = "\u{F202}" case etsy = "\u{F203}" case evStation = "\u{F5F1}" case eventbrite = "\u{F7C6}" case evernote = "\u{F204}" case exclamation = "\u{F205}" case exitRun = "\u{FA47}" case exitToApp = "\u{F206}" case expandAll = "\u{FAB3}" case expandAllOutline = "\u{FAB4}" case exponent = "\u{F962}" case exponentBox = "\u{F963}" case export = "\u{F207}" case eye = "\u{F208}" case eyeOff = "\u{F209}" case eyeOffOutline = "\u{F6D0}" case eyeOutline = "\u{F6CF}" case eyePlus = "\u{F86A}" case eyePlusOutline = "\u{F86B}" case eyeSettings = "\u{F86C}" case eyeSettingsOutline = "\u{F86D}" case eyedropper = "\u{F20A}" case eyedropperVariant = "\u{F20B}" case face = "\u{F643}" case faceProfile = "\u{F644}" case facebook = "\u{F20C}" case facebookBox = "\u{F20D}" case facebookMessenger = "\u{F20E}" case facebookWorkplace = "\u{FB16}" case factory = "\u{F20F}" case fan = "\u{F210}" case fanOff = "\u{F81C}" case fastForward = "\u{F211}" case fastForwardOutline = "\u{F6D1}" case fax = "\u{F212}" case feather = "\u{F6D2}" case featureSearch = "\u{FA48}" case featureSearchOutline = "\u{FA49}" case fedora = "\u{F8DA}" case ferry = "\u{F213}" case file = "\u{F214}" case fileAccount = "\u{F73A}" case fileAlert = "\u{FA4A}" case fileAlertOutline = "\u{FA4B}" case fileCabinet = "\u{FAB5}" case fileChart = "\u{F215}" case fileCheck = "\u{F216}" case fileCloud = "\u{F217}" case fileCompare = "\u{F8A9}" case fileDelimited = "\u{F218}" case fileDocument = "\u{F219}" case fileDocumentBox = "\u{F21A}" case fileDocumentBoxMultiple = "\u{FAB6}" case fileDocumentBoxMultipleOutline = "\u{FAB7}" case fileDocumentBoxOutline = "\u{F9EC}" case fileDocumentOutline = "\u{F9ED}" case fileDownload = "\u{F964}" case fileDownloadOutline = "\u{F965}" case fileExcel = "\u{F21B}" case fileExcelBox = "\u{F21C}" case fileExport = "\u{F21D}" case fileFind = "\u{F21E}" case fileHidden = "\u{F613}" case fileImage = "\u{F21F}" case fileImport = "\u{F220}" case fileLock = "\u{F221}" case fileMove = "\u{FAB8}" case fileMultiple = "\u{F222}" case fileMusic = "\u{F223}" case fileOutline = "\u{F224}" case filePdf = "\u{F225}" case filePdfBox = "\u{F226}" case filePercent = "\u{F81D}" case filePlus = "\u{F751}" case filePowerpoint = "\u{F227}" case filePowerpointBox = "\u{F228}" case filePresentationBox = "\u{F229}" case fileQuestion = "\u{F86E}" case fileReplace = "\u{FB17}" case fileReplaceOutline = "\u{FB18}" case fileRestore = "\u{F670}" case fileSend = "\u{F22A}" case fileTree = "\u{F645}" case fileUndo = "\u{F8DB}" case fileUpload = "\u{FA4C}" case fileUploadOutline = "\u{FA4D}" case fileVideo = "\u{F22B}" case fileWord = "\u{F22C}" case fileWordBox = "\u{F22D}" case fileXml = "\u{F22E}" case film = "\u{F22F}" case filmstrip = "\u{F230}" case filmstripOff = "\u{F231}" case filter = "\u{F232}" case filterOutline = "\u{F233}" case filterRemove = "\u{F234}" case filterRemoveOutline = "\u{F235}" case filterVariant = "\u{F236}" case finance = "\u{F81E}" case findReplace = "\u{F6D3}" case fingerprint = "\u{F237}" case fire = "\u{F238}" case fireTruck = "\u{F8AA}" case firebase = "\u{F966}" case firefox = "\u{F239}" case fish = "\u{F23A}" case flag = "\u{F23B}" case flagCheckered = "\u{F23C}" case flagOutline = "\u{F23D}" case flagTriangle = "\u{F23F}" case flagVariant = "\u{F240}" case flagVariantOutline = "\u{F23E}" case flash = "\u{F241}" case flashAuto = "\u{F242}" case flashCircle = "\u{F81F}" case flashOff = "\u{F243}" case flashOutline = "\u{F6D4}" case flashRedEye = "\u{F67A}" case flashlight = "\u{F244}" case flashlightOff = "\u{F245}" case flask = "\u{F093}" case flaskEmpty = "\u{F094}" case flaskEmptyOutline = "\u{F095}" case flaskOutline = "\u{F096}" case flattr = "\u{F246}" case flipToBack = "\u{F247}" case flipToFront = "\u{F248}" case floorLamp = "\u{F8DC}" case floorPlan = "\u{F820}" case floppy = "\u{F249}" case floppyVariant = "\u{F9EE}" case flower = "\u{F24A}" case flowerOutline = "\u{F9EF}" case flowerTulip = "\u{F9F0}" case flowerTulipOutline = "\u{F9F1}" case folder = "\u{F24B}" case folderAccount = "\u{F24C}" case folderClock = "\u{FAB9}" case folderClockOutline = "\u{FABA}" case folderDownload = "\u{F24D}" case folderEdit = "\u{F8DD}" case folderGoogleDrive = "\u{F24E}" case folderImage = "\u{F24F}" case folderKey = "\u{F8AB}" case folderKeyNetwork = "\u{F8AC}" case folderLock = "\u{F250}" case folderLockOpen = "\u{F251}" case folderMove = "\u{F252}" case folderMultiple = "\u{F253}" case folderMultipleImage = "\u{F254}" case folderMultipleOutline = "\u{F255}" case folderNetwork = "\u{F86F}" case folderOpen = "\u{F76F}" case folderOutline = "\u{F256}" case folderPlus = "\u{F257}" case folderRemove = "\u{F258}" case folderSearch = "\u{F967}" case folderSearchOutline = "\u{F968}" case folderStar = "\u{F69C}" case folderUpload = "\u{F259}" case fontAwesome = "\u{F03A}" case food = "\u{F25A}" case foodApple = "\u{F25B}" case foodCroissant = "\u{F7C7}" case foodForkDrink = "\u{F5F2}" case foodOff = "\u{F5F3}" case foodVariant = "\u{F25C}" case football = "\u{F25D}" case footballAustralian = "\u{F25E}" case footballHelmet = "\u{F25F}" case forklift = "\u{F7C8}" case formatAlignBottom = "\u{F752}" case formatAlignCenter = "\u{F260}" case formatAlignJustify = "\u{F261}" case formatAlignLeft = "\u{F262}" case formatAlignMiddle = "\u{F753}" case formatAlignRight = "\u{F263}" case formatAlignTop = "\u{F754}" case formatAnnotationMinus = "\u{FABB}" case formatAnnotationPlus = "\u{F646}" case formatBold = "\u{F264}" case formatClear = "\u{F265}" case formatColorFill = "\u{F266}" case formatColorText = "\u{F69D}" case formatColumns = "\u{F8DE}" case formatFloatCenter = "\u{F267}" case formatFloatLeft = "\u{F268}" case formatFloatNone = "\u{F269}" case formatFloatRight = "\u{F26A}" case formatFont = "\u{F6D5}" case formatFontSizeDecrease = "\u{F9F2}" case formatFontSizeIncrease = "\u{F9F3}" case formatHeader1 = "\u{F26B}" case formatHeader2 = "\u{F26C}" case formatHeader3 = "\u{F26D}" case formatHeader4 = "\u{F26E}" case formatHeader5 = "\u{F26F}" case formatHeader6 = "\u{F270}" case formatHeaderDecrease = "\u{F271}" case formatHeaderEqual = "\u{F272}" case formatHeaderIncrease = "\u{F273}" case formatHeaderPound = "\u{F274}" case formatHorizontalAlignCenter = "\u{F61E}" case formatHorizontalAlignLeft = "\u{F61F}" case formatHorizontalAlignRight = "\u{F620}" case formatIndentDecrease = "\u{F275}" case formatIndentIncrease = "\u{F276}" case formatItalic = "\u{F277}" case formatLetterCase = "\u{FB19}" case formatLetterCaseLower = "\u{FB1A}" case formatLetterCaseUpper = "\u{FB1B}" case formatLineSpacing = "\u{F278}" case formatLineStyle = "\u{F5C8}" case formatLineWeight = "\u{F5C9}" case formatListBulleted = "\u{F279}" case formatListBulletedType = "\u{F27A}" case formatListCheckbox = "\u{F969}" case formatListChecks = "\u{F755}" case formatListNumbers = "\u{F27B}" case formatPageBreak = "\u{F6D6}" case formatPaint = "\u{F27C}" case formatParagraph = "\u{F27D}" case formatPilcrow = "\u{F6D7}" case formatQuoteClose = "\u{F27E}" case formatQuoteOpen = "\u{F756}" case formatRotate90 = "\u{F6A9}" case formatSection = "\u{F69E}" case formatSize = "\u{F27F}" case formatStrikethrough = "\u{F280}" case formatStrikethroughVariant = "\u{F281}" case formatSubscript = "\u{F282}" case formatSuperscript = "\u{F283}" case formatText = "\u{F284}" case formatTextdirectionLToR = "\u{F285}" case formatTextdirectionRToL = "\u{F286}" case formatTitle = "\u{F5F4}" case formatUnderline = "\u{F287}" case formatVerticalAlignBottom = "\u{F621}" case formatVerticalAlignCenter = "\u{F622}" case formatVerticalAlignTop = "\u{F623}" case formatWrapInline = "\u{F288}" case formatWrapSquare = "\u{F289}" case formatWrapTight = "\u{F28A}" case formatWrapTopBottom = "\u{F28B}" case forum = "\u{F28C}" case forumOutline = "\u{F821}" case forward = "\u{F28D}" case fountain = "\u{F96A}" case foursquare = "\u{F28E}" case freebsd = "\u{F8DF}" case fridge = "\u{F28F}" case fridgeFilled = "\u{F290}" case fridgeFilledBottom = "\u{F291}" case fridgeFilledTop = "\u{F292}" case fuel = "\u{F7C9}" case fullscreen = "\u{F293}" case fullscreenExit = "\u{F294}" case function = "\u{F295}" case functionVariant = "\u{F870}" case gamepad = "\u{F296}" case gamepadVariant = "\u{F297}" case garage = "\u{F6D8}" case garageAlert = "\u{F871}" case garageOpen = "\u{F6D9}" case gasCylinder = "\u{F647}" case gasStation = "\u{F298}" case gate = "\u{F299}" case gateAnd = "\u{F8E0}" case gateNand = "\u{F8E1}" case gateNor = "\u{F8E2}" case gateNot = "\u{F8E3}" case gateOr = "\u{F8E4}" case gateXnor = "\u{F8E5}" case gateXor = "\u{F8E6}" case gauge = "\u{F29A}" case gaugeEmpty = "\u{F872}" case gaugeFull = "\u{F873}" case gaugeLow = "\u{F874}" case gavel = "\u{F29B}" case genderFemale = "\u{F29C}" case genderMale = "\u{F29D}" case genderMaleFemale = "\u{F29E}" case genderTransgender = "\u{F29F}" case gentoo = "\u{F8E7}" case gesture = "\u{F7CA}" case gestureDoubleTap = "\u{F73B}" case gesturePinch = "\u{FABC}" case gestureSpread = "\u{FABD}" case gestureSwipeDown = "\u{F73C}" case gestureSwipeHorizontal = "\u{FABE}" case gestureSwipeLeft = "\u{F73D}" case gestureSwipeRight = "\u{F73E}" case gestureSwipeUp = "\u{F73F}" case gestureSwipeVertical = "\u{FABF}" case gestureTap = "\u{F740}" case gestureTwoDoubleTap = "\u{F741}" case gestureTwoTap = "\u{F742}" case ghost = "\u{F2A0}" case ghostOff = "\u{F9F4}" case gift = "\u{F2A1}" case git = "\u{F2A2}" case githubBox = "\u{F2A3}" case githubCircle = "\u{F2A4}" case githubFace = "\u{F6DA}" case glassCocktail = "\u{F356}" case glassFlute = "\u{F2A5}" case glassMug = "\u{F2A6}" case glassStange = "\u{F2A7}" case glassTulip = "\u{F2A8}" case glassWine = "\u{F875}" case glassdoor = "\u{F2A9}" case glasses = "\u{F2AA}" case globeModel = "\u{F8E8}" case gmail = "\u{F2AB}" case gnome = "\u{F2AC}" case golf = "\u{F822}" case gondola = "\u{F685}" case google = "\u{F2AD}" case googleAllo = "\u{F801}" case googleAnalytics = "\u{F7CB}" case googleAssistant = "\u{F7CC}" case googleCardboard = "\u{F2AE}" case googleChrome = "\u{F2AF}" case googleCircles = "\u{F2B0}" case googleCirclesCommunities = "\u{F2B1}" case googleCirclesExtended = "\u{F2B2}" case googleCirclesGroup = "\u{F2B3}" case googleController = "\u{F2B4}" case googleControllerOff = "\u{F2B5}" case googleDrive = "\u{F2B6}" case googleEarth = "\u{F2B7}" case googleFit = "\u{F96B}" case googleGlass = "\u{F2B8}" case googleHangouts = "\u{F2C9}" case googleHome = "\u{F823}" case googleKeep = "\u{F6DB}" case googleLens = "\u{F9F5}" case googleMaps = "\u{F5F5}" case googleNearby = "\u{F2B9}" case googlePages = "\u{F2BA}" case googlePhotos = "\u{F6DC}" case googlePhysicalWeb = "\u{F2BB}" case googlePlay = "\u{F2BC}" case googlePlus = "\u{F2BD}" case googlePlusBox = "\u{F2BE}" case googleSpreadsheet = "\u{F9F6}" case googleTranslate = "\u{F2BF}" case googleWallet = "\u{F2C0}" case gpu = "\u{F8AD}" case gradient = "\u{F69F}" case graphql = "\u{F876}" case greasePencil = "\u{F648}" case greaterThan = "\u{F96C}" case greaterThanOrEqual = "\u{F96D}" case grid = "\u{F2C1}" case gridLarge = "\u{F757}" case gridOff = "\u{F2C2}" case group = "\u{F2C3}" case guitarAcoustic = "\u{F770}" case guitarElectric = "\u{F2C4}" case guitarPick = "\u{F2C5}" case guitarPickOutline = "\u{F2C6}" case guyFawkesMask = "\u{F824}" case hackernews = "\u{F624}" case hail = "\u{FAC0}" case hamburger = "\u{F684}" case hammer = "\u{F8E9}" case hand = "\u{FA4E}" case handOkay = "\u{FA4F}" case handPeace = "\u{FA50}" case handPeaceVariant = "\u{FA51}" case handPointingDown = "\u{FA52}" case handPointingLeft = "\u{FA53}" case handPointingRight = "\u{F2C7}" case handPointingUp = "\u{FA54}" case hanger = "\u{F2C8}" case hardHat = "\u{F96E}" case harddisk = "\u{F2CA}" case headphones = "\u{F2CB}" case headphonesBluetooth = "\u{F96F}" case headphonesBox = "\u{F2CC}" case headphonesOff = "\u{F7CD}" case headphonesSettings = "\u{F2CD}" case headset = "\u{F2CE}" case headsetDock = "\u{F2CF}" case headsetOff = "\u{F2D0}" case heart = "\u{F2D1}" case heartBox = "\u{F2D2}" case heartBoxOutline = "\u{F2D3}" case heartBroken = "\u{F2D4}" case heartCircle = "\u{F970}" case heartCircleOutline = "\u{F971}" case heartHalf = "\u{F6DE}" case heartHalfFull = "\u{F6DD}" case heartHalfOutline = "\u{F6DF}" case heartMultiple = "\u{FA55}" case heartMultipleOutline = "\u{FA56}" case heartOff = "\u{F758}" case heartOutline = "\u{F2D5}" case heartPulse = "\u{F5F6}" case helicopter = "\u{FAC1}" case help = "\u{F2D6}" case helpBox = "\u{F78A}" case helpCircle = "\u{F2D7}" case helpCircleOutline = "\u{F625}" case helpNetwork = "\u{F6F4}" case hexagon = "\u{F2D8}" case hexagonMultiple = "\u{F6E0}" case hexagonOutline = "\u{F2D9}" case hexagonSlice1 = "\u{FAC2}" case hexagonSlice2 = "\u{FAC3}" case hexagonSlice3 = "\u{FAC4}" case hexagonSlice4 = "\u{FAC5}" case hexagonSlice5 = "\u{FAC6}" case hexagonSlice6 = "\u{FAC7}" case hexagram = "\u{FAC8}" case hexagramOutline = "\u{FAC9}" case highDefinition = "\u{F7CE}" case highDefinitionBox = "\u{F877}" case highway = "\u{F5F7}" case hinduism = "\u{F972}" case history = "\u{F2DA}" case hockeyPuck = "\u{F878}" case hockeySticks = "\u{F879}" case hololens = "\u{F2DB}" case home = "\u{F2DC}" case homeAccount = "\u{F825}" case homeAlert = "\u{F87A}" case homeAssistant = "\u{F7CF}" case homeAutomation = "\u{F7D0}" case homeCircle = "\u{F7D1}" case homeCurrencyUsd = "\u{F8AE}" case homeHeart = "\u{F826}" case homeLock = "\u{F8EA}" case homeLockOpen = "\u{F8EB}" case homeMapMarker = "\u{F5F8}" case homeMinus = "\u{F973}" case homeModern = "\u{F2DD}" case homeOutline = "\u{F6A0}" case homePlus = "\u{F974}" case homeVariant = "\u{F2DE}" case hook = "\u{F6E1}" case hookOff = "\u{F6E2}" case hops = "\u{F2DF}" case horseshoe = "\u{FA57}" case hospital = "\u{F2E0}" case hospitalBuilding = "\u{F2E1}" case hospitalMarker = "\u{F2E2}" case hotTub = "\u{F827}" case hotel = "\u{F2E3}" case houzz = "\u{F2E4}" case houzzBox = "\u{F2E5}" case hulu = "\u{F828}" case human = "\u{F2E6}" case humanChild = "\u{F2E7}" case humanFemale = "\u{F649}" case humanFemaleBoy = "\u{FA58}" case humanFemaleFemale = "\u{FA59}" case humanFemaleGirl = "\u{FA5A}" case humanGreeting = "\u{F64A}" case humanHandsdown = "\u{F64B}" case humanHandsup = "\u{F64C}" case humanMale = "\u{F64D}" case humanMaleBoy = "\u{FA5B}" case humanMaleFemale = "\u{F2E8}" case humanMaleGirl = "\u{FA5C}" case humanMaleMale = "\u{FA5D}" case humanPregnant = "\u{F5CF}" case humbleBundle = "\u{F743}" case iceCream = "\u{F829}" case image = "\u{F2E9}" case imageAlbum = "\u{F2EA}" case imageArea = "\u{F2EB}" case imageAreaClose = "\u{F2EC}" case imageBroken = "\u{F2ED}" case imageBrokenVariant = "\u{F2EE}" case imageFilter = "\u{F2EF}" case imageFilterBlackWhite = "\u{F2F0}" case imageFilterCenterFocus = "\u{F2F1}" case imageFilterCenterFocusWeak = "\u{F2F2}" case imageFilterDrama = "\u{F2F3}" case imageFilterFrames = "\u{F2F4}" case imageFilterHdr = "\u{F2F5}" case imageFilterNone = "\u{F2F6}" case imageFilterTiltShift = "\u{F2F7}" case imageFilterVintage = "\u{F2F8}" case imageMove = "\u{F9F7}" case imageMultiple = "\u{F2F9}" case imageOff = "\u{F82A}" case imageOutline = "\u{F975}" case imagePlus = "\u{F87B}" case imageSearch = "\u{F976}" case imageSearchOutline = "\u{F977}" case `import` = "\u{F2FA}" case inbox = "\u{F686}" case inboxArrowDown = "\u{F2FB}" case inboxArrowUp = "\u{F3D1}" case inboxMultiple = "\u{F8AF}" case incognito = "\u{F5F9}" case infinity = "\u{F6E3}" case information = "\u{F2FC}" case informationOutline = "\u{F2FD}" case informationVariant = "\u{F64E}" case instagram = "\u{F2FE}" case instapaper = "\u{F2FF}" case internetExplorer = "\u{F300}" case invertColors = "\u{F301}" case ip = "\u{FA5E}" case ipNetwork = "\u{FA5F}" case islam = "\u{F978}" case itunes = "\u{F676}" case jeepney = "\u{F302}" case jira = "\u{F303}" case jquery = "\u{F87C}" case jsfiddle = "\u{F304}" case json = "\u{F626}" case judaism = "\u{F979}" case karate = "\u{F82B}" case keg = "\u{F305}" case kettle = "\u{F5FA}" case key = "\u{F306}" case keyChange = "\u{F307}" case keyMinus = "\u{F308}" case keyPlus = "\u{F309}" case keyRemove = "\u{F30A}" case keyVariant = "\u{F30B}" case keyboard = "\u{F30C}" case keyboardBackspace = "\u{F30D}" case keyboardCaps = "\u{F30E}" case keyboardClose = "\u{F30F}" case keyboardOff = "\u{F310}" case keyboardOutline = "\u{F97A}" case keyboardReturn = "\u{F311}" case keyboardSettings = "\u{F9F8}" case keyboardSettingsOutline = "\u{F9F9}" case keyboardTab = "\u{F312}" case keyboardVariant = "\u{F313}" case kickstarter = "\u{F744}" case knife = "\u{F9FA}" case knifeMilitary = "\u{F9FB}" case kodi = "\u{F314}" case label = "\u{F315}" case labelOff = "\u{FACA}" case labelOffOutline = "\u{FACB}" case labelOutline = "\u{F316}" case labelVariant = "\u{FACC}" case labelVariantOutline = "\u{FACD}" case ladybug = "\u{F82C}" case lambda = "\u{F627}" case lamp = "\u{F6B4}" case lan = "\u{F317}" case lanConnect = "\u{F318}" case lanDisconnect = "\u{F319}" case lanPending = "\u{F31A}" case languageC = "\u{F671}" case languageCpp = "\u{F672}" case languageCsharp = "\u{F31B}" case languageCss3 = "\u{F31C}" case languageGo = "\u{F7D2}" case languageHtml5 = "\u{F31D}" case languageJava = "\u{FB1C}" case languageJavascript = "\u{F31E}" case languageLua = "\u{F8B0}" case languagePhp = "\u{F31F}" case languagePython = "\u{F320}" case languagePythonText = "\u{F321}" case languageR = "\u{F7D3}" case languageRubyOnRails = "\u{FACE}" case languageSwift = "\u{F6E4}" case languageTypescript = "\u{F6E5}" case laptop = "\u{F322}" case laptopChromebook = "\u{F323}" case laptopMac = "\u{F324}" case laptopOff = "\u{F6E6}" case laptopWindows = "\u{F325}" case laravel = "\u{FACF}" case lastfm = "\u{F326}" case lastpass = "\u{F446}" case launch = "\u{F327}" case lavaLamp = "\u{F7D4}" case layers = "\u{F328}" case layersOff = "\u{F329}" case layersOffOutline = "\u{F9FC}" case layersOutline = "\u{F9FD}" case leadPencil = "\u{F64F}" case leaf = "\u{F32A}" case ledOff = "\u{F32B}" case ledOn = "\u{F32C}" case ledOutline = "\u{F32D}" case ledStrip = "\u{F7D5}" case ledVariantOff = "\u{F32E}" case ledVariantOn = "\u{F32F}" case ledVariantOutline = "\u{F330}" case lessThan = "\u{F97B}" case lessThanOrEqual = "\u{F97C}" case library = "\u{F331}" case libraryBooks = "\u{F332}" case libraryMusic = "\u{F333}" case libraryPlus = "\u{F334}" case lifebuoy = "\u{F87D}" case lightSwitch = "\u{F97D}" case lightbulb = "\u{F335}" case lightbulbOn = "\u{F6E7}" case lightbulbOnOutline = "\u{F6E8}" case lightbulbOutline = "\u{F336}" case lighthouse = "\u{F9FE}" case lighthouseOn = "\u{F9FF}" case link = "\u{F337}" case linkOff = "\u{F338}" case linkVariant = "\u{F339}" case linkVariantOff = "\u{F33A}" case linkedin = "\u{F33B}" case linkedinBox = "\u{F33C}" case linux = "\u{F33D}" case linuxMint = "\u{F8EC}" case litecoin = "\u{FA60}" case loading = "\u{F771}" case lock = "\u{F33E}" case lockAlert = "\u{F8ED}" case lockClock = "\u{F97E}" case lockOpen = "\u{F33F}" case lockOpenOutline = "\u{F340}" case lockOutline = "\u{F341}" case lockPattern = "\u{F6E9}" case lockPlus = "\u{F5FB}" case lockQuestion = "\u{F8EE}" case lockReset = "\u{F772}" case lockSmart = "\u{F8B1}" case locker = "\u{F7D6}" case lockerMultiple = "\u{F7D7}" case login = "\u{F342}" case loginVariant = "\u{F5FC}" case logout = "\u{F343}" case logoutVariant = "\u{F5FD}" case looks = "\u{F344}" case loop = "\u{F6EA}" case loupe = "\u{F345}" case lumx = "\u{F346}" case lyft = "\u{FB1D}" case magnet = "\u{F347}" case magnetOn = "\u{F348}" case magnify = "\u{F349}" case magnifyClose = "\u{F97F}" case magnifyMinus = "\u{F34A}" case magnifyMinusCursor = "\u{FA61}" case magnifyMinusOutline = "\u{F6EB}" case magnifyPlus = "\u{F34B}" case magnifyPlusCursor = "\u{FA62}" case magnifyPlusOutline = "\u{F6EC}" case mailRu = "\u{F34C}" case mailbox = "\u{F6ED}" case map = "\u{F34D}" case mapLegend = "\u{FA00}" case mapMarker = "\u{F34E}" case mapMarkerCircle = "\u{F34F}" case mapMarkerDistance = "\u{F8EF}" case mapMarkerMinus = "\u{F650}" case mapMarkerMultiple = "\u{F350}" case mapMarkerOff = "\u{F351}" case mapMarkerOutline = "\u{F7D8}" case mapMarkerPlus = "\u{F651}" case mapMarkerRadius = "\u{F352}" case mapMinus = "\u{F980}" case mapOutline = "\u{F981}" case mapPlus = "\u{F982}" case mapSearch = "\u{F983}" case mapSearchOutline = "\u{F984}" case margin = "\u{F353}" case markdown = "\u{F354}" case marker = "\u{F652}" case markerCheck = "\u{F355}" case mastodon = "\u{FAD0}" case mastodonVariant = "\u{FAD1}" case materialDesign = "\u{F985}" case materialUi = "\u{F357}" case mathCompass = "\u{F358}" case matrix = "\u{F628}" case maxcdn = "\u{F359}" case medal = "\u{F986}" case medicalBag = "\u{F6EE}" case medium = "\u{F35A}" case meetup = "\u{FAD2}" case memory = "\u{F35B}" case menu = "\u{F35C}" case menuDown = "\u{F35D}" case menuDownOutline = "\u{F6B5}" case menuLeft = "\u{F35E}" case menuLeftOutline = "\u{FA01}" case menuRight = "\u{F35F}" case menuRightOutline = "\u{FA02}" case menuSwap = "\u{FA63}" case menuSwapOutline = "\u{FA64}" case menuUp = "\u{F360}" case menuUpOutline = "\u{F6B6}" case message = "\u{F361}" case messageAlert = "\u{F362}" case messageAlertOutline = "\u{FA03}" case messageBulleted = "\u{F6A1}" case messageBulletedOff = "\u{F6A2}" case messageDraw = "\u{F363}" case messageImage = "\u{F364}" case messageOutline = "\u{F365}" case messagePlus = "\u{F653}" case messageProcessing = "\u{F366}" case messageReply = "\u{F367}" case messageReplyText = "\u{F368}" case messageSettings = "\u{F6EF}" case messageSettingsVariant = "\u{F6F0}" case messageText = "\u{F369}" case messageTextOutline = "\u{F36A}" case messageVideo = "\u{F36B}" case meteor = "\u{F629}" case metronome = "\u{F7D9}" case metronomeTick = "\u{F7DA}" case microSd = "\u{F7DB}" case microphone = "\u{F36C}" case microphoneMinus = "\u{F8B2}" case microphoneOff = "\u{F36D}" case microphoneOutline = "\u{F36E}" case microphonePlus = "\u{F8B3}" case microphoneSettings = "\u{F36F}" case microphoneVariant = "\u{F370}" case microphoneVariantOff = "\u{F371}" case microscope = "\u{F654}" case microsoft = "\u{F372}" case microsoftDynamics = "\u{F987}" case midi = "\u{F8F0}" case midiPort = "\u{F8F1}" case minecraft = "\u{F373}" case miniSd = "\u{FA04}" case minidisc = "\u{FA05}" case minus = "\u{F374}" case minusBox = "\u{F375}" case minusBoxOutline = "\u{F6F1}" case minusCircle = "\u{F376}" case minusCircleOutline = "\u{F377}" case minusNetwork = "\u{F378}" case mixcloud = "\u{F62A}" case mixedReality = "\u{F87E}" case mixer = "\u{F7DC}" case monitor = "\u{F379}" case monitorCellphone = "\u{F988}" case monitorCellphoneStar = "\u{F989}" case monitorDashboard = "\u{FA06}" case monitorMultiple = "\u{F37A}" case more = "\u{F37B}" case motorbike = "\u{F37C}" case mouse = "\u{F37D}" case mouseBluetooth = "\u{F98A}" case mouseOff = "\u{F37E}" case mouseVariant = "\u{F37F}" case mouseVariantOff = "\u{F380}" case moveResize = "\u{F655}" case moveResizeVariant = "\u{F656}" case movie = "\u{F381}" case movieRoll = "\u{F7DD}" case muffin = "\u{F98B}" case multiplication = "\u{F382}" case multiplicationBox = "\u{F383}" case mushroom = "\u{F7DE}" case mushroomOutline = "\u{F7DF}" case music = "\u{F759}" case musicBox = "\u{F384}" case musicBoxOutline = "\u{F385}" case musicCircle = "\u{F386}" case musicCircleOutline = "\u{FAD3}" case musicNote = "\u{F387}" case musicNoteBluetooth = "\u{F5FE}" case musicNoteBluetoothOff = "\u{F5FF}" case musicNoteEighth = "\u{F388}" case musicNoteHalf = "\u{F389}" case musicNoteOff = "\u{F38A}" case musicNoteQuarter = "\u{F38B}" case musicNoteSixteenth = "\u{F38C}" case musicNoteWhole = "\u{F38D}" case musicOff = "\u{F75A}" case nas = "\u{F8F2}" case nativescript = "\u{F87F}" case nature = "\u{F38E}" case naturePeople = "\u{F38F}" case navigation = "\u{F390}" case nearMe = "\u{F5CD}" case needle = "\u{F391}" case netflix = "\u{F745}" case network = "\u{F6F2}" case networkStrength1 = "\u{F8F3}" case networkStrength1Alert = "\u{F8F4}" case networkStrength2 = "\u{F8F5}" case networkStrength2Alert = "\u{F8F6}" case networkStrength3 = "\u{F8F7}" case networkStrength3Alert = "\u{F8F8}" case networkStrength4 = "\u{F8F9}" case networkStrength4Alert = "\u{F8FA}" case networkStrengthOff = "\u{F8FB}" case networkStrengthOffOutline = "\u{F8FC}" case networkStrengthOutline = "\u{F8FD}" case newBox = "\u{F394}" case newspaper = "\u{F395}" case nfc = "\u{F396}" case nfcTap = "\u{F397}" case nfcVariant = "\u{F398}" case ninja = "\u{F773}" case nintendoSwitch = "\u{F7E0}" case nodejs = "\u{F399}" case notEqual = "\u{F98C}" case notEqualVariant = "\u{F98D}" case note = "\u{F39A}" case noteMultiple = "\u{F6B7}" case noteMultipleOutline = "\u{F6B8}" case noteOutline = "\u{F39B}" case notePlus = "\u{F39C}" case notePlusOutline = "\u{F39D}" case noteText = "\u{F39E}" case notebook = "\u{F82D}" case notificationClearAll = "\u{F39F}" case npm = "\u{F6F6}" case npmVariant = "\u{F98E}" case npmVariantOutline = "\u{F98F}" case nuke = "\u{F6A3}" case null = "\u{F7E1}" case numeric = "\u{F3A0}" case numeric0 = "\u{30}" case numeric0Box = "\u{F3A1}" case numeric0BoxMultipleOutline = "\u{F3A2}" case numeric0BoxOutline = "\u{F3A3}" case numeric1 = "\u{31}" case numeric1Box = "\u{F3A4}" case numeric1BoxMultipleOutline = "\u{F3A5}" case numeric1BoxOutline = "\u{F3A6}" case numeric2 = "\u{32}" case numeric2Box = "\u{F3A7}" case numeric2BoxMultipleOutline = "\u{F3A8}" case numeric2BoxOutline = "\u{F3A9}" case numeric3 = "\u{33}" case numeric3Box = "\u{F3AA}" case numeric3BoxMultipleOutline = "\u{F3AB}" case numeric3BoxOutline = "\u{F3AC}" case numeric4 = "\u{34}" case numeric4Box = "\u{F3AD}" case numeric4BoxMultipleOutline = "\u{F3AE}" case numeric4BoxOutline = "\u{F3AF}" case numeric5 = "\u{35}" case numeric5Box = "\u{F3B0}" case numeric5BoxMultipleOutline = "\u{F3B1}" case numeric5BoxOutline = "\u{F3B2}" case numeric6 = "\u{36}" case numeric6Box = "\u{F3B3}" case numeric6BoxMultipleOutline = "\u{F3B4}" case numeric6BoxOutline = "\u{F3B5}" case numeric7 = "\u{37}" case numeric7Box = "\u{F3B6}" case numeric7BoxMultipleOutline = "\u{F3B7}" case numeric7BoxOutline = "\u{F3B8}" case numeric8 = "\u{38}" case numeric8Box = "\u{F3B9}" case numeric8BoxMultipleOutline = "\u{F3BA}" case numeric8BoxOutline = "\u{F3BB}" case numeric9 = "\u{39}" case numeric9Box = "\u{F3BC}" case numeric9BoxMultipleOutline = "\u{F3BD}" case numeric9BoxOutline = "\u{F3BE}" case numeric9PlusBox = "\u{F3BF}" case numeric9PlusBoxMultipleOutline = "\u{F3C0}" case numeric9PlusBoxOutline = "\u{F3C1}" case nut = "\u{F6F7}" case nutrition = "\u{F3C2}" case oar = "\u{F67B}" case octagon = "\u{F3C3}" case octagonOutline = "\u{F3C4}" case octagram = "\u{F6F8}" case octagramOutline = "\u{F774}" case odnoklassniki = "\u{F3C5}" case office = "\u{F3C6}" case officeBuilding = "\u{F990}" case oil = "\u{F3C7}" case oilTemperature = "\u{F3C8}" case omega = "\u{F3C9}" case onedrive = "\u{F3CA}" case onenote = "\u{F746}" case onepassword = "\u{F880}" case opacity = "\u{F5CC}" case openInApp = "\u{F3CB}" case openInNew = "\u{F3CC}" case openid = "\u{F3CD}" case opera = "\u{F3CE}" case orbit = "\u{F018}" case origin = "\u{FB2B}" case ornament = "\u{F3CF}" case ornamentVariant = "\u{F3D0}" case owl = "\u{F3D2}" case package = "\u{F3D3}" case packageDown = "\u{F3D4}" case packageUp = "\u{F3D5}" case packageVariant = "\u{F3D6}" case packageVariantClosed = "\u{F3D7}" case pageFirst = "\u{F600}" case pageLast = "\u{F601}" case pageLayoutBody = "\u{F6F9}" case pageLayoutFooter = "\u{F6FA}" case pageLayoutHeader = "\u{F6FB}" case pageLayoutSidebarLeft = "\u{F6FC}" case pageLayoutSidebarRight = "\u{F6FD}" case palette = "\u{F3D8}" case paletteAdvanced = "\u{F3D9}" case paletteSwatch = "\u{F8B4}" case panda = "\u{F3DA}" case pandora = "\u{F3DB}" case panorama = "\u{F3DC}" case panoramaFisheye = "\u{F3DD}" case panoramaHorizontal = "\u{F3DE}" case panoramaVertical = "\u{F3DF}" case panoramaWideAngle = "\u{F3E0}" case paperCutVertical = "\u{F3E1}" case paperclip = "\u{F3E2}" case parking = "\u{F3E3}" case passport = "\u{F7E2}" case patreon = "\u{F881}" case pause = "\u{F3E4}" case pauseCircle = "\u{F3E5}" case pauseCircleOutline = "\u{F3E6}" case pauseOctagon = "\u{F3E7}" case pauseOctagonOutline = "\u{F3E8}" case paw = "\u{F3E9}" case pawOff = "\u{F657}" case paypal = "\u{F882}" case peace = "\u{F883}" case pen = "\u{F3EA}" case pencil = "\u{F3EB}" case pencilBox = "\u{F3EC}" case pencilBoxOutline = "\u{F3ED}" case pencilCircle = "\u{F6FE}" case pencilCircleOutline = "\u{F775}" case pencilLock = "\u{F3EE}" case pencilOff = "\u{F3EF}" case pentagon = "\u{F6FF}" case pentagonOutline = "\u{F700}" case percent = "\u{F3F0}" case periodicTable = "\u{F8B5}" case periodicTableCo2 = "\u{F7E3}" case periscope = "\u{F747}" case pharmacy = "\u{F3F1}" case phone = "\u{F3F2}" case phoneBluetooth = "\u{F3F3}" case phoneClassic = "\u{F602}" case phoneForward = "\u{F3F4}" case phoneHangup = "\u{F3F5}" case phoneInTalk = "\u{F3F6}" case phoneIncoming = "\u{F3F7}" case phoneLock = "\u{F3F8}" case phoneLog = "\u{F3F9}" case phoneMinus = "\u{F658}" case phoneMissed = "\u{F3FA}" case phoneOutgoing = "\u{F3FB}" case phonePaused = "\u{F3FC}" case phonePlus = "\u{F659}" case phoneReturn = "\u{F82E}" case phoneRotateLandscape = "\u{F884}" case phoneRotatePortrait = "\u{F885}" case phoneSettings = "\u{F3FD}" case phoneVoip = "\u{F3FE}" case pi = "\u{F3FF}" case piBox = "\u{F400}" case piano = "\u{F67C}" case pickaxe = "\u{F8B6}" case pier = "\u{F886}" case pierCrane = "\u{F887}" case pig = "\u{F401}" case pill = "\u{F402}" case pillar = "\u{F701}" case pin = "\u{F403}" case pinOff = "\u{F404}" case pinOffOutline = "\u{F92F}" case pinOutline = "\u{F930}" case pineTree = "\u{F405}" case pineTreeBox = "\u{F406}" case pinterest = "\u{F407}" case pinterestBox = "\u{F408}" case pinwheel = "\u{FAD4}" case pinwheelOutline = "\u{FAD5}" case pipe = "\u{F7E4}" case pipeDisconnected = "\u{F7E5}" case pipeLeak = "\u{F888}" case pirate = "\u{FA07}" case pistol = "\u{F702}" case piston = "\u{F889}" case pizza = "\u{F409}" case planeShield = "\u{F6BA}" case play = "\u{F40A}" case playBoxOutline = "\u{F40B}" case playCircle = "\u{F40C}" case playCircleOutline = "\u{F40D}" case playNetwork = "\u{F88A}" case playPause = "\u{F40E}" case playProtectedContent = "\u{F40F}" case playSpeed = "\u{F8FE}" case playlistCheck = "\u{F5C7}" case playlistEdit = "\u{F8FF}" case playlistMinus = "\u{F410}" case playlistPlay = "\u{F411}" case playlistPlus = "\u{F412}" case playlistRemove = "\u{F413}" case playstation = "\u{F414}" case plex = "\u{F6B9}" case plus = "\u{F415}" case plusBox = "\u{F416}" case plusBoxOutline = "\u{F703}" case plusCircle = "\u{F417}" case plusCircleMultipleOutline = "\u{F418}" case plusCircleOutline = "\u{F419}" case plusMinus = "\u{F991}" case plusMinusBox = "\u{F992}" case plusNetwork = "\u{F41A}" case plusOne = "\u{F41B}" case plusOutline = "\u{F704}" case pocket = "\u{F41C}" case podcast = "\u{F993}" case pokeball = "\u{F41D}" case pokemonGo = "\u{FA08}" case pokerChip = "\u{F82F}" case polaroid = "\u{F41E}" case poll = "\u{F41F}" case pollBox = "\u{F420}" case polymer = "\u{F421}" case pool = "\u{F606}" case popcorn = "\u{F422}" case pot = "\u{F65A}" case potMix = "\u{F65B}" case pound = "\u{F423}" case poundBox = "\u{F424}" case power = "\u{F425}" case powerCycle = "\u{F900}" case powerOff = "\u{F901}" case powerOn = "\u{F902}" case powerPlug = "\u{F6A4}" case powerPlugOff = "\u{F6A5}" case powerSettings = "\u{F426}" case powerSleep = "\u{F903}" case powerSocket = "\u{F427}" case powerSocketAu = "\u{F904}" case powerSocketEu = "\u{F7E6}" case powerSocketUk = "\u{F7E7}" case powerSocketUs = "\u{F7E8}" case powerStandby = "\u{F905}" case powershell = "\u{FA09}" case prescription = "\u{F705}" case presentation = "\u{F428}" case presentationPlay = "\u{F429}" case printer = "\u{F42A}" case printer3d = "\u{F42B}" case printerAlert = "\u{F42C}" case printerSettings = "\u{F706}" case printerWireless = "\u{FA0A}" case priorityHigh = "\u{F603}" case priorityLow = "\u{F604}" case professionalHexagon = "\u{F42D}" case progressCheck = "\u{F994}" case progressClock = "\u{F995}" case progressDownload = "\u{F996}" case progressUpload = "\u{F997}" case projector = "\u{F42E}" case projectorScreen = "\u{F42F}" case publish = "\u{F6A6}" case pulse = "\u{F430}" case puzzle = "\u{F431}" case puzzleOutline = "\u{FA65}" case qi = "\u{F998}" case qqchat = "\u{F605}" case qrcode = "\u{F432}" case qrcodeEdit = "\u{F8B7}" case qrcodeScan = "\u{F433}" case quadcopter = "\u{F434}" case qualityHigh = "\u{F435}" case qualityLow = "\u{FA0B}" case qualityMedium = "\u{FA0C}" case quicktime = "\u{F436}" case rabbit = "\u{F906}" case radar = "\u{F437}" case radiator = "\u{F438}" case radiatorDisabled = "\u{FAD6}" case radiatorOff = "\u{FAD7}" case radio = "\u{F439}" case radioHandheld = "\u{F43A}" case radioTower = "\u{F43B}" case radioactive = "\u{F43C}" case radioboxBlank = "\u{F43D}" case radioboxMarked = "\u{F43E}" case raspberrypi = "\u{F43F}" case rayEnd = "\u{F440}" case rayEndArrow = "\u{F441}" case rayStart = "\u{F442}" case rayStartArrow = "\u{F443}" case rayStartEnd = "\u{F444}" case rayVertex = "\u{F445}" case react = "\u{F707}" case read = "\u{F447}" case receipt = "\u{F449}" case record = "\u{F44A}" case recordPlayer = "\u{F999}" case recordRec = "\u{F44B}" case recycle = "\u{F44C}" case reddit = "\u{F44D}" case redo = "\u{F44E}" case redoVariant = "\u{F44F}" case reflectHorizontal = "\u{FA0D}" case reflectVertical = "\u{FA0E}" case refresh = "\u{F450}" case regex = "\u{F451}" case registeredTrademark = "\u{FA66}" case relativeScale = "\u{F452}" case reload = "\u{F453}" case reminder = "\u{F88B}" case remote = "\u{F454}" case remoteDesktop = "\u{F8B8}" case renameBox = "\u{F455}" case reorderHorizontal = "\u{F687}" case reorderVertical = "\u{F688}" case `repeat` = "\u{F456}" case repeatOff = "\u{F457}" case repeatOnce = "\u{F458}" case replay = "\u{F459}" case reply = "\u{F45A}" case replyAll = "\u{F45B}" case reproduction = "\u{F45C}" case resistor = "\u{FB1F}" case resistorNodes = "\u{FB20}" case resize = "\u{FA67}" case resizeBottomRight = "\u{F45D}" case responsive = "\u{F45E}" case restart = "\u{F708}" case restore = "\u{F99A}" case restoreClock = "\u{F6A7}" case rewind = "\u{F45F}" case rewindOutline = "\u{F709}" case rhombus = "\u{F70A}" case rhombusMedium = "\u{FA0F}" case rhombusOutline = "\u{F70B}" case rhombusSplit = "\u{FA10}" case ribbon = "\u{F460}" case rice = "\u{F7E9}" case ring = "\u{F7EA}" case road = "\u{F461}" case roadVariant = "\u{F462}" case robot = "\u{F6A8}" case robotIndustrial = "\u{FB21}" case robotVacuum = "\u{F70C}" case robotVacuumVariant = "\u{F907}" case rocket = "\u{F463}" case roomService = "\u{F88C}" case rotate3d = "\u{F464}" case rotateLeft = "\u{F465}" case rotateLeftVariant = "\u{F466}" case rotateRight = "\u{F467}" case rotateRightVariant = "\u{F468}" case roundedCorner = "\u{F607}" case routerWireless = "\u{F469}" case routerWirelessSettings = "\u{FA68}" case routes = "\u{F46A}" case rowing = "\u{F608}" case rss = "\u{F46B}" case rssBox = "\u{F46C}" case ruler = "\u{F46D}" case run = "\u{F70D}" case runFast = "\u{F46E}" case safe = "\u{FA69}" case sale = "\u{F46F}" case salesforce = "\u{F88D}" case sass = "\u{F7EB}" case satellite = "\u{F470}" case satelliteUplink = "\u{F908}" case satelliteVariant = "\u{F471}" case sausage = "\u{F8B9}" case saxophone = "\u{F609}" case scale = "\u{F472}" case scaleBalance = "\u{F5D1}" case scaleBathroom = "\u{F473}" case scanner = "\u{F6AA}" case scannerOff = "\u{F909}" case school = "\u{F474}" case scissorsCutting = "\u{FA6A}" case screenRotation = "\u{F475}" case screenRotationLock = "\u{F476}" case screwdriver = "\u{F477}" case script = "\u{F478}" case sd = "\u{F479}" case seal = "\u{F47A}" case searchWeb = "\u{F70E}" case seatFlat = "\u{F47B}" case seatFlatAngled = "\u{F47C}" case seatIndividualSuite = "\u{F47D}" case seatLegroomExtra = "\u{F47E}" case seatLegroomNormal = "\u{F47F}" case seatLegroomReduced = "\u{F480}" case seatReclineExtra = "\u{F481}" case seatReclineNormal = "\u{F482}" case security = "\u{F483}" case securityAccount = "\u{F88E}" case securityAccountOutline = "\u{FA11}" case securityClose = "\u{F99B}" case securityHome = "\u{F689}" case securityLock = "\u{F99C}" case securityNetwork = "\u{F484}" case securityOff = "\u{F99D}" case select = "\u{F485}" case selectAll = "\u{F486}" case selectCompare = "\u{FAD8}" case selectDrag = "\u{FA6B}" case selectInverse = "\u{F487}" case selectOff = "\u{F488}" case selection = "\u{F489}" case selectionDrag = "\u{FA6C}" case selectionOff = "\u{F776}" case send = "\u{F48A}" case sendLock = "\u{F7EC}" case serialPort = "\u{F65C}" case server = "\u{F48B}" case serverMinus = "\u{F48C}" case serverNetwork = "\u{F48D}" case serverNetworkOff = "\u{F48E}" case serverOff = "\u{F48F}" case serverPlus = "\u{F490}" case serverRemove = "\u{F491}" case serverSecurity = "\u{F492}" case setAll = "\u{F777}" case setCenter = "\u{F778}" case setCenterRight = "\u{F779}" case setLeft = "\u{F77A}" case setLeftCenter = "\u{F77B}" case setLeftRight = "\u{F77C}" case setNone = "\u{F77D}" case setRight = "\u{F77E}" case setTopBox = "\u{F99E}" case settings = "\u{F493}" case settingsBox = "\u{F494}" case settingsHelper = "\u{FA6D}" case settingsOutline = "\u{F8BA}" case shape = "\u{F830}" case shapeCirclePlus = "\u{F65D}" case shapeOutline = "\u{F831}" case shapePlus = "\u{F495}" case shapePolygonPlus = "\u{F65E}" case shapeRectanglePlus = "\u{F65F}" case shapeSquarePlus = "\u{F660}" case share = "\u{F496}" case shareOutline = "\u{F931}" case shareVariant = "\u{F497}" case shield = "\u{F498}" case shieldHalfFull = "\u{F77F}" case shieldOutline = "\u{F499}" case shieldPlus = "\u{FAD9}" case shieldPlusOutline = "\u{FADA}" case shieldRemove = "\u{FADB}" case shieldRemoveOutline = "\u{FADC}" case shipWheel = "\u{F832}" case shoeFormal = "\u{FB22}" case shoeHeel = "\u{FB23}" case shopify = "\u{FADD}" case shopping = "\u{F49A}" case shoppingMusic = "\u{F49B}" case shovel = "\u{F70F}" case shovelOff = "\u{F710}" case shower = "\u{F99F}" case showerHead = "\u{F9A0}" case shredder = "\u{F49C}" case shuffle = "\u{F49D}" case shuffleDisabled = "\u{F49E}" case shuffleVariant = "\u{F49F}" case sigma = "\u{F4A0}" case sigmaLower = "\u{F62B}" case signCaution = "\u{F4A1}" case signDirection = "\u{F780}" case signText = "\u{F781}" case signal = "\u{F4A2}" case signal2g = "\u{F711}" case signal3g = "\u{F712}" case signal4g = "\u{F713}" case signal5g = "\u{FA6E}" case signalCellular1 = "\u{F8BB}" case signalCellular2 = "\u{F8BC}" case signalCellular3 = "\u{F8BD}" case signalCellularOutline = "\u{F8BE}" case signalHspa = "\u{F714}" case signalHspaPlus = "\u{F715}" case signalOff = "\u{F782}" case signalVariant = "\u{F60A}" case silo = "\u{FB24}" case silverware = "\u{F4A3}" case silverwareFork = "\u{F4A4}" case silverwareForkKnife = "\u{FA6F}" case silverwareSpoon = "\u{F4A5}" case silverwareVariant = "\u{F4A6}" case sim = "\u{F4A7}" case simAlert = "\u{F4A8}" case simOff = "\u{F4A9}" case sinaWeibo = "\u{FADE}" case sitemap = "\u{F4AA}" case skipBackward = "\u{F4AB}" case skipForward = "\u{F4AC}" case skipNext = "\u{F4AD}" case skipNextCircle = "\u{F661}" case skipNextCircleOutline = "\u{F662}" case skipPrevious = "\u{F4AE}" case skipPreviousCircle = "\u{F663}" case skipPreviousCircleOutline = "\u{F664}" case skull = "\u{F68B}" case skype = "\u{F4AF}" case skypeBusiness = "\u{F4B0}" case slack = "\u{F4B1}" case slackware = "\u{F90A}" case sleep = "\u{F4B2}" case sleepOff = "\u{F4B3}" case smog = "\u{FA70}" case smokeDetector = "\u{F392}" case smoking = "\u{F4B4}" case smokingOff = "\u{F4B5}" case snapchat = "\u{F4B6}" case snowflake = "\u{F716}" case snowman = "\u{F4B7}" case soccer = "\u{F4B8}" case soccerField = "\u{F833}" case sofa = "\u{F4B9}" case solarPower = "\u{FA71}" case solid = "\u{F68C}" case sort = "\u{F4BA}" case sortAlphabetical = "\u{F4BB}" case sortAscending = "\u{F4BC}" case sortDescending = "\u{F4BD}" case sortNumeric = "\u{F4BE}" case sortVariant = "\u{F4BF}" case soundcloud = "\u{F4C0}" case sourceBranch = "\u{F62C}" case sourceCommit = "\u{F717}" case sourceCommitEnd = "\u{F718}" case sourceCommitEndLocal = "\u{F719}" case sourceCommitLocal = "\u{F71A}" case sourceCommitNextLocal = "\u{F71B}" case sourceCommitStart = "\u{F71C}" case sourceCommitStartNextLocal = "\u{F71D}" case sourceFork = "\u{F4C1}" case sourceMerge = "\u{F62D}" case sourcePull = "\u{F4C2}" case soySauce = "\u{F7ED}" case speaker = "\u{F4C3}" case speakerBluetooth = "\u{F9A1}" case speakerOff = "\u{F4C4}" case speakerWireless = "\u{F71E}" case speedometer = "\u{F4C5}" case spellcheck = "\u{F4C6}" case spotify = "\u{F4C7}" case spotlight = "\u{F4C8}" case spotlightBeam = "\u{F4C9}" case spray = "\u{F665}" case sprayBottle = "\u{FADF}" case square = "\u{F763}" case squareEditOutline = "\u{F90B}" case squareInc = "\u{F4CA}" case squareIncCash = "\u{F4CB}" case squareMedium = "\u{FA12}" case squareMediumOutline = "\u{FA13}" case squareOutline = "\u{F762}" case squareRoot = "\u{F783}" case squareRootBox = "\u{F9A2}" case squareSmall = "\u{FA14}" case squeegee = "\u{FAE0}" case ssh = "\u{F8BF}" case stackExchange = "\u{F60B}" case stackOverflow = "\u{F4CC}" case stadium = "\u{F71F}" case stairs = "\u{F4CD}" case standardDefinition = "\u{F7EE}" case star = "\u{F4CE}" case starBox = "\u{FA72}" case starBoxOutline = "\u{FA73}" case starCircle = "\u{F4CF}" case starCircleOutline = "\u{F9A3}" case starFace = "\u{F9A4}" case starFourPoints = "\u{FAE1}" case starFourPointsOutline = "\u{FAE2}" case starHalf = "\u{F4D0}" case starOff = "\u{F4D1}" case starOutline = "\u{F4D2}" case starThreePoints = "\u{FAE3}" case starThreePointsOutline = "\u{FAE4}" case steam = "\u{F4D3}" case steamBox = "\u{F90C}" case steering = "\u{F4D4}" case steeringOff = "\u{F90D}" case stepBackward = "\u{F4D5}" case stepBackward2 = "\u{F4D6}" case stepForward = "\u{F4D7}" case stepForward2 = "\u{F4D8}" case stethoscope = "\u{F4D9}" case sticker = "\u{F5D0}" case stickerEmoji = "\u{F784}" case stocking = "\u{F4DA}" case stop = "\u{F4DB}" case stopCircle = "\u{F666}" case stopCircleOutline = "\u{F667}" case store = "\u{F4DC}" case store24Hour = "\u{F4DD}" case stove = "\u{F4DE}" case strava = "\u{FB25}" case subdirectoryArrowLeft = "\u{F60C}" case subdirectoryArrowRight = "\u{F60D}" case subtitles = "\u{FA15}" case subtitlesOutline = "\u{FA16}" case subway = "\u{F6AB}" case subwayVariant = "\u{F4DF}" case summit = "\u{F785}" case sunglasses = "\u{F4E0}" case surroundSound = "\u{F5C5}" case surroundSound20 = "\u{F7EF}" case surroundSound31 = "\u{F7F0}" case surroundSound51 = "\u{F7F1}" case surroundSound71 = "\u{F7F2}" case svg = "\u{F720}" case swapHorizontal = "\u{F4E1}" case swapHorizontalVariant = "\u{F8C0}" case swapVertical = "\u{F4E2}" case swapVerticalVariant = "\u{F8C1}" case swim = "\u{F4E3}" case `switch` = "\u{F4E4}" case sword = "\u{F4E5}" case swordCross = "\u{F786}" case symfony = "\u{FAE5}" case sync = "\u{F4E6}" case syncAlert = "\u{F4E7}" case syncOff = "\u{F4E8}" case tab = "\u{F4E9}" case tabMinus = "\u{FB26}" case tabPlus = "\u{F75B}" case tabRemove = "\u{FB27}" case tabUnselected = "\u{F4EA}" case table = "\u{F4EB}" case tableBorder = "\u{FA17}" case tableColumn = "\u{F834}" case tableColumnPlusAfter = "\u{F4EC}" case tableColumnPlusBefore = "\u{F4ED}" case tableColumnRemove = "\u{F4EE}" case tableColumnWidth = "\u{F4EF}" case tableEdit = "\u{F4F0}" case tableLarge = "\u{F4F1}" case tableMergeCells = "\u{F9A5}" case tableOfContents = "\u{F835}" case tablePlus = "\u{FA74}" case tableRemove = "\u{FA75}" case tableRow = "\u{F836}" case tableRowHeight = "\u{F4F2}" case tableRowPlusAfter = "\u{F4F3}" case tableRowPlusBefore = "\u{F4F4}" case tableRowRemove = "\u{F4F5}" case tableSearch = "\u{F90E}" case tableSettings = "\u{F837}" case tablet = "\u{F4F6}" case tabletAndroid = "\u{F4F7}" case tabletCellphone = "\u{F9A6}" case tabletIpad = "\u{F4F8}" case taco = "\u{F761}" case tag = "\u{F4F9}" case tagFaces = "\u{F4FA}" case tagHeart = "\u{F68A}" case tagMinus = "\u{F90F}" case tagMultiple = "\u{F4FB}" case tagOutline = "\u{F4FC}" case tagPlus = "\u{F721}" case tagRemove = "\u{F722}" case tagTextOutline = "\u{F4FD}" case tapeMeasure = "\u{FB28}" case target = "\u{F4FE}" case targetVariant = "\u{FA76}" case taxi = "\u{F4FF}" case teach = "\u{F88F}" case teamviewer = "\u{F500}" case telegram = "\u{F501}" case telescope = "\u{FB29}" case television = "\u{F502}" case televisionBox = "\u{F838}" case televisionClassic = "\u{F7F3}" case televisionClassicOff = "\u{F839}" case televisionGuide = "\u{F503}" case televisionOff = "\u{F83A}" case temperatureCelsius = "\u{F504}" case temperatureFahrenheit = "\u{F505}" case temperatureKelvin = "\u{F506}" case tennis = "\u{F507}" case tent = "\u{F508}" case terrain = "\u{F509}" case testTube = "\u{F668}" case testTubeEmpty = "\u{F910}" case testTubeOff = "\u{F911}" case text = "\u{F9A7}" case textShadow = "\u{F669}" case textShort = "\u{F9A8}" case textSubject = "\u{F9A9}" case textToSpeech = "\u{F50A}" case textToSpeechOff = "\u{F50B}" case textbox = "\u{F60E}" case textboxPassword = "\u{F7F4}" case texture = "\u{F50C}" case theater = "\u{F50D}" case themeLightDark = "\u{F50E}" case thermometer = "\u{F50F}" case thermometerLines = "\u{F510}" case thermostat = "\u{F393}" case thermostatBox = "\u{F890}" case thoughtBubble = "\u{F7F5}" case thoughtBubbleOutline = "\u{F7F6}" case thumbDown = "\u{F511}" case thumbDownOutline = "\u{F512}" case thumbUp = "\u{F513}" case thumbUpOutline = "\u{F514}" case thumbsUpDown = "\u{F515}" case ticket = "\u{F516}" case ticketAccount = "\u{F517}" case ticketConfirmation = "\u{F518}" case ticketOutline = "\u{F912}" case ticketPercent = "\u{F723}" case tie = "\u{F519}" case tilde = "\u{F724}" case timelapse = "\u{F51A}" case timer = "\u{F51B}" case timer10 = "\u{F51C}" case timer3 = "\u{F51D}" case timerOff = "\u{F51E}" case timerSand = "\u{F51F}" case timerSandEmpty = "\u{F6AC}" case timerSandFull = "\u{F78B}" case timetable = "\u{F520}" case toggleSwitch = "\u{F521}" case toggleSwitchOff = "\u{F522}" case toggleSwitchOffOutline = "\u{FA18}" case toggleSwitchOutline = "\u{FA19}" case toilet = "\u{F9AA}" case toolbox = "\u{F9AB}" case toolboxOutline = "\u{F9AC}" case tooltip = "\u{F523}" case tooltipEdit = "\u{F524}" case tooltipImage = "\u{F525}" case tooltipOutline = "\u{F526}" case tooltipOutlinePlus = "\u{F527}" case tooltipText = "\u{F528}" case tooth = "\u{F8C2}" case toothOutline = "\u{F529}" case tor = "\u{F52A}" case tournament = "\u{F9AD}" case towerBeach = "\u{F680}" case towerFire = "\u{F681}" case towing = "\u{F83B}" case trackLight = "\u{F913}" case trackpad = "\u{F7F7}" case trackpadLock = "\u{F932}" case tractor = "\u{F891}" case trademark = "\u{FA77}" case trafficLight = "\u{F52B}" case train = "\u{F52C}" case trainVariant = "\u{F8C3}" case tram = "\u{F52D}" case transcribe = "\u{F52E}" case transcribeClose = "\u{F52F}" case transfer = "\u{F530}" case transitTransfer = "\u{F6AD}" case transition = "\u{F914}" case transitionMasked = "\u{F915}" case translate = "\u{F5CA}" case trashCan = "\u{FA78}" case trashCanOutline = "\u{FA79}" case treasureChest = "\u{F725}" case tree = "\u{F531}" case trello = "\u{F532}" case trendingDown = "\u{F533}" case trendingNeutral = "\u{F534}" case trendingUp = "\u{F535}" case triangle = "\u{F536}" case triangleOutline = "\u{F537}" case trophy = "\u{F538}" case trophyAward = "\u{F539}" case trophyOutline = "\u{F53A}" case trophyVariant = "\u{F53B}" case trophyVariantOutline = "\u{F53C}" case truck = "\u{F53D}" case truckDelivery = "\u{F53E}" case truckFast = "\u{F787}" case truckTrailer = "\u{F726}" case tshirtCrew = "\u{FA7A}" case tshirtCrewOutline = "\u{F53F}" case tshirtV = "\u{FA7B}" case tshirtVOutline = "\u{F540}" case tumbleDryer = "\u{F916}" case tumblr = "\u{F541}" case tumblrBox = "\u{F917}" case tumblrReblog = "\u{F542}" case tune = "\u{F62E}" case tuneVertical = "\u{F66A}" case twitch = "\u{F543}" case twitter = "\u{F544}" case twitterBox = "\u{F545}" case twitterCircle = "\u{F546}" case twitterRetweet = "\u{F547}" case twoFactorAuthentication = "\u{F9AE}" case uber = "\u{F748}" case ubuntu = "\u{F548}" case ultraHighDefinition = "\u{F7F8}" case umbraco = "\u{F549}" case umbrella = "\u{F54A}" case umbrellaClosed = "\u{F9AF}" case umbrellaOutline = "\u{F54B}" case undo = "\u{F54C}" case undoVariant = "\u{F54D}" case unfoldLessHorizontal = "\u{F54E}" case unfoldLessVertical = "\u{F75F}" case unfoldMoreHorizontal = "\u{F54F}" case unfoldMoreVertical = "\u{F760}" case ungroup = "\u{F550}" case unity = "\u{F6AE}" case unreal = "\u{F9B0}" case untappd = "\u{F551}" case update = "\u{F6AF}" case upload = "\u{F552}" case uploadMultiple = "\u{F83C}" case uploadNetwork = "\u{F6F5}" case usb = "\u{F553}" case vanPassenger = "\u{F7F9}" case vanUtility = "\u{F7FA}" case vanish = "\u{F7FB}" case variable = "\u{FAE6}" case vectorArrangeAbove = "\u{F554}" case vectorArrangeBelow = "\u{F555}" case vectorBezier = "\u{FAE7}" case vectorCircle = "\u{F556}" case vectorCircleVariant = "\u{F557}" case vectorCombine = "\u{F558}" case vectorCurve = "\u{F559}" case vectorDifference = "\u{F55A}" case vectorDifferenceAb = "\u{F55B}" case vectorDifferenceBa = "\u{F55C}" case vectorEllipse = "\u{F892}" case vectorIntersection = "\u{F55D}" case vectorLine = "\u{F55E}" case vectorPoint = "\u{F55F}" case vectorPolygon = "\u{F560}" case vectorPolyline = "\u{F561}" case vectorRadius = "\u{F749}" case vectorRectangle = "\u{F5C6}" case vectorSelection = "\u{F562}" case vectorSquare = "\u{F001}" case vectorTriangle = "\u{F563}" case vectorUnion = "\u{F564}" case venmo = "\u{F578}" case verified = "\u{F565}" case vhs = "\u{FA1A}" case vibrate = "\u{F566}" case video = "\u{F567}" case video3d = "\u{F7FC}" case video4kBox = "\u{F83D}" case videoAccount = "\u{F918}" case videoImage = "\u{F919}" case videoInputAntenna = "\u{F83E}" case videoInputComponent = "\u{F83F}" case videoInputHdmi = "\u{F840}" case videoInputSvideo = "\u{F841}" case videoMinus = "\u{F9B1}" case videoOff = "\u{F568}" case videoPlus = "\u{F9B2}" case videoStabilization = "\u{F91A}" case videoSwitch = "\u{F569}" case videoVintage = "\u{FA1B}" case viewAgenda = "\u{F56A}" case viewArray = "\u{F56B}" case viewCarousel = "\u{F56C}" case viewColumn = "\u{F56D}" case viewDashboard = "\u{F56E}" case viewDashboardOutline = "\u{FA1C}" case viewDashboardVariant = "\u{F842}" case viewDay = "\u{F56F}" case viewGrid = "\u{F570}" case viewHeadline = "\u{F571}" case viewList = "\u{F572}" case viewModule = "\u{F573}" case viewParallel = "\u{F727}" case viewQuilt = "\u{F574}" case viewSequential = "\u{F728}" case viewStream = "\u{F575}" case viewWeek = "\u{F576}" case vimeo = "\u{F577}" case violin = "\u{F60F}" case virtualReality = "\u{F893}" case visualStudio = "\u{F610}" case visualStudioCode = "\u{FA1D}" case vk = "\u{F579}" case vkBox = "\u{F57A}" case vkCircle = "\u{F57B}" case vlc = "\u{F57C}" case voice = "\u{F5CB}" case voicemail = "\u{F57D}" case volleyball = "\u{F9B3}" case volumeHigh = "\u{F57E}" case volumeLow = "\u{F57F}" case volumeMedium = "\u{F580}" case volumeMinus = "\u{F75D}" case volumeMute = "\u{F75E}" case volumeOff = "\u{F581}" case volumePlus = "\u{F75C}" case vote = "\u{FA1E}" case voteOutline = "\u{FA1F}" case vpn = "\u{F582}" case vuejs = "\u{F843}" case walk = "\u{F583}" case wall = "\u{F7FD}" case wallSconce = "\u{F91B}" case wallSconceFlat = "\u{F91C}" case wallSconceVariant = "\u{F91D}" case wallet = "\u{F584}" case walletGiftcard = "\u{F585}" case walletMembership = "\u{F586}" case walletTravel = "\u{F587}" case wan = "\u{F588}" case washingMachine = "\u{F729}" case watch = "\u{F589}" case watchExport = "\u{F58A}" case watchExportVariant = "\u{F894}" case watchImport = "\u{F58B}" case watchImportVariant = "\u{F895}" case watchVariant = "\u{F896}" case watchVibrate = "\u{F6B0}" case water = "\u{F58C}" case waterOff = "\u{F58D}" case waterPercent = "\u{F58E}" case waterPump = "\u{F58F}" case watermark = "\u{F612}" case waves = "\u{F78C}" case weatherCloudy = "\u{F590}" case weatherFog = "\u{F591}" case weatherHail = "\u{F592}" case weatherHurricane = "\u{F897}" case weatherLightning = "\u{F593}" case weatherLightningRainy = "\u{F67D}" case weatherNight = "\u{F594}" case weatherPartlycloudy = "\u{F595}" case weatherPouring = "\u{F596}" case weatherRainy = "\u{F597}" case weatherSnowy = "\u{F598}" case weatherSnowyRainy = "\u{F67E}" case weatherSunny = "\u{F599}" case weatherSunset = "\u{F59A}" case weatherSunsetDown = "\u{F59B}" case weatherSunsetUp = "\u{F59C}" case weatherWindy = "\u{F59D}" case weatherWindyVariant = "\u{F59E}" case web = "\u{F59F}" case webcam = "\u{F5A0}" case webhook = "\u{F62F}" case webpack = "\u{F72A}" case wechat = "\u{F611}" case weight = "\u{F5A1}" case weightKilogram = "\u{F5A2}" case weightPound = "\u{F9B4}" case whatsapp = "\u{F5A3}" case wheelchairAccessibility = "\u{F5A4}" case whistle = "\u{F9B5}" case whiteBalanceAuto = "\u{F5A5}" case whiteBalanceIncandescent = "\u{F5A6}" case whiteBalanceIridescent = "\u{F5A7}" case whiteBalanceSunny = "\u{F5A8}" case widgets = "\u{F72B}" case wifi = "\u{F5A9}" case wifiOff = "\u{F5AA}" case wifiStrength1 = "\u{F91E}" case wifiStrength1Alert = "\u{F91F}" case wifiStrength1Lock = "\u{F920}" case wifiStrength2 = "\u{F921}" case wifiStrength2Alert = "\u{F922}" case wifiStrength2Lock = "\u{F923}" case wifiStrength3 = "\u{F924}" case wifiStrength3Alert = "\u{F925}" case wifiStrength3Lock = "\u{F926}" case wifiStrength4 = "\u{F927}" case wifiStrength4Alert = "\u{F928}" case wifiStrength4Lock = "\u{F929}" case wifiStrengthAlertOutline = "\u{F92A}" case wifiStrengthLockOutline = "\u{F92B}" case wifiStrengthOff = "\u{F92C}" case wifiStrengthOffOutline = "\u{F92D}" case wifiStrengthOutline = "\u{F92E}" case wii = "\u{F5AB}" case wiiu = "\u{F72C}" case wikipedia = "\u{F5AC}" case windowClose = "\u{F5AD}" case windowClosed = "\u{F5AE}" case windowMaximize = "\u{F5AF}" case windowMinimize = "\u{F5B0}" case windowOpen = "\u{F5B1}" case windowRestore = "\u{F5B2}" case windows = "\u{F5B3}" case windowsClassic = "\u{FA20}" case wiper = "\u{FAE8}" case wordpress = "\u{F5B4}" case worker = "\u{F5B5}" case wrap = "\u{F5B6}" case wrench = "\u{F5B7}" case wunderlist = "\u{F5B8}" case xamarin = "\u{F844}" case xamarinOutline = "\u{F845}" case xaml = "\u{F673}" case xbox = "\u{F5B9}" case xboxController = "\u{F5BA}" case xboxControllerBatteryAlert = "\u{F74A}" case xboxControllerBatteryCharging = "\u{FA21}" case xboxControllerBatteryEmpty = "\u{F74B}" case xboxControllerBatteryFull = "\u{F74C}" case xboxControllerBatteryLow = "\u{F74D}" case xboxControllerBatteryMedium = "\u{F74E}" case xboxControllerBatteryUnknown = "\u{F74F}" case xboxControllerOff = "\u{F5BB}" case xda = "\u{F5BC}" case xing = "\u{F5BD}" case xingBox = "\u{F5BE}" case xingCircle = "\u{F5BF}" case xml = "\u{F5C0}" case xmpp = "\u{F7FE}" case yahoo = "\u{FB2A}" case yammer = "\u{F788}" case yeast = "\u{F5C1}" case yelp = "\u{F5C2}" case yinYang = "\u{F67F}" case youtube = "\u{F5C3}" case youtubeCreatorStudio = "\u{F846}" case youtubeGaming = "\u{F847}" case youtubeTv = "\u{F448}" case zWave = "\u{FAE9}" case zend = "\u{FAEA}" case zipBox = "\u{F5C4}" case zipDisk = "\u{FA22}" case zodiacAquarius = "\u{FA7C}" case zodiacAries = "\u{FA7D}" case zodiacCancer = "\u{FA7E}" case zodiacCapricorn = "\u{FA7F}" case zodiacGemini = "\u{FA80}" case zodiacLeo = "\u{FA81}" case zodiacLibra = "\u{FA82}" case zodiacPisces = "\u{FA83}" case zodiacSagittarius = "\u{FA84}" case zodiacScorpio = "\u{FA85}" case zodiacTaurus = "\u{FA86}" case zodiacVirgo = "\u{FA87}" public static var blank: MaterialDesignIcons { return .solid } }
mit
f39a64865e8e58917f25d5fb9778cfc5
30.524235
63
0.651727
2.456116
false
false
false
false
radex/swift-compiler-crashes
crashes-fuzzing/07437-swift-genericparamlist-getascanonicalgenericsignature.swift
11
1598
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let t: BooleanType, A { typealias e = 0 class c : BooleanType, A { if true { if true { class struct B private let a : B<T : T.E == c struct d<T : NSObject { struct B<T where B : a : e let a : T where B == e protocol A : NSObject { let a : b = e(f(v: BooleanType, A { case c private let a { struct B<b class A { typealias e = e func b: T typealias e : BooleanType, A { let a = [Void{ { struct S(v: P { class c : S<T where I.E == 0 protocol c : b { func c, let t: C { struct S(v: BooleanType, A { case c, struct B func c, typealias e = [Void{ protocol A : S(f(v: T where T.B == 0 var _ = e: String { typealias e = c enum b { func c { enum b { func c func c func c, typealias e = Int protocol A : T : S<T where I.E == c struct B<T where T.E == c, class A : T struct B<T where T if true { enum b { func b<Int var e: T.E == c struct B class A : P { struct S(") var _ = e struct S<T where B == 0 var e struct S<T where B : S(f(f(v: e(f(v: P { private let a = e: NSObject { enum b { func b enum b { class A { let t: BooleanType, A { typealias e : T.B : AnyObject) { struct B<Int> case c, enum b { protocol A { struct d<f : P { class class func b: NSObject { case c let t: NSObject { class A { let a = 0 struct B<T where T.B : e: BooleanType, A : String { class c : P { struct B<T : AnyObject) { struct S(f(f(f(") let a { struct B<d { func b<b: b { func b struct B<T where B == e let a = [Void{ typealias e : BooleanType, A { var b { st
mit
973a3f0f66ae0e43f684f59936e28f29
17.159091
87
0.634543
2.658902
false
false
false
false
klaus01/Centipede
Centipede/Foundation/CE_NSUserActivity.swift
1
3170
// // CE_NSUserActivity.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import Foundation extension NSUserActivity { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: NSUserActivity_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? NSUserActivity_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: NSUserActivity_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is NSUserActivity_Delegate { return obj as! NSUserActivity_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal func getDelegateInstance() -> NSUserActivity_Delegate { return NSUserActivity_Delegate() } @discardableResult public func ce_userActivityWillSave(handle: @escaping (NSUserActivity) -> Void) -> Self { ce._userActivityWillSave = handle rebindingDelegate() return self } @discardableResult public func ce_userActivityWasContinued(handle: @escaping (NSUserActivity) -> Void) -> Self { ce._userActivityWasContinued = handle rebindingDelegate() return self } @discardableResult public func ce_userActivity_didReceive(handle: @escaping (NSUserActivity?, InputStream, OutputStream) -> Void) -> Self { ce._userActivity_didReceive = handle rebindingDelegate() return self } } internal class NSUserActivity_Delegate: NSObject, NSUserActivityDelegate { var _userActivityWillSave: ((NSUserActivity) -> Void)? var _userActivityWasContinued: ((NSUserActivity) -> Void)? var _userActivity_didReceive: ((NSUserActivity?, InputStream, OutputStream) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(userActivityWillSave(_:)) : _userActivityWillSave, #selector(userActivityWasContinued(_:)) : _userActivityWasContinued, #selector(userActivity(_:didReceive:outputStream:)) : _userActivity_didReceive, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func userActivityWillSave(_ userActivity: NSUserActivity) { _userActivityWillSave!(userActivity) } @objc func userActivityWasContinued(_ userActivity: NSUserActivity) { _userActivityWasContinued!(userActivity) } @objc func userActivity(_ userActivity: NSUserActivity?, didReceive inputStream: InputStream, outputStream: OutputStream) { _userActivity_didReceive!(userActivity, inputStream, outputStream) } }
mit
3d37991326bd399136271b08aab677b4
32.347368
128
0.64899
5.32437
false
false
false
false
rokuz/omim
iphone/Maps/Bookmarks/Catalog/Subscription/BaseSubscriptionViewController.swift
1
6135
import Foundation import SafariServices class BaseSubscriptionViewController: MWMViewController { //MARK: base outlets @IBOutlet private var loadingView: UIView! //MARK: dependency private(set) var subscriptionManager: ISubscriptionManager? private let bookmarksManager: MWMBookmarksManager = MWMBookmarksManager.shared() private var subscriptionGroup: ISubscriptionGroup? @objc var onSubscribe: MWMVoidBlock? @objc var onCancel: MWMVoidBlock? @objc var source: String = kStatWebView override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return [.portrait] } } override var preferredStatusBarStyle: UIStatusBarStyle { get { return .lightContent } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) subscriptionManager?.addListener(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { subscriptionManager?.removeListener(self) } override func viewDidLoad() { super.viewDidLoad() self.presentationController?.delegate = self; } func configure(buttons: [SubscriptionPeriod: BookmarksSubscriptionButton], discountLabels: [SubscriptionPeriod: BookmarksSubscriptionDiscountLabel]) { subscriptionManager?.getAvailableSubscriptions { [weak self] (subscriptions, error) in guard let subscriptions = subscriptions, subscriptions.count >= buttons.count else { MWMAlertViewController.activeAlert().presentInfoAlert(L("price_error_title"), text: L("price_error_subtitle")) self?.onCancel?() return } let group = SubscriptionGroup(subscriptions: subscriptions) self?.subscriptionGroup = group for (period, button) in buttons { if let subscriptionItem = group[period] { button.config(title: subscriptionItem.title, price: subscriptionItem.formattedPrice, enabled: true) if subscriptionItem.hasDiscount, let discountLabel = discountLabels[period] { discountLabel.isHidden = false; discountLabel.text = subscriptionItem.formattedDisount } } } } } func purchase(sender: UIButton, period: SubscriptionPeriod) { guard let subscription = subscriptionGroup?[period]?.subscription else{ return } signup(anchor: sender) { [weak self] success in guard success else { return } self?.loadingView.isHidden = false self?.bookmarksManager.ping { success in guard success else { self?.loadingView.isHidden = true let errorDialog = SubscriptionFailViewController { [weak self] in self?.dismiss(animated: true) } self?.present(errorDialog, animated: true) return } self?.subscriptionManager?.subscribe(to: subscription) } } Statistics.logEvent(kStatInappPay, withParameters: [kStatPurchase: MWMPurchaseManager.bookmarksSubscriptionServerId()], with: .realtime) } @IBAction func onRestore(_ sender: UIButton) { Statistics.logEvent(kStatInappRestore, withParameters: [kStatPurchase: MWMPurchaseManager.bookmarksSubscriptionServerId()]) signup(anchor: sender) { [weak self] (success) in guard success else { return } self?.loadingView.isHidden = false self?.subscriptionManager?.restore { result in self?.loadingView.isHidden = true let alertText: String switch result { case .valid: alertText = L("restore_success_alert") case .notValid: alertText = L("restore_no_subscription_alert") case .serverError, .authError: alertText = L("restore_error_alert") } MWMAlertViewController.activeAlert().presentInfoAlert(L("restore_subscription"), text: alertText) } } } @IBAction func onClose(_ sender: UIButton) { onCancel?() Statistics.logEvent(kStatInappCancel, withParameters: [kStatPurchase: MWMPurchaseManager.bookmarksSubscriptionServerId()]) } @IBAction func onTerms(_ sender: UIButton) { guard let url = URL(string: MWMAuthorizationViewModel.termsOfUseLink()) else { return } let safari = SFSafariViewController(url: url) self.present(safari, animated: true, completion: nil) } @IBAction func onPrivacy(_ sender: UIButton) { guard let url = URL(string: MWMAuthorizationViewModel.privacyPolicyLink()) else { return } let safari = SFSafariViewController(url: url) self.present(safari, animated: true, completion: nil) } } extension BaseSubscriptionViewController: UIAdaptivePresentationControllerDelegate { func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { onCancel?() } } extension BaseSubscriptionViewController: SubscriptionManagerListener { func didFailToValidate() { loadingView.isHidden = true MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle")) } func didValidate(_ isValid: Bool) { loadingView.isHidden = true if (isValid) { onSubscribe?() } else { MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle")) } } func didFailToSubscribe(_ subscription: ISubscription, error: Error?) { loadingView.isHidden = true MWMAlertViewController.activeAlert().presentInfoAlert(L("bookmarks_convert_error_title"), text: L("purchase_error_subtitle")) } func didSubscribe(_ subscription: ISubscription) { MWMPurchaseManager.setBookmarksSubscriptionActive(true) bookmarksManager.resetInvalidCategories() } func didDefer(_ subscription: ISubscription) { } }
apache-2.0
eb2589b74c346e866ed4a09505a93497
34.877193
127
0.677099
5.325521
false
false
false
false
mikina/SwiftNews
SwiftNews/SwiftNews/Modules/LiveNews/TabCoordinator/LiveNewsTabCoordinator.swift
1
833
// // LiveNewsTabCoordinator.swift // SwiftNews // // Created by Mike Mikina on 12/5/16. // Copyright © 2016 SwiftCookies.com. All rights reserved. // import UIKit class LiveNewsTabCoordinator: TabCoordinator { var rootController: CustomNavigationController var customTabBarItem = TabBarItem(builder: TabBarItemBuilder { builder in builder.icon = "live_feed" builder.type = .spike builder.backgroundColor = UIColor("#F90038") builder.iconColor = UIColor(Constants.TabBar.SpikeButtonColor) builder.selectedIconColor = UIColor(Constants.TabBar.SpikeSelectedButtonColor) }) init() { let homeVC = ViewController() homeVC.title = "Live feed" self.rootController = CustomNavigationController(rootViewController: homeVC) self.rootController.customTabBarItem = self.customTabBarItem } }
mit
c2d1be6057951e1dc8386c12ea68e609
29.814815
82
0.752404
4.333333
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/PRODUCTNAME/Application/Debug/DebugMenu.swift
1
1310
// // DebugMenu.swift // PRODUCTNAME // // Created by LEADDEVELOPER on TODAYSDATE. // Copyright © THISYEAR ORGANIZATION. All rights reserved. // import Swiftilities import Services import Crashlytics class DebugMenu { static func enableDebugGesture(_ viewController: UIViewController) { let debugGesture = UITapGestureRecognizer(target: self, action: #selector(openDebugAlert)) debugGesture.numberOfTapsRequired = 3 debugGesture.numberOfTouchesRequired = 2 viewController.view.addGestureRecognizer(debugGesture) } @objc static func openDebugAlert() { guard let delegate = UIApplication.shared.delegate as? AppDelegate, let rootViewController = delegate.window?.rootViewController else { Log.warn("Debug alert unable to present since the window rootViewController is nil") return } var topMostViewController: UIViewController? = rootViewController while topMostViewController?.presentedViewController != nil { topMostViewController = topMostViewController?.presentedViewController! } let debug = UINavigationController(rootViewController: DebugMenuViewController()) topMostViewController?.present(debug, animated: true, completion: nil) } }
mit
37728e2e6b63f108072745b53e481cb7
35.361111
100
0.718105
5.977169
false
false
false
false
kingcos/Swift-X-Algorithms
Sort/06-MergeSort/06-MergeSort/main.swift
1
1336
// // main.swift // 06-MergeSort // // Created by 买明 on 11/03/2017. // Copyright © 2017 买明. All rights reserved. // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms import Foundation func mergeSort<T: Comparable>(_ arr: Array<T>, _ isNotOrdered: (T, T) -> Bool) -> Array<T> { // [0, mid) & [mid, arr.count) func merge<T>(_ lArr: Array<T>, _ rArr: Array<T>, _ isNotOrdered: (T, T) -> Bool) -> Array<T> { var arr = lArr + rArr var l = 0, r = 0 for i in 0..<arr.count { if l >= lArr.count { arr[i] = rArr[r] r += 1 } else if r >= rArr.count { arr[i] = lArr[l] l += 1 } else if isNotOrdered(lArr[l], rArr[r]) { arr[i] = lArr[l] l += 1 } else { arr[i] = rArr[r] r += 1 } } return arr } guard arr.count > 1 else { return arr } let mid = arr.count / 2 let lArr = mergeSort(Array(arr[0..<mid]), isNotOrdered) let rArr = mergeSort(Array(arr[mid..<arr.count]), isNotOrdered) return merge(lArr, rArr, isNotOrdered) } TestHelper.checkSortAlgorithm(mergeSort) TestHelper.checkSortAlgorithm(mergeSort, 10000)
mit
c4235f66218c857f11ab9d869dbcab71
27.234043
99
0.504145
3.538667
false
false
false
false
interstateone/Fresh
Fresh/Components/Now Playing/WaveformSliderView.swift
1
4126
// // WaveformSliderView.swift // Fresh // // Created by Brandon Evans on 2016-01-10. // Copyright © 2016 Brandon Evans. All rights reserved. // import Cocoa class WaveformSliderView: NSControl { var maskImage: NSImage? = nil var waveform: Waveform? = nil { didSet { guard let waveform = waveform else { return } guard let offscreenRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(bounds.width), pixelsHigh: Int(bounds.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bitmapFormat: NSBitmapFormat.NSAlphaFirstBitmapFormat, bytesPerRow: 0, bitsPerPixel: 0) else { return } // Set offscreen context guard let graphicsContext = NSGraphicsContext(bitmapImageRep: offscreenRep) else { return } NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrentContext(graphicsContext) let context = graphicsContext.CGContext CGContextSetFillColorWithColor(context, NSColor.blackColor().CGColor) let width = bounds.size.width / CGFloat(waveform.values.count) let maxValue = CGFloat(waveform.values.maxElement() ?? 1) for (index, value) in waveform.values.enumerate() { let rect = CGRectIntegral(CGRectMake(CGFloat(index) * width, 0, width, CGFloat(value) / maxValue * bounds.size.height)) CGContextFillRect(context, rect) } NSGraphicsContext.restoreGraphicsState() let waveformImage = NSImage(size:bounds.size) waveformImage.addRepresentation(offscreenRep) maskImage = waveformImage } } var maxValue: Double = 0 { didSet { guard let cell = cell as? WaveformSliderCell else { return } maxValue = max(maxValue, 0) cell.maxValue = maxValue setNeedsDisplay() } } override var doubleValue: Double { set { var _doubleValue = max(newValue, 0) _doubleValue = min(newValue, maxValue) cell?.objectValue = _doubleValue super.doubleValue = _doubleValue setNeedsDisplay() } get { return super.doubleValue } } override static func cellClass() -> AnyClass { return WaveformSliderCell.self } override func drawRect(dirtyRect: NSRect) { cell?.drawWithFrame(bounds, inView: self) } override func mouseDown(event: NSEvent) { let mousePoint = convertPoint(event.locationInWindow, fromView: nil) if let cell = cell as? WaveformSliderCell where cell.knobPath().containsPoint(mousePoint) { trackMouseWithStartPoint(mousePoint) } else if CGRectContainsPoint(bounds, mousePoint) { doubleValue = Double(valueForPoint(mousePoint)) NSApp.sendAction(action, to:target, from:self) trackMouseWithStartPoint(mousePoint) } } private func valueForPoint(point: NSPoint) -> CGFloat { return point.x / CGRectGetWidth(bounds) * CGFloat(maxValue) } private func trackMouseWithStartPoint(point: NSPoint) { // Compute the value offset: this makes the pointer stay on the same piece of the knob when dragging let valueOffset = Double(valueForPoint(point)) - (objectValue as? NSNumber ?? NSNumber(double: 0)).doubleValue var event: NSEvent? while event?.type != .LeftMouseUp { event = window?.nextEventMatchingMask(Int(NSEventMask.LeftMouseDraggedMask.rawValue) | Int(NSEventMask.LeftMouseUpMask.rawValue)) guard let event = event else { continue } let eventLocation = convertPoint(event.locationInWindow, fromView: nil) let value = Double(valueForPoint(eventLocation)) doubleValue = value - valueOffset NSApp.sendAction(action, to: target, from: self) } } }
mit
2d18d6be4d3a85a5dc92892fcc3d93a8
38.663462
344
0.629576
5.15625
false
false
false
false
niklasberglund/bitwake
BitWake/BitWake.swift
1
1879
// // BitWake.swift // BitWake // // Created by Niklas Berglund on 2017-06-16. // Copyright © 2017 Niklas Berglund. All rights reserved. // import Foundation let kUserDefaultsSuiteName = "com.bitwake" let kWalletsFileName = "walletsCollectionStore" let kCollectionViewHeaderHeight: CGFloat = 28.0 enum Cryptocurrency { case BTC } public class BitWake { static var appDelegate: AppDelegate { get { return NSApplication.shared().delegate as! AppDelegate } } public static func ensureHaveApplicationSupportDirectory() { let applicationSupportUrl = BitWake.applicationSupportUrl() if !FileManager.default.fileExists(atPath: applicationSupportUrl!.path) { BitWake.createApplicationSupportDirectory() } } private static func createApplicationSupportDirectory() { let applicationSupportUrl = BitWake.applicationSupportUrl() do { try FileManager.default.createDirectory(at: applicationSupportUrl!, withIntermediateDirectories: false, attributes: nil) } catch let error { debugPrint(error) } } public static func applicationSupportUrl() -> URL? { do { let applicationSupportUrl = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let applicationName = ProcessInfo.processInfo.processName return applicationSupportUrl.appendingPathComponent(applicationName, isDirectory: true) } catch let error { debugPrint(error) return nil } } public static func walletsFileUrl() -> URL { return self.applicationSupportUrl()!.appendingPathComponent(kWalletsFileName, isDirectory: false) } }
mit
15eeed841212e079dbf524575ccfb023
28.809524
159
0.661342
5.556213
false
false
false
false
chillpop/Vokoder
SwiftSampleProject/SwiftyVokoderTests/ManagedObjectContextTests.swift
3
6773
// // ManagedObjectContextTests.swift // SwiftSampleProject // // Created by Carl Hill-Popper on 2/9/16. // Copyright © 2016 Vokal. // import XCTest import Vokoder @testable import SwiftyVokoder class ManagedObjectContextTests: XCTestCase { let manager = VOKCoreDataManager.sharedInstance() override func setUp() { super.setUp() self.manager.resetCoreData() self.manager.setResource("CoreDataModel", database: "CoreDataModel.sqlite") // Don't need to keep a reference to the imported object, so set to _ let _ = Stop.vok_import(CTAData.allStopDictionaries()) self.manager.saveMainContextAndWait() } func testContextChain() { let tempContext = self.manager.temporaryContext() //temp context is a child of the main context XCTAssertEqual(tempContext.parent, self.manager.managedObjectContext) //main context has a private parent context XCTAssertNotNil(self.manager.managedObjectContext.parent) } func testDeletingObjectsOnTempContextGetsSavedToMainContext() { //get a temp context, delete from temp, save to main, verify deleted on main let tempContext = self.manager.temporaryContext() let countOfStations = self.manager.count(for: Station.self) XCTAssertGreaterThan(countOfStations, 0) tempContext.performAndWait { self.manager.deleteAllObjects(of: Station.self, context: tempContext) } self.manager.saveAndMerge(withMainContextAndWait: tempContext) let updatedCountOfStations = self.manager.count(for: Station.self) XCTAssertEqual(updatedCountOfStations, 0) XCTAssertNotEqual(countOfStations, updatedCountOfStations) } func testAddingObjectsOnTempContextGetsSavedToMainContext() { //get a temp context, add to temp, save to main, verify added to main let tempContext = self.manager.temporaryContext() let countOfTrainLines: UInt = self.manager.count(for: TrainLine.self) let expectedCountOfTrainLines = countOfTrainLines + 1 tempContext.performAndWait { let silverLine = TrainLine.vok_newInstance(with: tempContext) silverLine.identifier = "SLV" silverLine.name = "Silver Line" } self.manager.saveAndMerge(withMainContextAndWait: tempContext) let updatedCount = self.manager.count(for: TrainLine.self) XCTAssertEqual(updatedCount, expectedCountOfTrainLines) } func testSaveWithoutWaitingEventuallySaves() { let countOfStations = self.manager.count(for: Station.self) XCTAssertGreaterThan(countOfStations, 0) self.manager.deleteAllObjects(of: Station.self, context: nil) self.expectation(forNotification: NSNotification.Name.NSManagedObjectContextDidSave.rawValue, object: self.manager.managedObjectContext) { _ in let updatedCountOfStations = self.manager.count(for: Station.self) XCTAssertEqual(updatedCountOfStations, 0) XCTAssertNotEqual(countOfStations, updatedCountOfStations) return true } guard let rootContext = self.manager.managedObjectContext.parent else { XCTFail("Expecting the main context to have a parent context") return } self.expectation(forNotification: NSNotification.Name.NSManagedObjectContextDidSave.rawValue, object: rootContext) { _ in let updatedCountOfStations = self.manager.count(for: Station.self, for: rootContext) XCTAssertEqual(updatedCountOfStations, 0) XCTAssertNotEqual(countOfStations, updatedCountOfStations) return true } self.manager.saveMainContext() self.waitForExpectations(timeout: 10, handler: nil) } func testSaveAndMergeWithMainContextSavesGrandChildren() { let childContext = self.manager.temporaryContext() let grandChildContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) grandChildContext.parent = childContext let countOfStations = self.manager.count(for: Station.self) XCTAssertGreaterThan(countOfStations, 0) grandChildContext.performAndWait { self.manager.deleteAllObjects(of: Station.self, context: grandChildContext) } self.manager.saveAndMerge(withMainContextAndWait: grandChildContext) let updatedCountOfStations = self.manager.count(for: Station.self) XCTAssertEqual(updatedCountOfStations, 0) XCTAssertNotEqual(countOfStations, updatedCountOfStations) } func testUnsavedMainContextChangesGetPassedToTempContexts() { let countOfStations = self.manager.count(for: Station.self) XCTAssert(countOfStations > 0) //temp contexts should reflect any changes to their parent context (the main context) //regardless of if they were created before... let childContextBeforeChanges = self.manager.temporaryContext() //...changes are made to the parent context... self.manager.deleteAllObjects(of: Station.self, context: nil) //...or after the changes are made let childContextAfterChanges = self.manager.temporaryContext() let childCountOfStations = self.manager.count(for: Station.self, for: childContextBeforeChanges) XCTAssertNotEqual(countOfStations, childCountOfStations) XCTAssertEqual(childCountOfStations, 0) let otherChildCountOfStations = self.manager.count(for: Station.self, for: childContextAfterChanges) XCTAssertNotEqual(countOfStations, otherChildCountOfStations) XCTAssertEqual(otherChildCountOfStations, childCountOfStations) XCTAssertEqual(otherChildCountOfStations, 0) } func testUnsavedTempContextChangesDoNotGetPassedToMainContext() { let countOfStations = self.manager.count(for: Station.self) XCTAssertGreaterThan(countOfStations, 0) let childContext = self.manager.temporaryContext() self.manager.deleteAllObjects(of: Station.self, context: childContext) let childCountOfStations = self.manager.count(for: Station.self, for: childContext) XCTAssertNotEqual(countOfStations, childCountOfStations) XCTAssertEqual(childCountOfStations, 0) let updatedCountOfStations = self.manager.count(for: Station.self) XCTAssertEqual(countOfStations, updatedCountOfStations) } }
mit
198d753a368e09eae2f9fee9f471c352
40.802469
108
0.68547
5.523654
false
true
false
false
tnantoka/AppBoard
AppBoard/Models/App.swift
1
724
// // App.swift // AppBoard // // Created by Tatsuya Tobioka on 3/10/16. // Copyright © 2016 Tatsuya Tobioka. All rights reserved. // import Foundation import RealmSwift import Himotoki import UIKit class App: Object { dynamic var name = "" dynamic var desc = "" dynamic var icon = "" dynamic var url = "" dynamic var releasedAt = NSDate() var board: Board { return linkingObjects(Board.self, forProperty: "apps").first! } lazy var iconImage: UIImage? = { return NSURL(string: self.icon).flatMap { NSData(contentsOfURL: $0) }.flatMap { UIImage(data: $0) } }() override class func ignoredProperties() -> [String] { return ["iconImage"] } }
mit
7e5fe11e45d318e89ad501ebcccde017
21.625
107
0.626556
4.016667
false
false
false
false
xiongxiong/TagList
Framework/SwiftTagList/Tag.swift
1
3517
// // Tag.swift // TagList // // Created by 王继荣 on 14/12/2016. // Copyright © 2016 wonderbear. All rights reserved. // import UIKit protocol TagDelegate: NSObjectProtocol { func tagUpdated() func tagActionTriggered(tag: Tag, action: TagAction) } open class Tag: UIView { weak var delegate: TagDelegate? weak var stateDelegate: TagStateDelegate? public private(set) var content: TagPresentable public var wrappers: [TagWrapper] = [] { didSet { update() } } public var padding: UIEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3) { didSet { update() } } public var enableSelect: Bool = true { didSet { update() } } public var isSelected: Bool { get { return content.isSelected } set { if isSelected != newValue { content.isSelected = newValue onSelect?(self) update() } } } private var tagContent: TagContent! private var wrapped: TagWrapper! private var tapGestureRecognizer: UITapGestureRecognizer! private var onSelect: ((Tag) -> Void)? open override var intrinsicContentSize: CGSize { let size = wrapped.intrinsicContentSize return CGSize(width: size.width + padding.left + padding.right, height: size.height + padding.top + padding.bottom) } public init(content: TagPresentable, onInit: ((Tag) -> Void)? = nil, onSelect: ((Tag) -> Void)? = nil) { self.content = content self.onSelect = onSelect super.init(frame: CGRect.zero) onInit?(self) tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTap)) addGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer.numberOfTapsRequired = 1 clipsToBounds = true update() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update() { subviews.forEach { (view) in view.removeFromSuperview() } tagContent = content.createTagContent() tagContent.actionDelegate = self stateDelegate = tagContent stateDelegate?.tagSelected(isSelected) wrapped = TagWrapper().wrap(target: tagContent) wrapped = wrappers.reduce(wrapped) { (result, element) in element.wrap(wrapper: result) } addSubview(wrapped) wrapped.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: wrapped, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: wrapped, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) delegate?.tagUpdated() } func onTap() { if enableSelect { isSelected = !isSelected } else { isSelected = false } tagActionTriggered(action: .tap) } } extension Tag: TagActionDelegate { public func tagActionTriggered(action: TagAction) { delegate?.tagActionTriggered(tag: self, action: action) } } public enum TagAction { case tap case remove case custom(action: String) }
mit
a3daed31e55842b059359dd024b769a7
27.306452
159
0.603989
4.868239
false
false
false
false
iOS-Swift-Developers/Swift
实战前技术点/3.JQPageView/JQPageView/JQPageView/JQTitleStyle.swift
1
1410
// // JQTitleStyle.swift // JQPageView // // Created by 韩俊强 on 2017/7/18. // Copyright © 2017年 HaRi. All rights reserved. // import UIKit class JQTitleStyle { /// 是否是滚动的Title var isScrollEnable : Bool = false /// 普通Title颜色 var normalColor : UIColor = UIColor(r: 0, g: 0, b: 0) /// 选中Title颜色 var selectedColor : UIColor = UIColor(r: 255, g: 127, b: 0) /// Title字体大小 var font : UIFont = UIFont.systemFont(ofSize: 14.0) /// 滚动Title的字体间距 var titleMargin : CGFloat = 20 /// titleView的高度 var titleHeight : CGFloat = 44 /// titleView的背景颜色 var titleBgColor : UIColor = .clear /// 是否显示底部滚动条 var isShowBottomLine : Bool = false /// 底部滚动条颜色 var bottomLineColor : UIColor = UIColor.orange /// 底部滚动条高度 var bottomLineH : CGFloat = 2 /// 是都进行缩放 var isNeedScale : Bool = false var scaleRange : CGFloat = 1.2 /// 是否显示遮盖 var isShowCover : Bool = false /// 遮盖背景颜色 var coverBgColor : UIColor = UIColor.lightGray /// 文字&遮盖间隙 var coverMargin : CGFloat = 5 /// 遮盖的高度 var coverH : CGFloat = 0 /// 遮盖的宽度 var coverW : CGFloat = 0 /// 设置圆角大小 var coverRadius : CGFloat = 12 }
mit
621c1b55b04ae1f79f8deaaf891308a9
23.18
63
0.607113
3.801887
false
false
false
false
P0ed/Fx
Sources/FxTestKit/FxTestArranger+ReactiveOperator.swift
1
1947
import Fx import Foundation import QuartzCore public extension FxTestArranger where Target: ReactiveOperator { @discardableResult func assert(_ closure: ([TimedValue<Target.ReturnValues>]) -> Void) -> Self { let factory = targetGenerator() let expectation = createExpectation() var collectedValues = [TimedValue<Target.ReturnValues>]() let startedTime = CACurrentMediaTime() let sink: (Target.ReturnValues) -> Void = { let time = CACurrentMediaTime() - startedTime collectedValues.append(timed(at: Int(floor(time / ReactiveOperatorContext.realClockMultiplier)), value: $0)) collectedValues.count == factory.expectedReturns ? expectation.fulfill() : () } let contextEngine = createContext() let disposable = factory.generator(contextEngine.context, sink) waitForExpectation(expectation) disposable.dispose() contextEngine.disposable.dispose() closure(collectedValues) return self } @discardableResult func assertValues(_ closure: ([Target.ReturnValues]) -> Void) -> Self { assert { closure($0.map(\.value)) } } } private func createContext() -> (disposable: ManualDisposable, context: ReactiveOperatorContext) { var isStopped = false var accumulatedValues = [TimedValue<() -> Void>]() let context = ReactiveOperatorContext { time, value in accumulatedValues.append(.init(time: time, value: value)) } let engineStartTime = CACurrentMediaTime() func engineCycle() { let elapsedTime = CACurrentMediaTime() - engineStartTime accumulatedValues .removeAll { timedValue in with(elapsedTime >= CFTimeInterval(timedValue.time) * ReactiveOperatorContext.realClockMultiplier) { guard $0 else { return } DispatchQueue.main.async { timedValue.value() } } } guard !isStopped else { return } DispatchQueue.main.async(execute: engineCycle) } DispatchQueue.main.async(execute: engineCycle) return ( ManualDisposable { isStopped = true }, context ) }
mit
fbeb14c3d74f01a1be756fc335a82727
28.953846
111
0.734977
4.022727
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
HTWDresden/HTWDresden/MealMainViewController.swift
1
1201
import UIKit class MealMainViewController: UIViewController { var tableView = UITableView() var meals = [MensaData]() override func viewDidLoad() { super.viewDidLoad() tableView.frame = view.bounds tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] tableView.delegate = self tableView.dataSource = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") self.view.addSubview(tableView) } } extension MealMainViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.textLabel?.text = meals[indexPath.row].strTitle cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let controller = MealDetailViewController() self.navigationController?.pushViewController(controller, animated: true) } }
gpl-2.0
8db6192ab67a5a5d0e4aa22685972724
30.631579
106
0.796836
4.882114
false
false
false
false
cweatureapps/SwiftScraper
Pods/Observable-Swift/Observable-Swift/TupleObservable.swift
2
2218
// // TupleObservable.swift // Observable-Swift // // Created by Leszek Ślażyński on 20/06/14. // Copyright (c) 2014 Leszek Ślażyński. All rights reserved. // public class PairObservable<O1: AnyObservable, O2: AnyObservable> : OwnableObservable { internal typealias T1 = O1.ValueType internal typealias T2 = O2.ValueType public typealias ValueType = (T1, T2) public private(set) var beforeChange = EventReference<ValueChange<(T1, T2)>>() public private(set) var afterChange = EventReference<ValueChange<(T1, T2)>>() internal var first : T1 internal var second : T2 public var value : (T1, T2) { return (first, second) } private let _base1 : O1 private let _base2 : O2 public init (_ o1: O1, _ o2: O2) { _base1 = o1 _base2 = o2 first = o1.value second = o2.value o1.beforeChange.add(owner: self) { [weak self] c1 in let oldV = (c1.oldValue, self!.second) let newV = (c1.newValue, self!.second) let change = ValueChange(oldV, newV) self!.beforeChange.notify(change) } o1.afterChange.add(owner: self) { [weak self] c1 in let nV1 = c1.newValue self!.first = nV1 let oldV = (c1.oldValue, self!.second) let newV = (c1.newValue, self!.second) let change = ValueChange(oldV, newV) self!.afterChange.notify(change) } o2.beforeChange.add(owner: self) { [weak self] c2 in let oldV = (self!.first, c2.oldValue) let newV = (self!.first, c2.newValue) let change = ValueChange(oldV, newV) self!.beforeChange.notify(change) } o2.afterChange.add(owner: self) { [weak self] c2 in let nV2 = c2.newValue self!.second = nV2 let oldV = (self!.first, c2.oldValue) let newV = (self!.first, c2.newValue) let change = ValueChange(oldV, newV) self!.afterChange.notify(change) } } } public func & <O1 : AnyObservable, O2: AnyObservable> (x: O1, y: O2) -> PairObservable<O1, O2> { return PairObservable(x, y) }
mit
f51c4c841a99d54fcc37e6bd8af5332f
32.515152
96
0.579566
3.62623
false
false
false
false
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/UV/UV/Handle.swift
111
10266
//===--- Handle.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 Boilerplate import CUV public protocol uv_handle_type { func cast<T>() -> UnsafeMutablePointer<T> func cast<T>() -> UnsafePointer<T> func isNil() -> Bool func testNil() throws mutating func nullify() static func alloc() -> Self mutating func dealloc() } extension UnsafeMutablePointer : uv_handle_type { public func cast<T>() -> UnsafeMutablePointer<T> { return UnsafeMutablePointer<T>(self) } public func cast<T>() -> UnsafePointer<T> { return UnsafePointer<T>(self) } public func isNil() -> Bool { return self == nil } public func testNil() throws { if isNil() { throw Error.HandleClosed } } public mutating func nullify() { self = nil } public static func alloc() -> UnsafeMutablePointer { return UnsafeMutablePointer(allocatingCapacity: 1) } mutating public func dealloc() { self.deinitialize(count: 1) self.deallocateCapacity(1) } } public typealias uv_handle_p = UnsafeMutablePointer<uv_handle_t> protocol PropertyType { associatedtype Object associatedtype `Type` static func name() -> String static func getterValue() -> `Type` static func function() -> (Object, UnsafeMutablePointer<`Type`>) -> Int32 static func read(object:Object) throws -> `Type` static func write(object:Object, value:`Type`) throws } extension PropertyType { static func read(object:Object) throws -> Type { return try Error.handle { code in var value:Type = getterValue() code = function()(object, &value) return value } } static func write(object:Object, value:Type) throws { var value:Type = value try Error.handle { function()(object, &value) } } } extension PropertyType { static func readNoThrow(object:Object) -> Type? { return try? read(object) } static func writeNoThrow(object:Object, value:Type?) { if let value = value { do { try write(object, value: value) } catch let e as Error { print(e.description) } catch { print("Unknown error occured while setting ", name()) } } } } private protocol BufferPropertyType : PropertyType { } private extension BufferPropertyType where Type == Int32 { static func getterValue() -> Type { return 0 } } private class SendBufferSizeProperty : BufferPropertyType { typealias Object = uv_handle_p typealias `Type` = Int32 static func name() -> String { return "send buffer size" } static func function() -> (Object, UnsafeMutablePointer<Type>) -> Int32 { return uv_send_buffer_size } } private class RecvBufferSizeProperty : BufferPropertyType { typealias Object = uv_handle_p typealias `Type` = Int32 static func name() -> String { return "recv buffer size" } static func function() -> (Object, UnsafeMutablePointer<Type>) -> Int32 { return uv_recv_buffer_size } } public protocol HandleType : AnyObject { var baseHandle:uv_handle_p {get} var loop:Loop? {get} var active:Bool {get} var closing:Bool {get} func close() func ref() throws func unref() throws var referenced:Bool {get} //present, because properties can not throw. So both ways func getSendBufferSize() throws -> Int32 func setSendBufferSize(size:Int32) throws var sendBufferSize:Int32? {get set} //present, because properties can not throw. So both ways func getRecvBufferSize() throws -> Int32 func setRecvBufferSize(size:Int32) throws var recvBufferSize:Int32? {get set} //present, because properties can not throw. So both ways func getFileno() throws -> uv_os_fd_t var fileno:uv_os_fd_t? {get} } public class HandleBase { private var _baseHandle:uv_handle_p? public var baseHandle:uv_handle_p { get { if _baseHandle == nil { _baseHandle = getBaseHandle() } return _baseHandle! } set { _baseHandle = newValue } } func getBaseHandle() -> uv_handle_p { return nil } func clearHandle() { baseHandle.nullify() } } public class Handle<Type : uv_handle_type> : HandleBase, HandleType { public var handle:Type override func getBaseHandle() -> uv_handle_p { return self.handle.cast() } override func clearHandle() { super.clearHandle() handle.nullify() } init(_ initializer:(Type)->Int32) throws { self.handle = Type.alloc() super.init() do { try Error.handle { initializer(self.handle) } baseHandle.pointee.data = UnsafeMutablePointer<Void>(OpaquePointer(bitPattern: Unmanaged.passRetained(self))) } catch let e { //cleanum if not created handle.dealloc() throw e } } private static func doWithHandle<Handle: uv_handle_type, Ret>(handle: Handle, fun:(Handle) throws -> Ret) throws -> Ret { try handle.testNil() return try fun(handle) } private func doWithBaseHandle<Ret>(fun:(uv_handle_p) throws -> Ret) throws -> Ret { return try Handle.doWithHandle(baseHandle, fun: fun) } func doWithHandle<Ret>(fun:(Type) throws -> Ret) throws -> Ret { return try Handle.doWithHandle(handle, fun: fun) } public var loop:Loop? { get { return try? doWithBaseHandle { handle in Loop(loop: handle.pointee.loop) } } } public var active:Bool { get { return !baseHandle.isNil() && uv_is_active(baseHandle) != 0 } } public var closing:Bool { get { return baseHandle.isNil() || uv_is_closing(baseHandle) != 0 } } //uv_close public func close() { if !baseHandle.isNil() { uv_close(baseHandle, handle_close_cb) } } public func ref() throws { try doWithBaseHandle { _ in uv_ref(self.baseHandle) } } public func unref() throws { try doWithBaseHandle { _ in uv_unref(self.baseHandle) } } public var referenced:Bool { get { return !baseHandle.isNil() && uv_has_ref(baseHandle) != 0 } } //uv_handle_size //present, because properties can not throw. So both ways public func getSendBufferSize() throws -> Int32 { return try doWithBaseHandle { handle in try SendBufferSizeProperty.read(handle) } } public func setSendBufferSize(size:Int32) throws { try doWithBaseHandle { handle in try SendBufferSizeProperty.write(handle, value: size) } } public var sendBufferSize:Int32? { get { return try? doWithBaseHandle { handle in return try SendBufferSizeProperty.read(handle) } } set { do { try doWithBaseHandle { handle in SendBufferSizeProperty.writeNoThrow(handle, value: newValue) } } catch { } } } //present, because properties can not throw. So both ways public func getRecvBufferSize() throws -> Int32 { return try doWithBaseHandle { handle in try RecvBufferSizeProperty.read(handle) } } public func setRecvBufferSize(size:Int32) throws { try doWithBaseHandle { handle in try RecvBufferSizeProperty.write(handle, value: size) } } public var recvBufferSize:Int32? { get { return try? doWithBaseHandle { handle in return try RecvBufferSizeProperty.read(handle) } } set { do { try doWithBaseHandle { handle in RecvBufferSizeProperty.writeNoThrow(handle, value: newValue) } } catch { } } } //present, because properties can not throw. So both ways public func getFileno() throws -> uv_os_fd_t { return try doWithBaseHandle { handle in try Error.handle { code in var fileno = uv_os_fd_t() code = uv_fileno(handle, &fileno) return fileno } } } public var fileno:uv_os_fd_t? { get { return try? getFileno() } } } extension HandleType { static func fromHandle(handle:uv_handle_type) -> Self { let handle:uv_handle_p = handle.cast() return Unmanaged.fromOpaque(OpaquePointer(handle.pointee.data)).takeUnretainedValue() } } private func handle_close_cb(handle:uv_handle_p) { if handle.pointee.data != nil { let object = Unmanaged<HandleBase>.fromOpaque(OpaquePointer(handle.pointee.data)).takeRetainedValue() handle.pointee.data = nil object.clearHandle() } handle.deinitialize(count: 1) handle.deallocateCapacity(1) }
mit
6931a125637314ce995f920496a5b46d
25.667532
125
0.573057
4.616007
false
false
false
false
Haina/IBDemo
IBInspectable/MyCustomView/CustomView.swift
1
809
// // CustomView.swift // IBInspectable // // Created by 张凤娟 on 15/6/17. // Copyright (c) 2015年 张凤娟. All rights reserved. // //{ // @IBInspectable var borderColor: UIColor = UIColor.clearColor(); // @IBInspectable var borderWidth: CGFloat = 0; // @IBInspectable var cornerRadius: CGFloat = 0; //} import UIKit @IBDesignable class CustomView: UIView { @IBInspectable var borderColor: UIColor = UIColor.clearColor(){ didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } }
apache-2.0
b3794f17786208b0bfd5d6e7f2b5024b
19.921053
69
0.601258
4.320652
false
false
false
false
timvermeulen/DraughtsCloud
Sources/App/Models/Move/Move+Draughts.swift
1
1313
import Draughts extension Move { init(_ move: Draughts.Move, from start: StartPosition, to end: EndPosition) throws { guard Self.player == move.player, let start = start.id?.int, let end = end.id?.int else { throw Abort.serverError } self.init( start: start, end: end, bitboards: Bitboards(move: move) ) } func getNotation() throws -> String { let startPosition = Draughts.Position(try getStartPosition().toAnyPosition()) let endPosition = Draughts.Position(try getEndPosition().toAnyPosition()) guard let move = startPosition.legalMoves.first(where: { $0.endPosition == endPosition }) else { throw Abort.serverError } return move.unambiguousNotation } } extension AnyMove { init(_ move: Draughts.Move, from start: AnyPosition, to end: AnyPosition) throws { switch (move.player, start, end) { case (.white, .white(let start), .black(let end)): self = .white(try WhiteMove(move, from: start, to: end)) case (.black, .black(let start), .white(let end)): self = .black(try BlackMove(move, from: start, to: end)) default: throw Abort.serverError } } }
mit
b615292a6dd5489b53413a31c3731b97
33.552632
130
0.586443
4.115987
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/Launch/FileSystemLayoutMigration.swift
1
5333
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /// The `FileSystemLayoutMigration` copies data persisted in the `Documents` directory /// to a location in `Application Support` and then removes the data from `Documents`. /// Some files are renamed for consistentency. This class is very defensive in order to /// reduce the risk of any data corruption or loss. final class FileSystemLayoutMigration { /// Migration errors. enum Error: Swift.Error, Equatable { /// The migration has already been completed. case migrationAlreadyCompleted /// The migration failed and cleanup would result in data loss. case migrationFailed } /// A `Step` in the migration. struct Step: Equatable { /// The path to copy from. let from: String /// The path to copy to. let to: String } // MARK: - Properties /// The ordered steps in the migration. let steps: [Step] = [ Step(from: "accounts", to: "accounts"), Step(from: "Science Journal", to: "root"), Step(from: "DeletedData", to: "root/DeletedData"), Step(from: "ScienceJournal.sqlite", to: "root/sensor_data.sqlite"), Step(from: "ScienceJournal.sqlite-shm", to: "root/sensor_data.sqlite-shm"), Step(from: "ScienceJournal.sqlite-wal", to: "root/sensor_data.sqlite-wal"), ] /// Whether or not a migration is needed. /// /// Check this property before calling `execute`. /// /// - Returns: true if a migration is needed, otherwise false. var isNeeded: Bool { return devicePreferenceManager.fileSystemLayoutVersion < postMigrationFileSystemLayoutVersion } private let fromBaseDirectory: URL private let toBaseDirectory: URL private let devicePreferenceManager: DevicePreferenceManager private let fileManager: FileManager = .default private let postMigrationFileSystemLayoutVersion: FileSystemLayout.Version = .two private var executeCompleted = false // MARK: - Public /// Designated Initializer. /// /// - Parameters: /// - fromBaseDirectory: the base directory for all from paths. /// - toBaseDirectory: the base directory for all to paths. /// - devicePreferenceManager: the device preference manager. init(from fromBaseDirectory: URL, to toBaseDirectory: URL, devicePreferenceManager: DevicePreferenceManager = DevicePreferenceManager()) { self.fromBaseDirectory = fromBaseDirectory self.toBaseDirectory = toBaseDirectory self.devicePreferenceManager = devicePreferenceManager } /// Execute the migration. /// /// Call `isNeeded` to see if a migration is needed before calling this method. After this /// method completes, call `cleanup` to clean up the legacy directory structure. /// /// - Throws: /// - migrationAlreadyCompleted: if the file system is not in the expected state. /// - Error: a `FileManager` error if something goes wrong. func execute() throws { guard isNeeded else { throw Error.migrationAlreadyCompleted } try prepareToBaseDirectory() try steps .map {( fromBaseDirectory.appendingPathComponent($0.from), toBaseDirectory.appendingPathComponent($0.to) )} .forEach(copyItem(at:to:)) executeCompleted = true } private func prepareToBaseDirectory() throws { if fileManager.fileExists(atPath: toBaseDirectory.path) { try fileManager.removeItem(at: toBaseDirectory) } try fileManager.createDirectory(at: toBaseDirectory, withIntermediateDirectories: true) URL.excludeFromiCloudBackups(url: toBaseDirectory) } private func copyItem(at atURL: URL, to toURL: URL) throws { if fileManager.fileExists(atPath: atURL.path) { let parentDirectory = toURL.deletingLastPathComponent() if !fileManager.fileExists(atPath: parentDirectory.path) { try fileManager.createDirectory(at: parentDirectory, withIntermediateDirectories: true) } try fileManager.copyItem(at: atURL, to: toURL) } } /// Clean up known files and directories in the `fromBaseDirectory`. /// /// You must call `execute` before calling this method. /// /// - Throws: /// - migrationFailed: if the migration did not complete successfully. /// - Error: a `FileManager` error if something goes wrong during cleanup. func cleanup() throws { guard executeCompleted else { throw Error.migrationFailed } try steps .map { fromBaseDirectory.appendingPathComponent($0.from) } .forEach(removeItem(at:)) devicePreferenceManager.fileSystemLayoutVersion = postMigrationFileSystemLayoutVersion } private func removeItem(at atURL: URL) throws { if fileManager.fileExists(atPath: atURL.path) { try fileManager.removeItem(at: atURL) } } }
apache-2.0
d3d69a680b939ba6b554e24b47d8d14c
32.540881
97
0.709919
4.62934
false
false
false
false
wuzer/douyuTV
douyuTV/douyuTV/Class/HomeViewController/AmuseViewController.swift
1
1379
// // AmuseViewController.swift // douyuTV // // Created by Jefferson on 2016/11/2. // Copyright © 2016年 Jefferson. All rights reserved. // import UIKit private let KMenuViewHeight: CGFloat = 200 class AmuseViewController: BaseAnchorViewController { fileprivate lazy var amuseViewModel = AmuseViewModel() fileprivate lazy var menuView: AmuseMenuView = { let rect = CGRect(x: 0, y: -KMenuViewHeight, width: KScreenWidth, height: KMenuViewHeight) let menuView = AmuseMenuView(frame: rect) return menuView }() override func viewDidLoad() { super.viewDidLoad() } } extension AmuseViewController { override func setupUI() { super.setupUI() collectionView.addSubview(menuView) collectionView.contentInset = UIEdgeInsets(top: KMenuViewHeight, left: 0, bottom: 0, right: 0) } } // MARK: loadData extension AmuseViewController { override func loadData() { // baseViewModel = amuseViewModel amuseViewModel.loadAmuseData { self.collectionView.reloadData() var tempAnchors = self.amuseViewModel.anchorGroups tempAnchors.removeFirst() // assignment self.menuView.anchors = tempAnchors self.showHaveDataView() } } }
mit
b09628600e7512dbef4b812d5fca51cc
21.933333
102
0.628634
5.058824
false
false
false
false
julienbodet/wikipedia-ios
WMF Framework/CollectionViewEditController.swift
1
24722
import Foundation public enum CollectionViewCellSwipeType { case primary, secondary, none } enum CollectionViewCellState { case idle, open } class EditBarButton: UIBarButtonItem { var systemItem: UIBarButtonSystemItem? } public protocol CollectionViewEditControllerNavigationDelegate: class { func didChangeEditingState(from oldEditingState: EditingState, to newEditingState: EditingState, rightBarButton: UIBarButtonItem?, leftBarButton: UIBarButtonItem?) // same implementation for 2/3 func didSetBatchEditToolbarHidden(_ batchEditToolbarViewController: BatchEditToolbarViewController, isHidden: Bool, with items: [UIButton]) // has default implementation func newEditingState(for currentEditingState: EditingState, fromEditBarButtonWithSystemItem systemItem: UIBarButtonSystemItem) -> EditingState func emptyStateDidChange(_ empty: Bool) var currentTheme: Theme { get } } public class CollectionViewEditController: NSObject, UIGestureRecognizerDelegate, ActionDelegate { let collectionView: UICollectionView struct SwipeInfo { let translation: CGFloat let velocity: CGFloat let state: SwipeState } var swipeInfoByIndexPath: [IndexPath: SwipeInfo] = [:] var configuredCellsByIndexPath: [IndexPath: SwipeableCell] = [:] var activeCell: SwipeableCell? { guard let indexPath = activeIndexPath else { return nil } return collectionView.cellForItem(at: indexPath) as? SwipeableCell } public var isActive: Bool { return activeIndexPath != nil } var activeIndexPath: IndexPath? { didSet { if activeIndexPath != nil { editingState = .swiping } else { editingState = isCollectionViewEmpty ? .empty : .none } } } var isRTL: Bool = false var initialSwipeTranslation: CGFloat = 0 let maxExtension: CGFloat = 10 let panGestureRecognizer: UIPanGestureRecognizer let longPressGestureRecognizer: UILongPressGestureRecognizer public init(collectionView: UICollectionView) { self.collectionView = collectionView panGestureRecognizer = UIPanGestureRecognizer() longPressGestureRecognizer = UILongPressGestureRecognizer() super.init() panGestureRecognizer.addTarget(self, action: #selector(handlePanGesture)) longPressGestureRecognizer.addTarget(self, action: #selector(handleLongPressGesture)) if let gestureRecognizers = self.collectionView.gestureRecognizers { var otherGestureRecognizer: UIGestureRecognizer for gestureRecognizer in gestureRecognizers { otherGestureRecognizer = gestureRecognizer is UIPanGestureRecognizer ? panGestureRecognizer : longPressGestureRecognizer gestureRecognizer.require(toFail: otherGestureRecognizer) } } panGestureRecognizer.delegate = self self.collectionView.addGestureRecognizer(panGestureRecognizer) longPressGestureRecognizer.delegate = self longPressGestureRecognizer.minimumPressDuration = 0.05 longPressGestureRecognizer.require(toFail: panGestureRecognizer) self.collectionView.addGestureRecognizer(longPressGestureRecognizer) NotificationCenter.default.addObserver(self, selector: #selector(close), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(articleWasUpdated(_:)), name: NSNotification.Name.WMFArticleUpdated, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func articleWasUpdated(_ notification: Notification) { for (indexPath, cell) in configuredCellsByIndexPath { cell.actions = availableActions(at: indexPath) } } public func swipeTranslationForItem(at indexPath: IndexPath) -> CGFloat? { return swipeInfoByIndexPath[indexPath]?.translation } public func configureSwipeableCell(_ cell: UICollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) { guard !layoutOnly, let cell = cell as? SwipeableCell else { return } cell.actions = availableActions(at: indexPath) configuredCellsByIndexPath[indexPath] = cell guard let info = swipeInfoByIndexPath[indexPath] else { return } cell.swipeState = info.state cell.actionsView.delegate = self cell.swipeTranslation = info.translation } public func deconfigureSwipeableCell(_ cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { configuredCellsByIndexPath.removeValue(forKey: indexPath) } public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer === panGestureRecognizer { return panGestureRecognizerShouldBegin(panGestureRecognizer) } if gestureRecognizer === longPressGestureRecognizer { return longPressGestureRecognizerShouldBegin(longPressGestureRecognizer) } return false } public weak var delegate: ActionDelegate? public func didPerformAction(_ action: Action) -> Bool { if let cell = activeCell { return cell.actionsView.updateConfirmationImage(for: action) { self.delegatePerformingAction(action) } } return self.delegatePerformingAction(action) } private func delegatePerformingAction(_ action: Action) -> Bool { guard action.indexPath == activeIndexPath else { return self.delegate?.didPerformAction(action) ?? false } let activatedAction = action.type == .delete ? action : nil closeActionPane(with: activatedAction) { (finished) in let _ = self.delegate?.didPerformAction(action) } return true } public func willPerformAction(_ action: Action) -> Bool { return delegate?.willPerformAction(action) ?? didPerformAction(action) } public func availableActions(at indexPath: IndexPath) -> [Action] { return delegate?.availableActions(at: indexPath) ?? [] } func panGestureRecognizerShouldBegin(_ gestureRecognizer: UIPanGestureRecognizer) -> Bool { var shouldBegin = false defer { if !shouldBegin { closeActionPane() } } guard let delegate = delegate else { return shouldBegin } let position = gestureRecognizer.location(in: collectionView) guard let indexPath = collectionView.indexPathForItem(at: position) else { return shouldBegin } let velocity = gestureRecognizer.velocity(in: collectionView) // Begin only if there's enough x velocity. if fabs(velocity.y) >= fabs(velocity.x) { return shouldBegin } defer { if let indexPath = activeIndexPath { initialSwipeTranslation = swipeInfoByIndexPath[indexPath]?.translation ?? 0 } } isRTL = collectionView.effectiveUserInterfaceLayoutDirection == .rightToLeft let isOpenSwipe = isRTL ? velocity.x > 0 : velocity.x < 0 if !isOpenSwipe { // only allow closing swipes on active cells shouldBegin = indexPath == activeIndexPath return shouldBegin } if activeIndexPath != nil && activeIndexPath != indexPath { closeActionPane() } guard activeIndexPath == nil else { shouldBegin = true return shouldBegin } activeIndexPath = indexPath guard let cell = activeCell, cell.actions.count > 0 else { activeIndexPath = nil return shouldBegin } shouldBegin = true return shouldBegin } func longPressGestureRecognizerShouldBegin(_ gestureRecognizer: UILongPressGestureRecognizer) -> Bool { guard let cell = activeCell else { return false } // Don't allow the cancel gesture to recognize if any of the touches are within the actions view. let numberOfTouches = gestureRecognizer.numberOfTouches for touchIndex in 0..<numberOfTouches { let touchLocation = gestureRecognizer.location(ofTouch: touchIndex, in: cell.actionsView) let touchedActionsView = cell.actionsView.bounds.contains(touchLocation) return !touchedActionsView } return true } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer is UILongPressGestureRecognizer { return true } if gestureRecognizer is UIPanGestureRecognizer{ return otherGestureRecognizer is UILongPressGestureRecognizer } return false } private lazy var batchEditToolbarViewController: BatchEditToolbarViewController = { let batchEditToolbarViewController = BatchEditToolbarViewController(nibName: "BatchEditToolbarViewController", bundle: Bundle.wmf) batchEditToolbarViewController.items = self.batchEditToolbarItems return batchEditToolbarViewController }() @objc func handlePanGesture(_ sender: UIPanGestureRecognizer) { guard let indexPath = activeIndexPath, let cell = activeCell else { return } cell.actionsView.delegate = self let deltaX = sender.translation(in: collectionView).x let velocityX = sender.velocity(in: collectionView).x var swipeTranslation = deltaX + initialSwipeTranslation let normalizedSwipeTranslation = isRTL ? swipeTranslation : -swipeTranslation let normalizedMaxSwipeTranslation = abs(cell.swipeTranslationWhenOpen) switch (sender.state) { case .began: cell.swipeState = .swiping fallthrough case .changed: if normalizedSwipeTranslation < 0 { let normalizedSqrt = maxExtension * log(abs(normalizedSwipeTranslation)) swipeTranslation = isRTL ? 0 - normalizedSqrt : normalizedSqrt } if normalizedSwipeTranslation > normalizedMaxSwipeTranslation { let maxWidth = normalizedMaxSwipeTranslation let delta = normalizedSwipeTranslation - maxWidth swipeTranslation = isRTL ? maxWidth + (maxExtension * log(delta)) : 0 - maxWidth - (maxExtension * log(delta)) } cell.swipeTranslation = swipeTranslation swipeInfoByIndexPath[indexPath] = SwipeInfo(translation: swipeTranslation, velocity: velocityX, state: .swiping) case .cancelled: fallthrough case .failed: fallthrough case .ended: let isOpen: Bool let velocityAdjustment = 0.3 * velocityX if isRTL { isOpen = swipeTranslation + velocityAdjustment > 0.5 * cell.swipeTranslationWhenOpen } else { isOpen = swipeTranslation + velocityAdjustment < 0.5 * cell.swipeTranslationWhenOpen } if isOpen { openActionPane() } else { closeActionPane() } fallthrough default: break } } @objc func handleLongPressGesture(_ sender: UILongPressGestureRecognizer) { guard activeIndexPath != nil else { return } switch (sender.state) { case .ended: closeActionPane() default: break } } var areSwipeActionsDisabled: Bool = false { didSet { longPressGestureRecognizer.isEnabled = !areSwipeActionsDisabled panGestureRecognizer.isEnabled = !areSwipeActionsDisabled } } // MARK: - States func openActionPane(_ completion: @escaping (Bool) -> Void = {_ in }) { collectionView.allowsSelection = false guard let cell = activeCell, let indexPath = activeIndexPath else { completion(false) return } let targetTranslation = cell.swipeTranslationWhenOpen let velocity = swipeInfoByIndexPath[indexPath]?.velocity ?? 0 swipeInfoByIndexPath[indexPath] = SwipeInfo(translation: targetTranslation, velocity: velocity, state: .open) cell.swipeState = .open animateActionPane(of: cell, to: targetTranslation, with: velocity, completion: completion) } func closeActionPane(with expandedAction: Action? = nil, _ completion: @escaping (Bool) -> Void = {_ in }) { collectionView.allowsSelection = true guard let cell = activeCell, let indexPath = activeIndexPath else { completion(false) return } activeIndexPath = nil let velocity = swipeInfoByIndexPath[indexPath]?.velocity ?? 0 swipeInfoByIndexPath[indexPath] = nil if let expandedAction = expandedAction { let translation = isRTL ? cell.bounds.width : 0 - cell.bounds.width animateActionPane(of: cell, to: translation, with: velocity, expandedAction: expandedAction, completion: { (finished) in //don't set isSwiping to false so that the expanded action stays visible through the fade completion(finished) }) } else { animateActionPane(of: cell, to: 0, with: velocity, completion: { (finished: Bool) in cell.swipeState = self.activeIndexPath == indexPath ? .swiping : .closed completion(finished) }) } } func animateActionPane(of cell: SwipeableCell, to targetTranslation: CGFloat, with swipeVelocity: CGFloat, expandedAction: Action? = nil, completion: @escaping (Bool) -> Void = {_ in }) { if let action = expandedAction { UIView.animate(withDuration: 0.3, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: { cell.actionsView.expand(action) cell.swipeTranslation = targetTranslation cell.layoutIfNeeded() }, completion: completion) return } let initialSwipeTranslation = cell.swipeTranslation let animationTranslation = targetTranslation - initialSwipeTranslation let animationDuration: TimeInterval = 0.3 let distanceInOneSecond = animationTranslation / CGFloat(animationDuration) let unitSpeed = distanceInOneSecond == 0 ? 0 : swipeVelocity / distanceInOneSecond UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: unitSpeed, options: [.allowUserInteraction, .beginFromCurrentState], animations: { cell.swipeTranslation = targetTranslation cell.layoutIfNeeded() }, completion: completion) } // MARK: - Batch editing public var isShowingDefaultCellOnly: Bool = false { didSet { guard oldValue != isShowingDefaultCellOnly else { return } editingState = isCollectionViewEmpty || isShowingDefaultCellOnly ? .empty : .none } } public weak var navigationDelegate: CollectionViewEditControllerNavigationDelegate? { willSet { batchEditToolbarViewController.remove() } didSet { guard oldValue !== navigationDelegate else { return } if navigationDelegate == nil { editingState = .unknown } else { editingState = isCollectionViewEmpty || isShowingDefaultCellOnly ? .empty : .none } } } private var editableCells: [BatchEditableCell] { guard let editableCells = collectionView.visibleCells as? [BatchEditableCell] else { return [] } return editableCells } public var isBatchEditing: Bool { return editingState == .open } private var editingState: EditingState = .unknown { didSet { guard editingState != oldValue else { return } editingStateDidChange(from: oldValue, to: editingState) } } private func editingStateDidChange(from oldValue: EditingState, to newValue: EditingState) { let rightBarButtonSystemItem: UIBarButtonSystemItem? let leftBarButtonSystemItem: UIBarButtonSystemItem? var isRightBarButtonEnabled = !(isCollectionViewEmpty || isShowingDefaultCellOnly) || shouldShowEditButtonsForEmptyState switch newValue { case .editing: areSwipeActionsDisabled = true leftBarButtonSystemItem = .cancel rightBarButtonSystemItem = .done isRightBarButtonEnabled = true if oldValue == .open { transformBatchEditPane(for: editingState) } case .swiping: leftBarButtonSystemItem = nil rightBarButtonSystemItem = .edit case .open: leftBarButtonSystemItem = nil rightBarButtonSystemItem = .cancel transformBatchEditPane(for: editingState) case .closed: leftBarButtonSystemItem = nil rightBarButtonSystemItem = .edit transformBatchEditPane(for: editingState) case .empty: leftBarButtonSystemItem = nil rightBarButtonSystemItem = shouldShowEditButtonsForEmptyState ? .edit : nil isBatchEditToolbarHidden = true default: leftBarButtonSystemItem = nil rightBarButtonSystemItem = .edit } var rightButton: EditBarButton? var leftButton: EditBarButton? if let barButtonSystemItem = rightBarButtonSystemItem { rightButton = EditBarButton(barButtonSystemItem: barButtonSystemItem, target: self, action: #selector(barButtonPressed(_:))) rightButton?.systemItem = barButtonSystemItem } if let barButtonSystemItem = leftBarButtonSystemItem { leftButton = EditBarButton(barButtonSystemItem: barButtonSystemItem, target: self, action: #selector(barButtonPressed(_:))) leftButton?.systemItem = barButtonSystemItem } leftButton?.tag = editingState.tag rightButton?.tag = editingState.tag rightButton?.isEnabled = isRightBarButtonEnabled let font = rightBarButtonSystemItem != .edit ? UIFont.wmf_font(.semiboldBody) : UIFont.wmf_font(.body) let attributes = [NSAttributedStringKey.font: font] rightButton?.setTitleTextAttributes(attributes, for: .normal) leftButton?.setTitleTextAttributes(attributes, for: .normal) navigationDelegate?.didChangeEditingState(from: oldValue, to: editingState, rightBarButton: rightButton, leftBarButton: leftButton) } private func transformBatchEditPane(for state: EditingState, animated: Bool = true) { guard !isCollectionViewEmpty else { return } let willOpen = state == .open areSwipeActionsDisabled = willOpen collectionView.allowsMultipleSelection = willOpen isBatchEditToolbarHidden = !willOpen for cell in editableCells { guard cell.isBatchEditable else { continue } if animated { // ensure layout is in the start anim state cell.isBatchEditing = !willOpen cell.layoutIfNeeded() UIView.animate(withDuration: 0.3, delay: 0.1, options: [.allowUserInteraction, .beginFromCurrentState, .curveEaseInOut], animations: { cell.isBatchEditing = willOpen cell.layoutIfNeeded() }) } else { cell.isBatchEditing = willOpen cell.layoutIfNeeded() } if let themeableCell = cell as? Themeable, let navigationDelegate = navigationDelegate { themeableCell.apply(theme: navigationDelegate.currentTheme) } } if !willOpen { selectedIndexPaths.forEach({ collectionView.deselectItem(at: $0, animated: true) }) batchEditToolbarViewController.setItemsEnabled(false) } } @objc public func close() { guard editingState == .open || editingState == .swiping else { return } if editingState == .swiping { editingState = .none } else { editingState = .closed } closeActionPane() } private func emptyStateDidChange() { if isCollectionViewEmpty || isShowingDefaultCellOnly { editingState = .empty } else { editingState = .none } navigationDelegate?.emptyStateDidChange(isCollectionViewEmpty) } public var isCollectionViewEmpty: Bool = true { didSet { guard oldValue != isCollectionViewEmpty else { return } emptyStateDidChange() } } public var shouldShowEditButtonsForEmptyState: Bool = false @objc private func barButtonPressed(_ sender: EditBarButton) { guard let navigationDelegate = navigationDelegate else { assertionFailure("Unable to set new editing state - navigationDelegate is nil") return } guard let systemItem = sender.systemItem else { assertionFailure("Unable to set new editing state - systemItem is nil") return } let currentEditingState = editingState if currentEditingState == .swiping { closeActionPane() } editingState = navigationDelegate.newEditingState(for: currentEditingState, fromEditBarButtonWithSystemItem: systemItem) } public func changeEditingState(to newEditingState: EditingState) { editingState = newEditingState } public var isTextEditing: Bool = false { didSet { editingState = .editing } } public var isClosed: Bool { let isClosed = editingState != .open if !isClosed { batchEditToolbarViewController.setItemsEnabled(!selectedIndexPaths.isEmpty) } return isClosed } public func transformBatchEditPaneOnScroll() { transformBatchEditPane(for: editingState, animated: false) } private var selectedIndexPaths: [IndexPath] { return collectionView.indexPathsForSelectedItems ?? [] } private var isBatchEditToolbarHidden: Bool = true { didSet { guard collectionView.window != nil else { return } self.navigationDelegate?.didSetBatchEditToolbarHidden(batchEditToolbarViewController, isHidden: self.isBatchEditToolbarHidden, with: self.batchEditToolbarItems) } } private var batchEditToolbarActions: [BatchEditToolbarAction] { guard let delegate = delegate, let actions = delegate.availableBatchEditToolbarActions else { return [] } return actions } @objc public func didPerformBatchEditToolbarAction(with sender: UIBarButtonItem) { let didPerformAction = delegate?.didPerformBatchEditToolbarAction?(batchEditToolbarActions[sender.tag]) ?? false if didPerformAction { editingState = .closed } } private lazy var batchEditToolbarItems: [UIButton] = { var buttons: [UIButton] = [] for (index, action) in batchEditToolbarActions.enumerated() { let button = UIButton(type: .system) button.addTarget(self, action: #selector(didPerformBatchEditToolbarAction(with:)), for: .touchUpInside) button.tag = index button.setTitle(action.title, for: UIControlState.normal) buttons.append(button) button.isEnabled = false } return buttons }() }
mit
86183b2049ddad461338921501e5dfd2
37.507788
200
0.636397
6.314687
false
false
false
false
ryanbaldwin/RealmSwiftFHIR
firekit/fhir-parser-resources/fhir-1.6.0/swift-4.0/template-resource-populatable.swift
1
1482
public override func populate(from other: Any) { guard let o = other as? {{ klass.name }} else { print("Tried to populate \(Swift.type(of: self)) with values from \(Swift.type(of: other)). Skipping.") return } super.populate(from: o) {%- for prop in klass.properties %} {%- if prop.is_array %} for (index, t) in o.{{prop.name}}.enumerated() { guard index < self.{{prop.name}}.count else { // we should always copy in case the same source is being used across several targets // in a single transaction. let val = {{prop|realm_listify}}() val.populate(from: t) self.{{prop.name}}.append(val) continue } self.{{prop.name}}[index].populate(from: t) } while self.{{ prop.name }}.count > o.{{ prop.name }}.count { let objectToRemove = self.{{ prop.name }}.last! self.{{ prop.name }}.removeLast() try! (objectToRemove as? CascadeDeletable)?.cascadeDelete() ?? realm?.delete(objectToRemove) } {%- elif prop|populatable %} FireKit.populate(&self.{{ prop.name}}, from: o.{{ prop.name }}) {%- elif prop|requires_realm_optional %} {{ prop.name }}.value = o.{{ prop.name }}.value {%- elif prop.is_native %} {{ prop.name }} = o.{{prop.name}} {%- endif %} {%- endfor %} }
apache-2.0
0a0478b9aa87a53d75e2351b33454ecd
38.026316
115
0.519568
4.246418
false
false
false
false
sallar/lunchify-swift
Lunchify/VenuesMapViewController.swift
1
3341
// // VenuesMapViewController.swift // Lunchify // // Created by Sallar Kaboli on 9/3/16. // Copyright © 2016 Sallar Kaboli. All rights reserved. // import UIKit import MapKit import UIColor_Hex_Swift class VenuesMapViewController: VenueListViewController { @IBOutlet var mapView: MKMapView! var pointAnnotation: MKPointAnnotation! var pinAnnotationView: MKPinAnnotationView! var hasBeenCentered: Bool = false var annotationsAdded: Bool = false var userLocation: MKUserLocation? override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self mapView.showsUserLocation = true } override func configureView() { super.configureView() } override func venuesDidLoad(_ venues: Venues) { addAnnotations() } func addAnnotations() { if self.venues.count > 0 && !annotationsAdded && hasBeenCentered { annotationsAdded = true for (index, venue) in self.venues.enumerated() { let annotation = Annotation() annotation.coordinate = venue.location!.coordinate annotation.title = venue.name annotation.subtitle = venue.address annotation.index = index mapView.addAnnotation(annotation) } } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowVenue" { let venue = self.venues[(sender as! MKAnnotationView).tag] let controller = (segue.destination as! MenuViewController) controller.venue = venue controller.location = self.location controller.date = venuesService.getMenuDate("EEEE") } } } extension VenuesMapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { self.userLocation = userLocation if (!hasBeenCentered) { hasBeenCentered = true let region = MKCoordinateRegionMakeWithDistance(userLocation.location!.coordinate, 1000, 1000) mapView.setRegion(region, animated: false) self.addAnnotations() } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKPointAnnotation { let themeColor = UIColor("#C2185B") let detailButton = UIButton(type: .detailDisclosure) detailButton.tintColor = themeColor let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "venuePin") pinAnnotationView.pinTintColor = themeColor pinAnnotationView.canShowCallout = true pinAnnotationView.animatesDrop = true pinAnnotationView.rightCalloutAccessoryView = detailButton pinAnnotationView.tag = (annotation as! Annotation).index return pinAnnotationView } return nil } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { performSegue(withIdentifier: "ShowVenue", sender: view) } }
mit
86367c8238aba66d44d2b4e0429945ca
32.069307
129
0.63503
5.748709
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/Pods/APIKit/Sources/RequestType.swift
2
6145
import Foundation import Result /// `RequestType` protocol represents a request for Web API. /// Following 5 items must be implemented. /// - `typealias Response` /// - `var baseURL: NSURL` /// - `var method: HTTPMethod` /// - `var path: String` /// - `func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response` public protocol RequestType { /// The response type associated with the request type. associatedtype Response /// The base URL. var baseURL: NSURL { get } /// The HTTP request method. var method: HTTPMethod { get } /// The path URL component. var path: String { get } /// The convenience property for `queryParameters` and `bodyParameters`. If the implementation of /// `queryParameters` and `bodyParameters` are not provided, the values for them will be computed /// from this property depending on `method`. var parameters: AnyObject? { get } /// The actual parameters for the URL query. The values of this property will be escaped using `URLEncodedSerializetion`. /// If this property is not implemented and `method.prefersQueryParameter` is `true`, the value of this property /// will be computed from `parameters`. var queryParameters: [String: AnyObject]? { get } /// The actual parameters for the HTTP body. If this property is not implemented and `method.prefersQueryParameter` is `false`, /// the value of this property will be computed from `parameters` using `JSONBodyParameters`. var bodyParameters: BodyParametersType? { get } /// The HTTP header fields. In addition to fields defined in this property, `Accept` and `Content-Type` /// fields will be added by `dataParser` and `bodyParameters`. If you define `Accept` and `Content-Type` /// in this property, the values in this property are preferred. var headerFields: [String: String] { get } /// The parser object that states `Content-Type` to accept and parses response body. var dataParser: DataParserType { get } /// Intercepts `NSURLRequest` which is created by `RequestType.buildURLRequest()`. If an error is /// thrown in this method, the result of `Session.sendRequest()` truns `.Failure(.RequestError(error))`. /// - Throws: `ErrorType` func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest /// Intercepts response `AnyObject` and `NSHTTPURLResponse`. If an error is thrown in this method, /// the result of `Session.sendRequest()` turns `.Failure(.ResponseError(error))`. /// The default implementation of this method is provided to throw `RequestError.UnacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` func interceptObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> AnyObject /// Build `Response` instance from raw response object. This method is called after /// `interceptObject(:URLResponse:)` if it does not throw any error. /// - Throws: `ErrorType` func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response } public extension RequestType { public var parameters: AnyObject? { return nil } public var queryParameters: [String: AnyObject]? { guard let parameters = parameters as? [String: AnyObject] where method.prefersQueryParameters else { return nil } return parameters } public var bodyParameters: BodyParametersType? { guard let parameters = parameters where !method.prefersQueryParameters else { return nil } return JSONBodyParameters(JSONObject: parameters) } public var headerFields: [String: String] { return [:] } public var dataParser: DataParserType { return JSONDataParser(readingOptions: []) } public func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest { return URLRequest } public func interceptObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> AnyObject { guard (200..<300).contains(URLResponse.statusCode) else { throw ResponseError.UnacceptableStatusCode(URLResponse.statusCode) } return object } /// Builds `NSURLRequest` from properties of `self`. /// - Throws: `RequestError`, `ErrorType` public func buildURLRequest() throws -> NSURLRequest { let URL = path.isEmpty ? baseURL : baseURL.URLByAppendingPathComponent(path) guard let components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) else { throw RequestError.InvalidBaseURL(baseURL) } let URLRequest = NSMutableURLRequest() if let queryParameters = queryParameters where !queryParameters.isEmpty { components.percentEncodedQuery = URLEncodedSerialization.stringFromDictionary(queryParameters) } if let bodyParameters = bodyParameters { URLRequest.setValue(bodyParameters.contentType, forHTTPHeaderField: "Content-Type") switch try bodyParameters.buildEntity() { case .Data(let data): URLRequest.HTTPBody = data case .InputStream(let inputStream): URLRequest.HTTPBodyStream = inputStream } } URLRequest.URL = components.URL URLRequest.HTTPMethod = method.rawValue URLRequest.setValue(dataParser.contentType, forHTTPHeaderField: "Accept") headerFields.forEach { key, value in URLRequest.setValue(value, forHTTPHeaderField: key) } return (try interceptURLRequest(URLRequest)) } /// Builds `Response` from response `NSData`. /// - Throws: `ResponseError`, `ErrorType` public func parseData(data: NSData, URLResponse: NSHTTPURLResponse) throws -> Response { let parsedObject = try dataParser.parseData(data) let passedObject = try interceptObject(parsedObject, URLResponse: URLResponse) return try responseFromObject(passedObject, URLResponse: URLResponse) } }
mit
0dc794214de7bdc5ad63ec5413753e20
40.52027
131
0.691456
5.25663
false
false
false
false
silence0201/Swift-Study
AdvancedSwift/可选值/A Tour of Optional Techniques - Filtering Out nils with flatMap.playgroundpage/Contents.swift
1
2599
/*: ### Filtering Out `nil`s with `flatMap` If you have a sequence and it contains optionals, you might not care about the `nil` values. In fact, you might just want to ignore them. Suppose you wanted to process only the numbers in an array of strings. This is easily done in a `for` loop using optional pattern matching: */ //#-editable-code let numbers = ["1", "2", "3", "foo"] var sum = 0 for case let i? in numbers.map({ Int($0) }) { sum += i } sum //#-end-editable-code /*: You might also want to use `??` to replace the `nil`s with zeros: */ //#-editable-code numbers.map { Int($0) }.reduce(0) { $0 + ($1 ?? 0) } //#-end-editable-code /*: But really, you just want a version of `map` that filters out `nil` and unwraps the non-`nil` values. Enter the standard library's overload of `flatMap` on sequences, which does exactly that: */ //#-editable-code numbers.flatMap { Int($0) }.reduce(0, +) //#-end-editable-code /*: We've already seen two flattening maps: flattening a sequence mapped to arrays, and flattening an optional mapped to an optional. This is a hybrid of the two: flattening a sequence mapped to an optional. This makes sense if we return to our analogy of an optional being a collection of zero or one thing(s). If that collection were an array, `flatMap` would be exactly what we want. To implement our own version of this operator, let's first define a `flatten` that filters out `nil` values and returns an array of non-optionals: */ //#-editable-code func flatten_sample_impl<S: Sequence, T> (source: S) -> [T] where S.Iterator.Element == T? { let filtered = source.lazy.filter { $0 != nil } return filtered.map { $0! } } //#-end-editable-code /*: Ewww, a free function? Why no protocol extension? Unfortunately, there's no way to constrain an extension on `Sequence` to only apply to sequences of optionals. You'd need a two-placeholder clause (one for `S`, and one for `T`, as given here), and protocol extensions currently don't support this. Nonetheless, it does make `flatMap` simple to write: */ //#-editable-code extension Sequence { func flatMap_sample_impl<U>(transform: (Iterator.Element) -> U?) -> [U] { return flatten_sample_impl(source: self.lazy.map(transform)) } } //#-end-editable-code /*: In both these functions, we used `lazy` to defer actual creation of the array until the last moment. This is possibly a micro-optimization, but it might be worthwhile for larger arrays. Using `lazy` saves the allocation of multiple buffers that would otherwise be needed to write the intermediary results into. */
mit
ac8e330adc1f0b430e4e93a5cd66f7ec
28.534091
80
0.708734
3.594744
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Controllers/Tracking/TrackingController.swift
1
6865
// // TrackingController.swift // FoodAndFitness // // Created by Mylo Ho on 4/20/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import MapKit import CoreLocation import HealthKit import SwiftUtils final class TrackingController: BaseViewController { @IBOutlet fileprivate(set) weak var mapView: MKMapView! @IBOutlet fileprivate(set) weak var activeLabel: UILabel! @IBOutlet fileprivate(set) weak var imageView: UIImageView! @IBOutlet fileprivate(set) weak var button: UIButton! var viewModel: TrackingViewModel = TrackingViewModel() enum Action { case running case stopping } fileprivate var action: Action = .stopping { didSet { configureButton() } } lazy fileprivate var locationManager: CLLocationManager = { var manager = CLLocationManager() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.activityType = .fitness manager.distanceFilter = 10 return manager }() fileprivate var timer: Timer? fileprivate let healthKitStore: HKHealthStore = HKHealthStore() // MARK: - Cycle Life override var isNavigationBarHidden: Bool { return false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) locationManager.requestWhenInUseAuthorization() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) timer?.invalidate() } override func setupUI() { super.setupUI() title = Strings.tracking configureMapView() configureButton() } // MARK: - Private Functions private func configureMapView() { mapView.delegate = self mapView.showsUserLocation = true mapView.userTrackingMode = .follow } private func configureTimer() { timer = Timer(timeInterval: 1, target: self, selector: #selector(eachSecond), userInfo: nil, repeats: true) if let timer = timer { RunLoop.current.add(timer, forMode: .commonModes) } } private func configureButton() { switch action { case .running: button.setTitle(Strings.stop, for: .normal) button.backgroundColor = Color.red238 case .stopping: button.setTitle(Strings.start, for: .normal) button.backgroundColor = Color.green81 } } @objc private func eachSecond() { viewModel.seconds += 1 let secondsQuantity = HKQuantity(unit: HKUnit.second(), doubleValue: viewModel.seconds) print(secondsQuantity.description) let distanceQuantity = HKQuantity(unit: HKUnit.meter(), doubleValue: viewModel.distance) print(distanceQuantity.description) let paceUnit = HKUnit.second().unitDivided(by: HKUnit.meter()) let paceQuantity = HKQuantity(unit: paceUnit, doubleValue: viewModel.seconds / viewModel.distance) print(paceQuantity.description) } private func startUpdatingLocation() { locationManager.startUpdatingLocation() } private func stopUpdatingLocation() { locationManager.stopUpdatingLocation() } private func showOptions() { let alert = AlertController(title: App.name, message: Strings.choosePhotoAction, preferredStyle: .actionSheet) alert.addAction(Strings.save, handler: { self.viewModel.save(completion: { [weak self](result) in guard let this = self else { return } this.action = .stopping switch result { case .success(_): this.navigationController?.popViewController(animated: true) case .failure(let error): error.show() } }) }) alert.addAction(Strings.discard, style: .cancel, handler: { self.navigationController?.popViewController(animated: true) }) alert.present() } // MARK: - Action Functions @IBAction func startOrStop(_ sender: Any) { switch action { case .running: stopUpdatingLocation() timer?.invalidate() showOptions() case .stopping: configureTimer() startUpdatingLocation() action = .running } } @IBAction func chooseActive(_ sender: Any) { if action == .running { return } let chooseActiveTrackingController = ChooseActiveTrackingController() chooseActiveTrackingController.delegate = self present(chooseActiveTrackingController, animated: true) { UIView.animate(withDuration: 0.2) { chooseActiveTrackingController.view.backgroundColor = Color.blackAlpha20 } } } } // MARK: - ChooseActiveTrackingControllerDelegate extension TrackingController: ChooseActiveTrackingControllerDelegate { func viewController(_ viewController: ChooseActiveTrackingController, needsPerformAction action: ChooseActiveTrackingController.Action) { switch action { case .dismiss(let active): activeLabel.text = active.title viewModel.active = active imageView.image = active.image } } } // MARK: - MKMapViewDelegate extension TrackingController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.blue renderer.lineWidth = 2 return renderer } } // MARK: - CLLocationManagerDelegate extension TrackingController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { for location in locations { let recent = location.timestamp.timeIntervalSinceNow if abs(recent) < 10 && location.horizontalAccuracy < 20 { if locations.isNotEmpty { let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500) mapView.setRegion(region, animated: true) var coords: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]() if let lastLocation = viewModel.locations.last { coords.append(lastLocation.coordinate) viewModel.distance += location.distance(from: lastLocation) } coords.append(location.coordinate) mapView.add(MKPolyline(coordinates: coords, count: coords.count)) } viewModel.locations.append(location) } } } }
mit
0251484280973dcf8bc687703c4cda58
32.980198
141
0.633887
5.478053
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/NotificationsCenterDetailViewController.swift
1
4645
import UIKit import WMF import SwiftUI final class NotificationsCenterDetailViewController: ViewController { // MARK: - Properties var detailView: NotificationsCenterDetailView { return view as! NotificationsCenterDetailView } let viewModel: NotificationsCenterDetailViewModel // MARK: - Lifecycle init(theme: Theme, viewModel: NotificationsCenterDetailViewModel) { self.viewModel = viewModel super.init(theme: theme) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { let detailView = NotificationsCenterDetailView(frame: UIScreen.main.bounds) view = detailView scrollView = detailView.tableView detailView.tableView.dataSource = self detailView.tableView.delegate = self } // MARK: - Themeable override func apply(theme: Theme) { super.apply(theme: theme) detailView.apply(theme: theme) } } // MARK: - UITableView extension NotificationsCenterDetailViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: switch indexPath.row { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: NotificationsCenterDetailHeaderCell.reuseIdentifier) as? NotificationsCenterDetailHeaderCell ?? NotificationsCenterDetailHeaderCell() cell.configure(viewModel: viewModel, theme: theme) return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: NotificationsCenterDetailContentCell.reuseIdentifier) as? NotificationsCenterDetailContentCell ?? NotificationsCenterDetailContentCell() cell.configure(viewModel: viewModel, theme: theme) return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: NotificationsCenterDetailActionCell.reuseIdentifier) as? NotificationsCenterDetailActionCell ?? NotificationsCenterDetailActionCell() cell.configure(action: viewModel.primaryAction, theme: theme) return cell } default: let cell = tableView.dequeueReusableCell(withIdentifier: NotificationsCenterDetailActionCell.reuseIdentifier) as? NotificationsCenterDetailActionCell ?? NotificationsCenterDetailActionCell() cell.configure(action: viewModel.uniqueSecondaryActions[indexPath.row], theme: theme) return cell } } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if viewModel.primaryAction != nil { return 3 } return 2 default: return viewModel.uniqueSecondaryActions.count } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let actionCell = tableView.cellForRow(at: indexPath) as? NotificationsCenterDetailActionCell else { return } if let actionData = actionCell.action?.actionData, let url = actionData.url { logNotificationInteraction(with: actionCell.action) var userInfo: [AnyHashable : Any] = [RoutingUserInfoKeys.source: RoutingUserInfoSourceValue.notificationsCenter.rawValue] if let replyText = viewModel.contentBody { userInfo[RoutingUserInfoKeys.talkPageReplyText] = replyText as Any } navigate(to: url, userInfo: userInfo) } tableView.deselectRow(at: indexPath, animated: true) } private func logNotificationInteraction(with action: NotificationsCenterAction?) { let notification = viewModel.commonViewModel.notification guard let notificationId = notification.id else { return } if let notificationId = Int(notificationId), let notificationType = notification.typeString, let project = notification.wiki { RemoteNotificationsFunnel.shared.logNotificationInteraction( notificationId: notificationId, notificationWiki: project, notificationType: notificationType, action: action?.actionData?.actionType, selectionToken: nil) } } }
mit
14f904a3d24b25f03967f4d703c902ef
36.459677
209
0.667815
6.160477
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/02534-swift-genericsignature-profile.swift
11
471
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b<T.h = compose() { struct A : a { enum S<T: B<h: a { struct A { class a { struct A { struct A : T where I.E == compose(x: T class B? { protocol A : d = ") func a if true { protocol A : d = ") } func c: S<T: a { protocol b : B? { } protocol b : d { func g: B<h : a { } typealias b : b<T>(v: d = c
mit
73806756b7e39dde7e19bfa3b054a23d
18.625
87
0.624204
2.770588
false
true
false
false
JonyFang/AnimatedDropdownMenu
Examples/Examples/MenuTypes/CenterTypeThreeViewController.swift
1
3251
// // CenterTypeThreeViewController.swift // AnimatedDropdownMenu // // Created by JonyFang on 17/3/3. // Copyright © 2017年 JonyFang. All rights reserved. // import UIKit import AnimatedDropdownMenu class CenterTypeThreeViewController: UIViewController { // MARK: - Properties fileprivate let dropdownItems: [AnimatedDropdownMenu.Item] = [ AnimatedDropdownMenu.Item.init("EXPLORE", nil, nil), AnimatedDropdownMenu.Item.init("POPULAR", nil, nil), AnimatedDropdownMenu.Item.init("RECENT", nil, nil) ] fileprivate var selectedStageIndex: Int = 0 fileprivate var lastStageIndex: Int = 0 fileprivate var dropdownMenu: AnimatedDropdownMenu! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setupAnimatedDropdownMenu() view.backgroundColor = .white } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) resetNavigationBarColor() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) dropdownMenu.show() } // MARK: - Private Methods fileprivate func setupAnimatedDropdownMenu() { let dropdownMenu = AnimatedDropdownMenu(navigationController: navigationController, containerView: view, selectedIndex: selectedStageIndex, items: dropdownItems) dropdownMenu.cellBackgroundColor = UIColor.menuPurpleColor() dropdownMenu.menuTitleColor = UIColor.menuLightTextColor() dropdownMenu.menuArrowTintColor = UIColor.menuLightTextColor() dropdownMenu.cellTextColor = UIColor.init(white: 1.0, alpha: 0.3) dropdownMenu.cellTextSelectedColor = UIColor.menuLightTextColor() dropdownMenu.cellSeparatorColor = UIColor.init(white: 1.0, alpha: 0.1) dropdownMenu.cellTextAlignment = .center dropdownMenu.didSelectItemAtIndexHandler = { [weak self] selectedIndex in guard let strongSelf = self else { return } strongSelf.lastStageIndex = strongSelf.selectedStageIndex strongSelf.selectedStageIndex = selectedIndex guard strongSelf.selectedStageIndex != strongSelf.lastStageIndex else { return } //Configure Selected Action strongSelf.selectedAction() } self.dropdownMenu = dropdownMenu navigationItem.titleView = dropdownMenu } private func selectedAction() { print("\(dropdownItems[selectedStageIndex].title)") } fileprivate func resetNavigationBarColor() { navigationController?.navigationBar.barStyle = .black navigationController?.navigationBar.barTintColor = UIColor.menuPurpleColor() let textAttributes: [String: Any] = [ NSForegroundColorAttributeName: UIColor.menuLightTextColor(), NSFontAttributeName: UIFont.navigationBarTitleFont() ] navigationController?.navigationBar.titleTextAttributes = textAttributes } }
mit
143385a849dcd793914adf716ede3563
31.48
169
0.647475
6.059701
false
false
false
false
ello/ello-ios
Specs/Controllers/Join/JoinScreenSpec.swift
1
7068
//// /// JoinScreenSpec.swift // @testable import Ello import Quick import Nimble class JoinScreenSpec: QuickSpec { override func spec() { class MockDelegate: JoinScreenDelegate { var didValidate = false func backAction() {} func validate(email: String, username: String, password: String) { didValidate = true } func onePasswordAction(_ sender: UIView) {} func submit(email: String, username: String, password: String) {} func urlAction(title: String, url: URL) {} } describe("JoinScreen") { var subject: JoinScreen! var delegate: MockDelegate! beforeEach { delegate = MockDelegate() subject = JoinScreen() subject.delegate = delegate } describe("snapshots") { validateAllSnapshots { return subject } } describe("snapshot, one password shown") { beforeEach { subject.isOnePasswordAvailable = true } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, keyboard shown") { beforeEach { Keyboard.shared.isActive = true Keyboard.shared.bottomInset = 216 subject.keyboardWillChange(Keyboard.shared, animated: false) } afterEach { Keyboard.shared.isActive = false Keyboard.shared.bottomInset = 0 } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, email error shown") { beforeEach { subject.showEmailError("error") } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, username error shown") { beforeEach { subject.showUsernameError("error") } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, username error and message shown") { beforeEach { subject.showUsernameError("error") subject.showUsernameSuggestions(["username"]) } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, password error shown") { beforeEach { subject.showPasswordError("error") } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, message shown") { beforeEach { subject.showUsernameSuggestions(["username"]) } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, email valid") { beforeEach { subject.isEmailValid = true } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, email invalid") { beforeEach { subject.isEmailValid = false } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, username valid") { beforeEach { subject.isUsernameValid = true } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, username invalid") { beforeEach { subject.isUsernameValid = false } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, password valid") { beforeEach { subject.isPasswordValid = true } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, password invalid") { beforeEach { subject.isPasswordValid = false } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, all valid") { beforeEach { subject.isEmailValid = true subject.isUsernameValid = true subject.isPasswordValid = true } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, all invalid") { beforeEach { subject.isEmailValid = false subject.isUsernameValid = false subject.isPasswordValid = false } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("snapshot, username suggestions") { beforeEach { subject.showUsernameSuggestions(["aaa", "bbb", "ccc"]) } it("should have a valid snapshot") { expectValidSnapshot(subject, device: .phone6_Portrait) } } describe("changing text") { beforeEach { _ = subject.textField( UITextField(), shouldChangeCharactersIn: NSRange(location: 0, length: 0), replacementString: "" ) } it("should call 'validate' on the delegate") { expect(delegate.didValidate) == true } } } } }
mit
7b12162b992a1a3dcba88e92f60a9589
33.647059
82
0.460102
6.350404
false
false
false
false
hollance/swift-algorithm-club
MinimumCoinChange/Sources/MinimumCoinChange.swift
8
2372
// // Minimum Coin Change Problem Playground // Compare Greedy Algorithm and Dynamic Programming Algorithm in Swift // // Created by Jacopo Mangiavacchi on 04/03/17. // import Foundation public enum MinimumCoinChangeError: Error { case noRestPossibleForTheGivenValue } public struct MinimumCoinChange { internal let sortedCoinSet: [Int] public init(coinSet: [Int]) { self.sortedCoinSet = coinSet.sorted(by: { $0 > $1}) } //Greedy Algorithm public func changeGreedy(_ value: Int) throws -> [Int] { guard value > 0 else { return [] } var change: [Int] = [] var newValue = value for coin in sortedCoinSet { while newValue - coin >= 0 { change.append(coin) newValue -= coin } if newValue == 0 { break } } if newValue > 0 { throw MinimumCoinChangeError.noRestPossibleForTheGivenValue } return change } //Dynamic Programming Algorithm public func changeDynamic(_ value: Int) throws -> [Int] { guard value > 0 else { return [] } var cache: [Int : [Int]] = [:] func _changeDynamic(_ value: Int) -> [Int] { guard value > 0 else { return [] } if let cached = cache[value] { return cached } var potentialChangeArray: [[Int]] = [] for coin in sortedCoinSet { if value - coin >= 0 { var potentialChange: [Int] = [coin] potentialChange.append(contentsOf: _changeDynamic(value - coin)) if potentialChange.reduce(0, +) == value { potentialChangeArray.append(potentialChange) } } } if potentialChangeArray.count > 0 { let sortedPotentialChangeArray = potentialChangeArray.sorted(by: { $0.count < $1.count }) cache[value] = sortedPotentialChangeArray[0] return sortedPotentialChangeArray[0] } return [] } let change: [Int] = _changeDynamic(value) if change.reduce(0, +) != value { throw MinimumCoinChangeError.noRestPossibleForTheGivenValue } return change } }
mit
1d70335b1e635fcdba56ace28546630a
25.651685
105
0.537943
4.753507
false
false
false
false
mita4829/Iris
Iris/BrailleController.swift
1
9222
// // BrailleController.swift // Iris // // Created by Michael Tang on 4/22/17. // Copyright © 2017 Michael Tang. All rights reserved. // import Foundation import UIKit import AudioToolbox class BrailleController : UIViewController { var a = 0 var b = 0 var c = 0 var d = 0 var e = 0 var f = 0 //event listener variables var u = 0 var v = 0 var w = 0 var x = 0 var y = 0 var z = 0 let generator = UIImpactFeedbackGenerator(style: .heavy) @IBAction func aButton(_ sender: Any) { if(a == 1){ AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } u = 0 prepareNextChar() } @IBAction func bButton(_ sender: Any) { if(b == 1){ AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } v = 0 prepareNextChar() } @IBAction func cButton(_ sender: Any) { if(c == 1){ AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } w = 0 prepareNextChar() } @IBAction func dButton(_ sender: Any) { if(d == 1){ AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } x = 0 prepareNextChar() } @IBAction func eButton(_ sender: Any) { if(e == 1){ AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } y = 0 prepareNextChar() } @IBAction func fButton(_ sender: Any) { if(f == 1){ AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } z = 0 prepareNextChar() } @IBOutlet weak var label: UILabel! var messageFromViewController = String() //Updates UI label and sets inital modes on the pins func prepareLabel(){ let local = messageFromViewController label.text = local let index = local.index(local.startIndex, offsetBy: 0) u = 1 v = 1 w = 1 x = 1 y = 1 z = 1 choose(char: String(local[index])) return } override func viewDidLoad() { prepareLabel() } func prepareNextChar() -> Void { if(u == 0 && w == 0 && v == 0 && x == 0 && y == 0 && z == 0){ //consume first char in message and set next viberation pattern and set label //Comsume char let sizeofstr = messageFromViewController.characters.count if(sizeofstr <= 1){ //End of braille translation let end = UINotificationFeedbackGenerator() end.notificationOccurred(.error) print("End called") let alertController = UIAlertController(title: "Completed", message: "End of message", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "continue", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) label.text = "" messageFromViewController = "" return } print("All buttons have been pressed") //Perhaps have a viberation to indicate character is finished? //Consume first char and present message as a substr without the first char let nextCharIndex = messageFromViewController.index(messageFromViewController.startIndex, offsetBy: 1) let newSubstr = messageFromViewController.substring(from: nextCharIndex) //Update message messageFromViewController = newSubstr //complete preparation and send control back to prepareLabel prepareLabel() } return } //Map function func choose(char: String) { if char == "a" || char == "1" { a = 1 b = 0 c = 0 d = 0 e = 0 f = 0 return } if char == "b" || char == "2" { a = 1 b = 0 c = 1 d = 0 e = 0 f = 0 return } if char == "c" || char == "3" { a = 1 b = 1 c = 0 d = 0 e = 0 f = 0 return } if char == "d" || char == "4" { a = 1 b = 1 c = 0 d = 1 e = 0 f = 0 return } if char == "e" || char == "5" { a = 1 b = 0 c = 0 d = 1 e = 0 f = 0 return } if char == "f" || char == "6" { a = 1 b = 1 c = 1 d = 0 e = 0 f = 0 return } if char == "g" || char == "7" { a = 1 b = 1 c = 1 d = 1 e = 0 f = 0 return } if char == "h" || char == "8" { a = 1 b = 0 c = 1 d = 1 e = 0 f = 0 return } if char == "i" || char == "9" { a = 0 b = 1 c = 1 d = 0 e = 0 f = 0 return } if char == "j" || char == "0" { a = 0 b = 1 c = 1 d = 1 e = 0 f = 0 return } if char == "k" { a = 1 b = 0 c = 0 d = 0 e = 1 f = 0 return } if char == "l" { a = 1 b = 0 c = 1 d = 0 e = 1 f = 0 return } if char == "m" { a = 1 b = 1 c = 0 d = 0 e = 1 f = 0 return } if char == "n" { a = 1 b = 1 c = 0 d = 1 e = 1 f = 0 return } if char == "o" { a = 1 b = 0 c = 0 d = 1 e = 1 f = 0 return } if char == "p" { a = 1 b = 1 c = 1 d = 0 e = 1 f = 0 return } if char == "q" { a = 1 b = 1 c = 1 d = 1 e = 1 f = 0 return } if char == "r" { a = 1 b = 0 c = 1 d = 1 e = 1 f = 0 return } if char == "s" { a = 0 b = 1 c = 1 d = 0 e = 1 f = 0 return } if char == "t" { a = 0 b = 1 c = 1 d = 1 e = 1 f = 0 return } if char == "u" { a = 1 b = 0 c = 0 d = 0 e = 1 f = 1 return } if char == "v" { a = 1 b = 0 c = 1 d = 0 e = 1 f = 1 return } if char == "w" { a = 0 b = 1 c = 1 d = 1 e = 0 f = 1 return } if char == "x" { a = 1 b = 1 c = 0 d = 0 e = 1 f = 1 return } if char == "y" { a = 1 b = 1 c = 0 d = 1 e = 1 f = 1 return } if char == "z" { a = 1 b = 0 c = 0 d = 1 e = 1 f = 1 return } if char == " " { a = 0 b = 1 c = 0 d = 1 e = 1 f = 1 return } } } extension String { func index(from: Int) -> Index { return self.index(startIndex, offsetBy: from) } func substring(from: Int) -> String { let fromIndex = index(from: from) return substring(from: fromIndex) } func substring(to: Int) -> String { let toIndex = index(from: to) return substring(to: toIndex) } func substring(with r: Range<Int>) -> String { let startIndex = index(from: r.lowerBound) let endIndex = index(from: r.upperBound) return substring(with: startIndex..<endIndex) } }
apache-2.0
3fb4c7a57bdaf00c05bbbdc3ab8e253c
21.767901
148
0.365795
4.702193
false
false
false
false
nastia05/TTU-iOS-Developing-Course
Lecture 2/TestApplication/ViewController.swift
1
1208
// // ViewController.swift // TestApplication // // Created by nastia on 23.11.16. // Copyright © 2016 Anastasiia Soboleva. All rights reserved. // import UIKit class ViewController: UIViewController { /* 1. Do you remember why these outlets are weak? 2. Try to guess why these outlets are optional. */ @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var secondNameTExtField: UITextField! @IBOutlet weak var nextButton: UIButton! var person: Person? { didSet { nextButton.isEnabled = person != nil } } @IBAction func textChanged(_ sender: UITextField) { /* NB Person is a structure in this example, that is why when we write person.firstName = firstNameTextField.text then a completely new instance of a Person is created. So this is equal to write just person = Person(firstName: firstNameTextField.text, secondName: secondNameTExtField.text). But if a Person was a class and we wrote person.firstName = firstNameTextField.text then there would be no callback in didSet because the reference would be the same. */ person = Person(firstName: firstNameTextField.text, secondName: secondNameTExtField.text) } }
mit
8dc038aa14143ab790c012ef3e851cb2
23.14
93
0.72908
3.996689
false
false
false
false
nkskalyan/ganesh-yrg
EcoKitchen-iOS/EcoKitcheniOSHackathon/Theme.swift
1
5414
// // Theme.swift // EcoKitcheniOS // // Created by mh53653 on 11/13/16. // Copyright © 2016 madan. All rights reserved. // import UIKit extension UIColor { class var mainColor: UIColor { return UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1.0) } class var customBackgroundColor: UIColor { return UIColor(red: 250.0/255.0, green: 250.0/255.0, blue: 248.0/255.0, alpha: 1.0) } class var subtitleTextColor: UIColor { return UIColor(red: 193.0/255.0, green: 193.0/255.0, blue: 191.0/255.0, alpha: 1.0) } class var headlineTextColor: UIColor { return UIColor(red: 120.0/255.0, green: 125.0/255.0, blue: 121.0/255.0, alpha: 1.0) } class var subviewColor: UIColor { return UIColor(red: 249.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1.0) } class var navigationBarTextColor: UIColor { return UIColor(red: 253.0/255.0, green: 253.0/255.0, blue: 253.0/255.0, alpha: 1.0) } class var markerBlueColor: UIColor { return UIColor(red: 46.0/255.0, green: 168.0/255.0, blue: 216.0/255.0, alpha: 1.0) } class var eventViewColor: UIColor { return UIColor(red: 46.0/255.0, green: 168.0/255.0, blue: 217.0/255.0, alpha: 1.0) } class var contactViewColor: UIColor { return UIColor(red: 248.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1.0) } // message screen colors class var messageSubjectColor: UIColor { return UIColor(red: 53.0/255.0, green: 56.0/255.0, blue: 61.0/255.0, alpha: 1.0) } class var messageDetailColor: UIColor { return UIColor(red: 106.0/255.0, green: 106.0/255.0, blue: 106.0/255.0, alpha: 1.0) } class var messageDateColor: UIColor { return UIColor(red: 105.0/255.0, green: 105.0/255.0, blue: 105.0/255.0, alpha: 1.0) } } // MARK:- UIFont Extensions extension UIFont { class var standardTextFont: UIFont { return UIFont(name: "HelveticaNeue-Medium", size: 15)! } class var toolBarTextFont: UIFont { return UIFont(name: "HelveticaNeue-Medium", size: 9)! } class var iPhone6HighScaleTextFont: UIFont { return UIFont(name: "HelveticaNeue-Medium", size: 17)! } class var iPhone6HighScaleSubTitleTextFont: UIFont { return UIFont(name: "HelveticaNeue", size: 15)! } class var iPhone6PlusHighScaleTextFont: UIFont { return UIFont(name: "HelveticaNeue-Medium", size: 20)! } class var iPhone6PlusHighScaleSubTitleTextFont: UIFont { return UIFont(name: "HelveticaNeue", size: 17)! } class var iPhone5TextFont: UIFont { return UIFont(name: "HelveticaNeue", size: 13)! } class var iPhone6TextFont: UIFont { return UIFont(name: "HelveticaNeue", size: 15)! } class var iPhone6PlusTextFont: UIFont { return UIFont(name: "HelveticaNeue", size: 17)! } class var titleTextFont: UIFont { return UIFont(name: "HelveticaNeue-Medium", size: 15)! } class var boldTitleTextFont: UIFont { return UIFont(name: "HelveticaNeue-Bold", size: 15)! } class var subTitle1TextFont: UIFont { return UIFont(name: "HelveticaNeue-Medium", size: 13)! } class var subTitle2TextFont: UIFont { return UIFont(name: "HelveticaNeue-Medium", size: 12)! } // Nag Messages class var iPhone6PlusNagTitleFont: UIFont { return UIFont(name: "HelveticaNeue", size: 22)! } class var iPhone6PlusNagMessageFont: UIFont { return UIFont(name: "HelveticaNeue", size: 20)! } class var iPhone6NagTitleFont: UIFont { return UIFont(name: "HelveticaNeue", size: 20)! } class var iPhone6NagMessageFont: UIFont { return UIFont(name: "HelveticaNeue", size: 18)! } class var iPhone5NagTitleFont: UIFont { return UIFont(name: "HelveticaNeue", size: 17)! } class var iPhone5NagMessageFont: UIFont { return UIFont(name: "HelveticaNeue", size: 15)! } class var iPhone4NagTitleFont: UIFont { return UIFont(name: "HelveticaNeue", size: 16)! } class var iPhone4NagMessageFont: UIFont { return UIFont(name: "HelveticaNeue", size: 15)! } } // MARK:- UINavigationBar Extensions extension UINavigationBar { class func styleForNavigationBar() { UINavigationBar.appearance().barTintColor = UIColor.mainColor UINavigationBar.appearance().tintColor = UIColor.navigationBarTextColor UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont.standardTextFont, NSForegroundColorAttributeName: UIColor.navigationBarTextColor] } } // MARK:- UIToolbar Extensions extension UIToolbar { class func styleForToolbar() { UIToolbar.appearance().barTintColor = UIColor.mainColor UIToolbar.appearance().tintColor = UIColor.mainColor } } // MARK:- Apply Theme func applyTheme() { let sharedApplication = UIApplication.shared sharedApplication.delegate?.window??.tintColor = UIColor.mainColor sharedApplication.statusBarStyle = UIStatusBarStyle.lightContent UINavigationBar.styleForNavigationBar() UIToolbar.styleForToolbar() }
apache-2.0
0a9dcd7201e1f76fe203234b28477986
29.581921
101
0.639387
3.908303
false
false
false
false
DavadDi/flatbuffers
tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift
1
11552
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import XCTest @testable import FlatBuffers final class FlatBuffersUnionTests: XCTestCase { func testCreateMonstor() { var b = FlatBufferBuilder(initialSize: 20) let dmg: Int16 = 5 let str = "Axe" let axe = b.create(string: str) let weapon = Weapon.createWeapon(builder: &b, offset: axe, dmg: dmg) let weapons = b.createVector(ofOffsets: [weapon]) let root = LocalMonster.createMonster( builder: &b, offset: weapons, equipment: .Weapon, equippedOffset: weapon.o) b.finish(offset: root) let buffer = b.sizedByteArray XCTAssertEqual(buffer, [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 8, 0, 7, 0, 12, 0, 10, 0, 0, 0, 0, 0, 0, 1, 8, 0, 0, 0, 20, 0, 0, 0, 1, 0, 0, 0, 12, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 5, 0, 4, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0]) let monster = LocalMonster.getRootAsMonster(bb: ByteBuffer(bytes: buffer)) XCTAssertEqual(monster.weapon(at: 0)?.dmg, dmg) XCTAssertEqual(monster.weapon(at: 0)?.name, str) XCTAssertEqual(monster.weapon(at: 0)?.nameVector, [65, 120, 101]) let p: Weapon? = monster.equiped() XCTAssertEqual(p?.dmg, dmg) XCTAssertEqual(p?.name, str) XCTAssertEqual(p?.nameVector, [65, 120, 101]) } func testEndTableFinish() { var builder = FlatBufferBuilder(initialSize: 20) let sword = builder.create(string: "Sword") let axe = builder.create(string: "Axe") let weaponOne = Weapon.createWeapon(builder: &builder, offset: sword, dmg: 3) let weaponTwo = Weapon.createWeapon(builder: &builder, offset: axe, dmg: 5) let name = builder.create(string: "Orc") let inventory: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let inv = builder.createVector(inventory, size: 10) let weapons = builder.createVector(ofOffsets: [weaponOne, weaponTwo]) let path = builder.createVector(ofStructs: [ Vec(x: 4.0, y: 5.0, z: 6.0), Vec(x: 1.0, y: 2.0, z: 3.0), ]) let orc = FinalMonster.createMonster( builder: &builder, position: Vec(x: 1, y: 2, z: 3), hp: 300, name: name, inventory: inv, color: .red, weapons: weapons, equipment: .Weapon, equippedOffset: weaponTwo, path: path) builder.finish(offset: orc) XCTAssertEqual(builder.sizedByteArray, [32, 0, 0, 0, 0, 0, 26, 0, 48, 0, 36, 0, 0, 0, 34, 0, 28, 0, 0, 0, 24, 0, 23, 0, 16, 0, 15, 0, 8, 0, 4, 0, 26, 0, 0, 0, 44, 0, 0, 0, 104, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 76, 0, 0, 0, 0, 0, 44, 1, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 52, 0, 0, 0, 28, 0, 0, 0, 10, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 3, 0, 0, 0, 79, 114, 99, 0, 244, 255, 255, 255, 0, 0, 5, 0, 24, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 3, 0, 12, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0, 5, 0, 0, 0, 83, 119, 111, 114, 100, 0, 0, 0]) } func testEnumVector() { let vectorOfEnums: [ColorsNameSpace.RGB] = [.blue, .green] var builder = FlatBufferBuilder(initialSize: 1) let off = builder.createVector(vectorOfEnums) let start = ColorsNameSpace.Monster.startMonster(&builder) ColorsNameSpace.Monster.add(colors: off, &builder) let end = ColorsNameSpace.Monster.endMonster(&builder, start: start) builder.finish(offset: end) XCTAssertEqual(builder.sizedByteArray, [12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0]) let monster = ColorsNameSpace.Monster.getRootAsMonster(bb: builder.buffer) XCTAssertEqual(monster.colorsCount, 2) XCTAssertEqual(monster.colors(at: 0), .blue) XCTAssertEqual(monster.colors(at: 1), .green) } func testUnionVector() { var fb = FlatBufferBuilder() let swordDmg: Int32 = 8 let attackStart = Attacker.startAttacker(&fb) Attacker.add(swordAttackDamage: swordDmg, &fb) let attack = Attacker.endAttacker(&fb, start: attackStart) let characterType: [Character] = [.belle, .mulan, .bookfan] let characters = [ fb.create(struct: BookReader(booksRead: 7)), attack, fb.create(struct: BookReader(booksRead: 2)), ] let types = fb.createVector(characterType) let characterVector = fb.createVector(ofOffsets: characters) let end = Movie.createMovie( &fb, charactersTypeVectorOffset: types, charactersVectorOffset: characterVector) Movie.finish(&fb, end: end) var movie = Movie.getRootAsMovie(bb: fb.buffer) XCTAssertEqual(movie.charactersTypeCount, Int32(characterType.count)) XCTAssertEqual(movie.charactersCount, Int32(characters.count)) for i in 0..<movie.charactersTypeCount { XCTAssertEqual(movie.charactersType(at: i), characterType[Int(i)]) } XCTAssertEqual(movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, 7) XCTAssertEqual(movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, swordDmg) XCTAssertEqual(movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead, 2) var objc: MovieT? = movie.unpack() XCTAssertEqual(movie.charactersTypeCount, Int32(objc?.characters.count ?? 0)) XCTAssertEqual(movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, (objc?.characters[0]?.value as? BookReader)?.booksRead) fb.clear() let newMovie = Movie.pack(&fb, obj: &objc) fb.finish(offset: newMovie) let packedMovie = Movie.getRootAsMovie(bb: fb.buffer) XCTAssertEqual(packedMovie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead, movie.characters(at: 0, type: BookReader_Mutable.self)?.booksRead) XCTAssertEqual(packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage) XCTAssertEqual(packedMovie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead, movie.characters(at: 2, type: BookReader_Mutable.self)?.booksRead) } } public enum ColorsNameSpace { enum RGB: Int32, Enum { typealias T = Int32 static var byteSize: Int { MemoryLayout<Int32>.size } var value: Int32 { rawValue } case red = 0, green = 1, blue = 2 } struct Monster: FlatBufferObject { var __buffer: ByteBuffer! { _accessor.bb } private var _accessor: Table static func getRootAsMonster(bb: ByteBuffer) -> Monster { Monster(Table( bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } init(_ t: Table) { _accessor = t } init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } public var colorsCount: Int32 { let o = _accessor.offset(4); return o == 0 ? 0 : _accessor.vector(count: o) } public func colors(at index: Int32) -> ColorsNameSpace.RGB? { let o = _accessor.offset(4); return o == 0 ? ColorsNameSpace.RGB(rawValue: 0)! : ColorsNameSpace.RGB(rawValue: _accessor.directRead( of: Int32.self, offset: _accessor.vector(at: o) + index * 4)) } static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } static func add(colors: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add( offset: colors, at: 4) } static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } } } enum Equipment: Byte { case none, Weapon } enum Color3: Int8 { case red = 0, green, blue } struct FinalMonster { @inlinable static func createMonster( builder: inout FlatBufferBuilder, position: Vec, hp: Int16, name: Offset<String>, inventory: Offset<UOffset>, color: Color3, weapons: Offset<UOffset>, equipment: Equipment = .none, equippedOffset: Offset<Weapon>, path: Offset<UOffset>) -> Offset<LocalMonster> { let start = builder.startTable(with: 11) builder.create(struct: position, position: 4) builder.add(element: hp, def: 100, at: 8) builder.add(offset: name, at: 10) builder.add(offset: inventory, at: 14) builder.add(element: color.rawValue, def: Color3.green.rawValue, at: 16) builder.add(offset: weapons, at: 18) builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 20) builder.add(offset: equippedOffset, at: 22) builder.add(offset: path, at: 24) return Offset(offset: builder.endTable(at: start)) } } struct LocalMonster { private var __t: Table init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o) } init(_ t: Table) { __t = t } func weapon(at index: Int32) -> Weapon? { let o = __t.offset(4); return o == 0 ? nil : Weapon.assign( __t.indirect(__t.vector(at: o) + (index * 4)), __t.bb) } func equiped<T: FlatBufferObject>() -> T? { let o = __t.offset(8); return o == 0 ? nil : __t.union(o) } static func getRootAsMonster(bb: ByteBuffer) -> LocalMonster { LocalMonster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0)))) } @inlinable static func createMonster( builder: inout FlatBufferBuilder, offset: Offset<UOffset>, equipment: Equipment = .none, equippedOffset: UOffset) -> Offset<LocalMonster> { let start = builder.startTable(with: 3) builder.add(element: equippedOffset, def: 0, at: 8) builder.add(offset: offset, at: 4) builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 6) return Offset(offset: builder.endTable(at: start)) } } struct Weapon: FlatBufferObject { var __buffer: ByteBuffer! { __t.bb } static let offsets: (name: VOffset, dmg: VOffset) = (4, 6) private var __t: Table init(_ t: Table) { __t = t } init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o)} var dmg: Int16 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer(of: Int16.self, at: o) } var nameVector: [UInt8]? { __t.getVector(at: 4) } var name: String? { let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) } static func assign(_ i: Int32, _ bb: ByteBuffer) -> Weapon { Weapon(Table(bb: bb, position: i)) } @inlinable static func createWeapon( builder: inout FlatBufferBuilder, offset: Offset<String>, dmg: Int16) -> Offset<Weapon> { let _start = builder.startTable(with: 2) Weapon.add(builder: &builder, name: offset) Weapon.add(builder: &builder, dmg: dmg) return Weapon.end(builder: &builder, startOffset: _start) } @inlinable static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Weapon> { Offset(offset: builder.endTable(at: startOffset)) } @inlinable static func add(builder: inout FlatBufferBuilder, name: Offset<String>) { builder.add(offset: name, at: Weapon.offsets.name) } @inlinable static func add(builder: inout FlatBufferBuilder, dmg: Int16) { builder.add(element: dmg, def: 0, at: Weapon.offsets.dmg) } }
apache-2.0
abd0476dfcef8155d8471c5937e44dbe
39.533333
703
0.653913
3.344528
false
false
false
false
nkirby/Humber
_lib/HMGithub/_src/API/GithubAPI+Repos.swift
1
739
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import ReactiveCocoa // ======================================================= public protocol GithubAPIReposProviding { func getRepos(type type: String) -> SignalProducer<[GithubRepoResponse], GithubAPIError> } extension GithubAPI: GithubAPIReposProviding { public func getRepos(type type: String) -> SignalProducer<[GithubRepoResponse], GithubAPIError> { let request = GithubRequest(method: .GET, endpoint: "/user/repos", parameters: ["type": type]) return self.enqueueAndParseFeed(request: request, toType: GithubRepoResponse.self) } }
mit
e6c662cc50b56f87efc031b4b3c8e689
35.95
102
0.572395
5.728682
false
false
false
false
akuraru/RandomSwift
Classes/Check.swift
1
2697
// // Check.swift // RandomSwift // // Created by akuraru on 2015/05/15. // Copyright (c) 2015年 akuraru. All rights reserved. // import Foundation public class ChiSquaredTest { public func observedCounts(counts: [Int], expectedProbabilities: [Double], significanceLevel: Double) -> Bool { let degreesOfFreedom = counts.count - 1 if ((degreesOfFreedom + 1) != expectedProbabilities.count) { assertionFailure("Is not same count \(degreesOfFreedom + 1) ans \(expectedProbabilities.count)") } let chiSquare = self.chiSquare(counts, probaby: expectedProbabilities) let upperLimitOfChiSquareValue = self.q_chi2(degreesOfFreedom, chi2: chiSquare) return significanceLevel <= upperLimitOfChiSquareValue } func chiSquare(array: [Int], probaby: [Double]) -> Double { let allCount = Double(self.allCount(array)) let a = array.map({Double($0)}) let p = probaby.map({$0 * allCount}) return reduce(Zip2(a, p), 0, {(s: Double, t: (Double, Double)) in return s + (t.0 - t.1) * (t.0 - t.1) / t.1 }) } func allCount(array: [Int]) -> Int { return array.reduce(0, combine: {$0 + $1}) } func q_chi2(df: Int,chi2:Double) -> Double { if (df == 0) { return exp(-0.5 * chi2) } else if (df == 1) { let chi = sqrt(chi2) return 2 * self.q_nor(chi) } else if (df % 2 == 1) { /* 自由度が奇数 */ let chi = sqrt(chi2) let t: Double = chi * exp(-0.5 * chi2) / sqrt(2 * M_PI) let sequence = filter((3...df), { $0%2 == 0}) let d = reduce(sequence, (t, t), {(tu: (Double, Double), s: Int) in let t = tu.0 * chi2 / Double(s) return (t, t + tu.1) }) return 2 * (self.q_nor(chi) + d.1) } else { /* 自由度が偶数 */ var t = exp(-0.5 * chi2) let sequence = filter((2...df), { $0%2 == 1}) let d = reduce(sequence, (t, t), {(tu: (Double, Double), s: Int) in let t = tu.0 * chi2 / Double(s) return (t, t + tu.1) }) return d.1 } } func p_nor(z: Double) -> Double { var z2 = z * z var t: Double = z * exp(-0.5 * z2) / sqrt(2 * M_PI) var p = t for (var i = 3; i < 200; i += 2) { let prev = p t *= z2 / Double(i) p += t if (p == prev) { return 0.5 + p } } return (z > 0) ? 1 : 0 } func q_nor(z: Double) -> Double { return 1 - self.p_nor(z) } }
mit
a800c8ccc4ffa8322dbfa57250ec5b01
34.613333
115
0.48933
3.285363
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Services/Auto Backup/Providers/GoogleDriveBackupProvider.swift
2
7502
// // GoogleDriveBackupProvider.swift // SmartReceipts // // Created by Bogdan Evsenev on 30/06/2018. // Copyright © 2018 Will Baumann. All rights reserved. // import Foundation import RxSwift import GoogleAPIClientForREST class GoogleDriveBackupProvider: BackupProvider { let backupMetadata = GoogleDriveSyncMetadata() private var syncErrorsSubject = BehaviorSubject<SyncError?>(value: nil) var deviceSyncId: String? { return backupMetadata.deviceIdentifier } var lastDatabaseSyncTime: Date { return backupMetadata.getLastDatabaseSyncTime() ?? Date(timeIntervalSince1970: 0) } func deinitialize() { } func getRemoteBackups() -> Single<[RemoteBackupMetadata]> { return GoogleDriveService.shared.getFolders(name: SYNC_FOLDER_NAME) .map({ list -> [RemoteBackupMetadata] in var result = [RemoteBackupMetadata]() guard let files = list.files else { return result } for file in files { result.append(DefaultRemoteBackupMetadata(file: file)) } return result }).do(onError: { [weak self] in self?.handleError($0) }) } func restoreBackup(remoteBackupMetadata: RemoteBackupMetadata, overwriteExistingData: Bool) -> Completable { return GoogleDriveService.shared.getFiles(inFolderId: remoteBackupMetadata.id) .flatMap({ fileList -> Single<Bool> in guard let dbFile = fileList.files?.filter({ $0.name == SYNC_DB_NAME }).first else { return Single<Bool>.never() } return GoogleDriveService.shared.downloadFile(id: dbFile.identifier!) .map({ $0.data }) .map({ data -> Bool in let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(SYNC_DB_NAME)! do { try data.write(to: fileURL) } catch { return false } return Database.sharedInstance().importData(fromBackup: fileURL.path, overwrite: overwriteExistingData) }) }).asCompletable() .do(onError: { [weak self] in self?.handleError($0) }) } func deleteBackup(remoteBackupMetadata: RemoteBackupMetadata) -> Completable { return GoogleDriveService.shared.deleteFile(id: remoteBackupMetadata.id) .do(onError: { [weak self] in self?.handleError($0) }) } func clearCurrentBackupConfiguration() -> Completable { return Completable.create(subscribe: { [weak self] completable -> Disposable in Database.sharedInstance().markAllEntriesSynced(false) self?.backupMetadata.clear() completable(.completed) return Disposables.create() }) } func downloadDatabase(remoteBackupMetadata: RemoteBackupMetadata) -> Single<Database> { return GoogleDriveService.shared.getFiles(inFolderId: remoteBackupMetadata.id) .flatMap({ fileList -> Single<Database> in guard let dbFile = fileList.files?.filter({ $0.name == SYNC_DB_NAME }).first else { return Single<Database>.never() } return GoogleDriveService.shared.downloadFile(id: dbFile.identifier!) .map({ $0.data }) .map({ data -> Database in let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(SYNC_DB_NAME)! try? data.write(to: fileURL) return Database(databasePath: fileURL.absoluteString, tripsFolderPath: FileManager.tripsDirectoryPath) }) }).do(onError: { [weak self] in self?.handleError($0) }) } func downloadReceiptFile(syncId: String) -> Single<BackupReceiptFile> { return GoogleDriveService.shared.downloadFile(id: syncId) .map({ fileData -> BackupReceiptFile in return ("", fileData.data) }).do(onError: { [weak self] in self?.handleError($0) }) } func downloadAllData(remoteBackupMetadata: RemoteBackupMetadata) -> Single<BackupFetchResult> { return fetchBackup(remoteBackupMetadata: remoteBackupMetadata, debug: false) } func debugDownloadAllData(remoteBackupMetadata: RemoteBackupMetadata) -> Single<BackupFetchResult> { return fetchBackup(remoteBackupMetadata: remoteBackupMetadata, debug: true) } func getCriticalSyncErrorStream() -> Observable<SyncError> { return syncErrorsSubject.asObservable().filter({ $0 != nil }).map({ $0! }).asObservable() } func markErrorResolved(syncErrorType: SyncError) { guard let currentError = try? syncErrorsSubject.value() else { return } if syncErrorType == currentError { syncErrorsSubject.onNext(nil) } } // MARK: - Private private func fetchBackup(remoteBackupMetadata: RemoteBackupMetadata, debug: Bool) -> Single<BackupFetchResult> { return GoogleDriveService.shared.getFiles(inFolderId: remoteBackupMetadata.id) .flatMap({ fileList -> Single<BackupFetchResult> in guard let dbFile = fileList.files?.filter({ $0.name == SYNC_DB_NAME }).first else { return .never() } guard let receiptFiles = fileList.files?.filter({ $0.name != SYNC_DB_NAME }) else { return .never() } return GoogleDriveService.shared.downloadFile(id: dbFile.identifier!).asObservable() .map({ $0.data }) .map({ data -> Database in let dbName = debug ? "\(dbFile.identifier!)_\(SYNC_DB_NAME)" : SYNC_DB_NAME let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(dbName)! try? data.write(to: fileURL) return Database(databasePath: fileURL.absoluteString, tripsFolderPath: FileManager.tripsDirectoryPath) }).flatMap({ database -> Observable<BackupFetchResult> in return receiptFiles.asObservable() .filter({ $0.name != SYNC_DB_NAME }) // Added to avoid Google Drive requests rate .delayEach(seconds: 0.2, scheduler: BackgroundScheduler) .flatMap({ file -> Observable<(GTLRDrive_File, Data)> in return GoogleDriveService.shared.downloadFile(id: file.identifier!).asObservable() .map({ (file, $0.data) }) }) .map({ downloading -> BackupReceiptFile in let file = downloading.0 let filename = debug ? "\(file.identifier!)_\(file.name!)" : file.name! return (filename, downloading.1) }).toArray() .map({ downloadedFiles -> BackupFetchResult in return BackupFetchResult(database, downloadedFiles) }) }).asSingle() }).do(onError: { [weak self] in self?.handleError($0) }) } private func handleError(_ error: Error) { let syncError = SyncError.error(error) syncErrorsSubject.onNext(syncError) } }
agpl-3.0
2c074dbc8b7e37d6b8fe8a15d83515cc
49.006667
133
0.593521
5.377061
false
false
false
false
yuhaifei123/WeiBo_Swift
WeiBo_Swift/WeiBo_Swift/class/Home(主页)/view/Home_TableViewCell.swift
1
3742
// // Home_TableViewCell.swift // WeiBo_Swift // // Created by 虞海飞 on 2016/12/22. // Copyright © 2016年 虞海飞. All rights reserved. // import UIKit class Home_TableViewCell: UITableViewCell { //根据,图片(九宫格图片)大小 var size : CGSize = CGSize(width: 0.001, height: 0.001); var status : Status? { didSet{ //设置 topview 数据 topView.status = status; contentLabel.text = status?.text; pictureView.status = status; size = pictureView.calculateImageSize(); pictureView.snp.updateConstraints { (make) in make.size.equalTo(size); } updateUI(); } } func updateUI(){ } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); setupUI(); } /// 添加 view public func setupUI(){ //控制器 view,添加 view contentView.addSubview(topView); contentView.addSubview(contentLabel); contentView.addSubview(footerView); contentView.addSubview(pictureView); //view 布局 topView.snp.makeConstraints { (make) in make.left.equalTo(10); make.right.equalTo(-10); make.top.equalTo(10); make.height.equalTo(60); } //正文 contentLabel.snp.makeConstraints { (make) in make.top.equalTo(topView.snp.bottom).offset(10); make.left.equalTo(topView.snp.left); make.bottom.equalTo(pictureView.snp.top).offset(-5); } //配图 pictureView.snp.makeConstraints { (make) in make.left.equalTo(10); make.size.equalTo(CGSize(width: 0.01, height: 0.01)); } footerView.snp.makeConstraints { (make) in make.top.equalTo(pictureView.snp.bottom).offset(10); make.height.equalTo(44); make.left.equalTo(0); make.right.equalTo(0); // make.bottom.equalTo(contentView).offset(0); } } /** 用于获取行号 */ func rowHeight(status: Status) -> CGFloat { // 1.为了能够调用didSet, 计算配图的高度 self.status = status // 2.强制更新界面 self.layoutIfNeeded(); // 3.返回底部视图最大的Y值 return footerView.frame.maxY } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //头部 public lazy var topView : StatusFooterTopView = StatusFooterTopView(); ///正文 contentLabel public lazy var contentLabel : UILabel = { let label = UILabel(); label.textColor = UIColor.darkGray; //字体的大小 label.font = UIFont.systemFont(ofSize: 15); //自动换行 label.numberOfLines = 0; //必须申明行 width label.preferredMaxLayoutWidth = UIScreen.main.bounds.width-20; return label; }(); /// 底部工具条 public lazy var footerView: StatusFooterButtonView = { let view = StatusFooterButtonView(); view.backgroundColor = UIColor(white: 0.2, alpha: 0.5); return view; }(); /// 配图 九宫格 public lazy var pictureView : StatusPictureCollectionView = { let view = StatusPictureCollectionView(); return view; }(); }
apache-2.0
629e2eafc6703c3feeb7e9ecb7c1e820
23.908451
74
0.536613
4.635649
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/Chat/CustomView/ChatWithISayCell.swift
2
687
// // ChatWithISayCell.swift // viossvc // // Created by abx’s mac on 2016/12/2. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit class ChatWithISayCell:ChatWithBaseSayCell { override func awakeFromNib() { super.awakeFromNib() var image = UIImage(named: "msg-bubble-me") image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) backImage.image = image?.resizableImageWithCapInsets(UIEdgeInsetsMake(17, 23 , 17, 23), resizingMode: UIImageResizingMode.Stretch) backImage.tintColor = UIColor.whiteColor() detailLabel.textColor = UIColor.init(RGBHex: 0x000001) } }
apache-2.0
2f666a7d744ce266a7403137edb7cb4b
30
139
0.690616
4.158537
false
false
false
false
gu704823/DYTV
dytv/Pods/LeanCloud/Sources/Storage/Value.swift
5
14405
// // LCValue.swift // LeanCloud // // Created by Tang Tianyong on 2/27/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation /** Abstract data type. All LeanCloud data types must confirm this protocol. */ public protocol LCValue: NSObjectProtocol, NSCoding, NSCopying { /** The JSON representation. */ var jsonValue: AnyObject { get } /** The pretty description. */ var jsonString: String { get } /** The raw value of current value. For JSON-compatible objects, such as string, array, etc., raw value is the value of corresponding Swift built-in type. For some objects of other types, such as `LCObject`, `LCACL` etc., raw value is itself. */ var rawValue: LCValueConvertible { get } /* Shorthands for type conversion. */ var intValue: Int? { get } var uintValue: UInt? { get } var int8Value: Int8? { get } var uint8Value: UInt8? { get } var int16Value: Int16? { get } var uint16Value: UInt16? { get } var int32Value: Int32? { get } var uint32Value: UInt32? { get } var int64Value: Int64? { get } var uint64Value: UInt64? { get } var floatValue: Float? { get } var doubleValue: Double? { get } var boolValue: Bool? { get } var stringValue: String? { get } var arrayValue: [LCValueConvertible]? { get } var dictionaryValue: [String: LCValueConvertible]? { get } var dataValue: Data? { get } var dateValue: Date? { get } } extension LCValue { public var intValue: Int? { guard let number = rawValue as? Double else { return nil } return Int(number) } public var uintValue: UInt? { guard let number = rawValue as? Double else { return nil } return UInt(number) } public var int8Value: Int8? { guard let number = rawValue as? Double else { return nil } return Int8(number) } public var uint8Value: UInt8? { guard let number = rawValue as? Double else { return nil } return UInt8(number) } public var int16Value: Int16? { guard let number = rawValue as? Double else { return nil } return Int16(number) } public var uint16Value: UInt16? { guard let number = rawValue as? Double else { return nil } return UInt16(number) } public var int32Value: Int32? { guard let number = rawValue as? Double else { return nil } return Int32(number) } public var uint32Value: UInt32? { guard let number = rawValue as? Double else { return nil } return UInt32(number) } public var int64Value: Int64? { guard let number = rawValue as? Double else { return nil } return Int64(number) } public var uint64Value: UInt64? { guard let number = rawValue as? Double else { return nil } return UInt64(number) } public var floatValue: Float? { guard let number = rawValue as? Double else { return nil } return Float(number) } public var doubleValue: Double? { guard let number = rawValue as? Double else { return nil } return Double(number) } public var boolValue: Bool? { guard let number = rawValue as? Double else { return nil } return number != 0 } public var stringValue: String? { return rawValue as? String } public var arrayValue: [LCValueConvertible]? { return rawValue as? [LCValueConvertible] } public var dictionaryValue: [String: LCValueConvertible]? { return rawValue as? [String: LCValueConvertible] } public var dataValue: Data? { return rawValue as? Data } public var dateValue: Date? { return rawValue as? Date } } /** Extension of LCValue. By convention, all types that confirm `LCValue` must also confirm `LCValueExtension`. */ protocol LCValueExtension { /** The LCON (LeanCloud Object Notation) representation. For JSON-compatible objects, such as string, array, etc., LCON value is the same as JSON value. However, some types might have different representations, or even have no LCON value. For example, when an object has not been saved, its LCON value is nil. */ var lconValue: AnyObject? { get } /** Create an instance of current type. This method exists because some data types cannot be instantiated externally. - returns: An instance of current type. */ static func instance() throws -> LCValue // MARK: Enumeration /** Iterate children by a closure. - parameter body: The iterator closure. */ func forEachChild(_ body: (_ child: LCValue) -> Void) // MARK: Arithmetic /** Add an object. - parameter other: The object to be added, aka the addend. - returns: The sum of addition. */ func add(_ other: LCValue) throws -> LCValue /** Concatenate an object with unique option. - parameter other: The object to be concatenated. - parameter unique: Whether to concatenate with unique or not. If `unique` is true, for each element in `other`, if current object has already included the element, do nothing. Otherwise, the element will always be appended. - returns: The concatenation result. */ func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue /** Calculate difference with other. - parameter other: The object to differ. - returns: The difference result. */ func differ(_ other: LCValue) throws -> LCValue } /** Convertible protocol for `LCValue`. */ public protocol LCValueConvertible { /** Get the `LCValue` value for current object. */ var lcValue: LCValue { get } } /** Convertible protocol for `LCNull`. */ public protocol LCNullConvertible: LCValueConvertible { var lcNull: LCNull { get } } /** Convertible protocol for `LCNumber`. */ public protocol LCNumberConvertible: LCValueConvertible { var lcNumber: LCNumber { get } } /** Convertible protocol for `LCBool`. */ public protocol LCBoolConvertible: LCValueConvertible { var lcBool: LCBool { get } } /** Convertible protocol for `LCString`. */ public protocol LCStringConvertible: LCValueConvertible { var lcString: LCString { get } } /** Convertible protocol for `LCArray`. */ public protocol LCArrayConvertible: LCValueConvertible { var lcArray: LCArray { get } } /** Convertible protocol for `LCDictionary`. */ public protocol LCDictionaryConvertible: LCValueConvertible { var lcDictionary: LCDictionary { get } } /** Convertible protocol for `LCData`. */ public protocol LCDataConvertible: LCValueConvertible { var lcData: LCData { get } } /** Convertible protocol for `LCDate`. */ public protocol LCDateConvertible: LCValueConvertible { var lcDate: LCDate { get } } extension NSNull: LCNullConvertible { public var lcValue: LCValue { return lcNull } public var lcNull: LCNull { return LCNull() } } extension Int: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int8: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt8: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int16: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt16: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int32: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt32: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int64: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt64: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Float: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Double: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Bool: LCBoolConvertible { public var lcValue: LCValue { return lcBool } public var lcBool: LCBool { return LCBool(self) } } extension NSNumber: LCNumberConvertible, LCBoolConvertible { public var lcValue: LCValue { return try! ObjectProfiler.object(jsonValue: self) } public var lcNumber: LCNumber { return LCNumber(self.doubleValue) } public var lcBool: LCBool { return LCBool(self.boolValue) } } extension String: LCStringConvertible { public var lcValue: LCValue { return lcString } public var lcString: LCString { return LCString(self) } } extension NSString: LCStringConvertible { public var lcValue: LCValue { return lcString } public var lcString: LCString { return LCString(String(self)) } } extension Array: LCArrayConvertible { public var lcValue: LCValue { return lcArray } public var lcArray: LCArray { let value = try! map { element -> LCValue in guard let element = element as? LCValueConvertible else { throw LCError(code: .invalidType, reason: "Element is not LCValue-convertible.", userInfo: nil) } return element.lcValue } return LCArray(value) } } extension NSArray: LCArrayConvertible { public var lcValue: LCValue { return lcArray } public var lcArray: LCArray { return (self as Array).lcArray } } extension Dictionary: LCDictionaryConvertible { public var lcValue: LCValue { return lcDictionary } public var lcDictionary: LCDictionary { let elements = try! map { (key, value) -> (String, LCValue) in guard let key = key as? String else { throw LCError(code: .invalidType, reason: "Key is not a string.", userInfo: nil) } guard let value = value as? LCValueConvertible else { throw LCError(code: .invalidType, reason: "Value is not LCValue-convertible.", userInfo: nil) } return (key, value.lcValue) } let value = [String: LCValue](elements: elements) return LCDictionary(value) } } extension NSDictionary: LCDictionaryConvertible { public var lcValue: LCValue { return lcDictionary } public var lcDictionary: LCDictionary { return (self as Dictionary).lcDictionary } } extension Data: LCDataConvertible { public var lcValue: LCValue { return lcData } public var lcData: LCData { return LCData(self) } } extension NSData: LCDataConvertible { public var lcValue: LCValue { return lcData } public var lcData: LCData { return LCData(self as Data) } } extension Date: LCDateConvertible { public var lcValue: LCValue { return lcDate } public var lcDate: LCDate { return LCDate(self) } } extension NSDate: LCDateConvertible { public var lcValue: LCValue { return lcDate } public var lcDate: LCDate { return LCDate(self as Date) } } extension LCNull: LCValueConvertible, LCNullConvertible { public var lcValue: LCValue { return self } public var lcNull: LCNull { return self } } extension LCNumber: LCValueConvertible, LCNumberConvertible { public var lcValue: LCValue { return self } public var lcNumber: LCNumber { return self } } extension LCBool: LCValueConvertible, LCBoolConvertible { public var lcValue: LCValue { return self } public var lcBool: LCBool { return self } } extension LCString: LCValueConvertible, LCStringConvertible { public var lcValue: LCValue { return self } public var lcString: LCString { return self } } extension LCArray: LCValueConvertible, LCArrayConvertible { public var lcValue: LCValue { return self } public var lcArray: LCArray { return self } } extension LCDictionary: LCValueConvertible, LCDictionaryConvertible { public var lcValue: LCValue { return self } public var lcDictionary: LCDictionary { return self } } extension LCObject: LCValueConvertible { public var lcValue: LCValue { return self } } extension LCRelation: LCValueConvertible { public var lcValue: LCValue { return self } } extension LCGeoPoint: LCValueConvertible { public var lcValue: LCValue { return self } } extension LCData: LCValueConvertible, LCDataConvertible { public var lcValue: LCValue { return self } public var lcData: LCData { return self } } extension LCDate: LCValueConvertible, LCDateConvertible { public var lcValue: LCValue { return self } public var lcDate: LCDate { return self } } extension LCACL: LCValueConvertible { public var lcValue: LCValue { return self } }
mit
d3f277925e11d06d668a4f38a843e845
21.092025
123
0.63885
4.616667
false
false
false
false
sammyd/VT_InAppPurchase
prototyping/GreenGrocer/GreenGrocer/ShoppingListTableViewCell.swift
13
1971
/* * 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 class ShoppingListTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: MultilineLabelThatWorks! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var itemCountLabel: UILabel! private static var dateFormatter : NSDateFormatter = { let df = NSDateFormatter() df.dateStyle = .ShortStyle return df }() override func awakeFromNib() { super.awakeFromNib() nameLabel.layoutMargins = UIEdgeInsetsZero dateLabel.layoutMargins = UIEdgeInsetsMake(0, 10, 0, 0) } var shoppingList : ShoppingList? { didSet { if let shoppingList = shoppingList { nameLabel?.text = shoppingList.name itemCountLabel?.text = "\(shoppingList.products.count) items" dateLabel?.text = self.dynamicType.dateFormatter.stringFromDate(shoppingList.date) } } } }
mit
75a30f84359a9c3016db34b45f8f5032
36.188679
90
0.733638
4.79562
false
false
false
false
Themaister/RetroArch
pkg/apple/HelperBar/CocoaView+HelperBar.swift
6
1796
// // CocoaView+HelperBar.swift // RetroArchiOS // // Created by Yoshi Sugawara on 2/21/22. // Copyright © 2022 RetroArch. All rights reserved. // protocol HelperBarActionDelegate: AnyObject { func keyboardButtonTapped() func mouseButtonTapped() func helpButtonTapped() var isKeyboardEnabled: Bool { get } var isMouseEnabled: Bool { get } } extension CocoaView { @objc func setupHelperBar() { let helperVC = HelperBarViewController() let viewModel = HelperBarViewModel(delegate: helperVC, actionDelegate: self) helperVC.viewModel = viewModel addChild(helperVC) helperVC.didMove(toParent: self) helperBarView = helperVC.view helperBarView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(helperBarView) helperBarView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true helperBarView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true helperBarView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true helperBarView.heightAnchor.constraint(equalToConstant: 75).isActive = true } } extension CocoaView: HelperBarActionDelegate { func keyboardButtonTapped() { toggleCustomKeyboard() } func mouseButtonTapped() { mouseHandler.enabled.toggle() let messageKey = mouseHandler.enabled ? MSG_IOS_TOUCH_MOUSE_ENABLED : MSG_IOS_TOUCH_MOUSE_DISABLED let message = msg_hash_to_str(messageKey) runloop_msg_queue_push(message, 1, 100, true, nil, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO) } func helpButtonTapped() { } var isKeyboardEnabled: Bool { !keyboardController.view.isHidden } var isMouseEnabled: Bool { mouseHandler.enabled } }
gpl-3.0
cd7d65d57d2179fb91bd03235f36149a
30.491228
113
0.71922
4.443069
false
false
false
false
Chuck8080/ios-swift-rojsonparser
ROJSONParsing/ROJSONObject.swift
2
2630
// // JSONObject.swift // RASCOcloud // // Created by Robin Oster on 02/07/14. // Copyright (c) 2014 Robin Oster. All rights reserved. // import Foundation class ROJSONObject { var jsonData:JSON required init() { jsonData = [] } required init(jsonData:AnyObject) { self.jsonData = JSON(jsonData) } required init(jsonString:String) { var data = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) var error:NSError? if let dataTemp = data { var json:AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &error) if (error != nil) { println("Something went wrong during the creation of the json dict \(error)") } else { self.jsonData = JSON(json!) return } } self.jsonData = JSON("") } func getJSONValue(key:String) -> JSON { return jsonData[key] } func getValue(key:String) -> AnyObject { return jsonData[key].object } func getArray<T : ROJSONObject>(key:String) -> [T] { var elements = [T]() for jsonValue in getJSONValue(key).array! { var element = (T.self as T.Type)() element.jsonData = jsonValue elements.append(element) } return elements } func getDate(key:String, dateFormatter:NSDateFormatter? = nil) -> NSDate? { // TODO: implement your own data parsing return nil } } class Value<T> { class func get(rojsonobject:ROJSONObject, key:String) -> T { return rojsonobject.getValue(key) as T } class func getArray<T : ROJSONObject>(rojsonobject:ROJSONObject, key:String? = nil) -> [T] { // If there is a key given fetch the array from the dictionary directly if not fetch all objects and pack it into an array if let dictKey = key { return rojsonobject.getArray(dictKey) as [T] } else { var objects = [T]() for jsonValue in rojsonobject.jsonData.array! { var object = (T.self as T.Type)() object.jsonData = jsonValue objects.append(object) } return objects } } class func getDate(rojsonobject:ROJSONObject, key:String, dateFormatter:NSDateFormatter? = nil) -> NSDate? { return rojsonobject.getDate(key, dateFormatter: dateFormatter) } }
mit
f01efb09080398a3b456ede2e7dcafb9
26.989362
130
0.561597
4.638448
false
false
false
false
digices-llc/paqure-ios-framework
Paqure/User/User.swift
1
3791
// // User.swift // Paqure // // Created by Linguri Technology on 7/21/16. // Copyright © 2016 Digices. All rights reserved. // import UIKit class User: NSObject { var id : Int var username: NSString var password: NSString var email : NSString var first : NSString var last : NSString var age : Int var status : Int override init() { self.id = 2 self.username = "anonymous" self.password = "none" self.email = "[email protected]" self.first = "Anonymous" self.last = "User" self.age = 99 self.status = 2 } required init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeIntegerForKey("id") self.username = aDecoder.decodeObjectForKey("username") as! NSString self.password = aDecoder.decodeObjectForKey("password") as! NSString self.email = aDecoder.decodeObjectForKey("email") as! NSString self.first = aDecoder.decodeObjectForKey("first") as! NSString self.last = aDecoder.decodeObjectForKey("last") as! NSString self.age = aDecoder.decodeIntegerForKey("age") self.status = aDecoder.decodeIntegerForKey("status") } init(dict: NSDictionary) { // JSON object converts to [String:String] if let id = dict["id"] as? String { if let idInt = Int(id) { self.id = idInt } else { self.id = 2 } } else { self.id = 2 } if let username = dict["username"] as? String { self.username = username } else { self.username = "anonymous" } if let password = dict["password"] as? String { self.password = password } else { self.password = "none" } if let email = dict["email"] as? String { self.email = email } else { self.email = "[email protected]" } if let first = dict["first"] as? String { self.first = first } else { self.first = "Anonymous" } if let last = dict["last"] as? String { self.last = last } else { self.last = "User" } if let age = dict["age"] as? String { if let ageInt = Int(age) { self.age = ageInt } else { self.age = 0 } } else { self.age = 0 } if let status = dict["status"] as? String { if let statusInt = Int(status) { self.status = statusInt } else { self.status = 2 } } else { self.status = 2 } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(self.id, forKey: "id") aCoder.encodeObject(self.username, forKey: "username") aCoder.encodeObject(self.password, forKey: "password") aCoder.encodeObject(self.email, forKey: "email") aCoder.encodeObject(self.first, forKey: "first") aCoder.encodeObject(self.last, forKey: "last") aCoder.encodeInteger(self.age, forKey: "age") aCoder.encodeInteger(self.status, forKey: "status") } func encodedPostBody() -> NSData { let body = self.getSuffix() print(body) return body.dataUsingEncoding(NSUTF8StringEncoding)! as NSData } func getSuffix() -> String { return "id=\(self.id)&username=\(self.username)&password=\(self.password)&email=\(self.email)&first=\(self.first)&last=\(self.last)&age=\(self.age)&status=\(self.status)" } }
bsd-3-clause
dd141c6b0907eed9befab8697f44e256
28.161538
178
0.526649
4.396752
false
false
false
false
ianyh/Highball
Highball/ImageCollectionViewCell.swift
1
3168
// // ImageCollectionViewCell.swift // Highball // // Created by Ian Ynda-Hummel on 9/1/14. // Copyright (c) 2014 ianynda. All rights reserved. // import Cartography import FLAnimatedImage import FontAwesomeKit import PINRemoteImage import UIKit class ImageCollectionViewCell: UICollectionViewCell, UIScrollViewDelegate { var scrollView: UIScrollView! var imageView: FLAnimatedImageView! var failedImageView: UIImageView! var onTapHandler: (() -> ())? var contentWidth: CGFloat? { didSet { loadPhoto() } } var photo: PostPhoto? { didSet { loadPhoto() } } override init(frame: CGRect) { super.init(frame: frame) setUpCell() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpCell() } func setUpCell() { scrollView = UIScrollView() imageView = FLAnimatedImageView() failedImageView = UIImageView() scrollView.delegate = self scrollView.maximumZoomScale = 5.0 scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false imageView.contentMode = .ScaleAspectFit failedImageView.image = FAKIonIcons.iosCameraOutlineIconWithSize(50).imageWithSize(CGSize(width: 50, height: 50)) contentView.addSubview(scrollView) scrollView.addSubview(imageView) scrollView.addSubview(failedImageView) constrain(scrollView, contentView) { scrollView, contentView in scrollView.edges == contentView.edges } constrain(failedImageView, imageView) { failedImageView, imageView in failedImageView.edges == imageView.edges } let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageCollectionViewCell.onTap(_:))) addGestureRecognizer(tapGestureRecognizer) } override func layoutSubviews() { super.layoutSubviews() let imageSize = contentView.frame.size let imageFrame = CGRect(origin: CGPoint.zero, size: imageSize) imageView.frame = imageFrame } override func prepareForReuse() { super.prepareForReuse() imageView.image = nil imageView.animatedImage = nil failedImageView.hidden = true scrollView.zoomScale = 1 centerScrollViewContents() } func loadPhoto() { guard let photo = photo, contentWidth = contentWidth else { return } let imageURL = photo.urlWithWidth(contentWidth) imageView.pin_setImageFromURL(imageURL) { result in self.failedImageView.hidden = result.error == nil } } func scrollViewDidZoom(scrollView: UIScrollView) { centerScrollViewContents() } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func centerScrollViewContents() { let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } func onTap(recognizer: UITapGestureRecognizer) { onTapHandler?() } }
mit
5c80d817ecbdd7253286e4249ae6e4d1
22.294118
119
0.746528
4.030534
false
false
false
false
yujinjcho/movie_recommendations
ios_ui/Pods/Nimble/Sources/Nimble/Matchers/BeIdenticalTo.swift
64
1690
import Foundation /// A Nimble matcher that succeeds when the actual value is the same instance /// as the expected instance. public func beIdenticalTo(_ expected: Any?) -> Predicate<Any> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in #if os(Linux) let actual = try actualExpression.evaluate() as? AnyObject #else let actual = try actualExpression.evaluate() as AnyObject? #endif failureMessage.actualValue = "\(identityAsString(actual))" failureMessage.postfixMessage = "be identical to \(identityAsString(expected))" #if os(Linux) return actual === (expected as? AnyObject) && actual !== nil #else return actual === (expected as AnyObject?) && actual !== nil #endif }.requireNonNil } public func === (lhs: Expectation<Any>, rhs: Any?) { lhs.to(beIdenticalTo(rhs)) } public func !== (lhs: Expectation<Any>, rhs: Any?) { lhs.toNot(beIdenticalTo(rhs)) } /// A Nimble matcher that succeeds when the actual value is the same instance /// as the expected instance. /// /// Alias for "beIdenticalTo". public func be(_ expected: Any?) -> Predicate<Any> { return beIdenticalTo(expected) } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func beIdenticalToMatcher(_ expected: NSObject?) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let aExpr = actualExpression.cast { $0 as Any? } return try! beIdenticalTo(expected).matches(aExpr, failureMessage: failureMessage) } } } #endif
mit
5b22257a914307f6e73ae3871dc8d627
35.73913
94
0.663314
4.617486
false
false
false
false
botherbox/JSONtoModel
JSONtoModel/EasyNetwork/String+Hash.swift
2
1071
// // StringHash.swift // 黑马微博 // // Created by 刘凡 on 15/2/21. // Copyright (c) 2015年 joyios. All rights reserved. // /// 注意:要使用本分类,需要在 bridge.h 中添加以下头文件导入 /// #import <CommonCrypto/CommonCrypto.h> /// 如果使用了单元测试,项目 和 测试项目的 bridge.h 中都需要导入 import Foundation extension String { /// 返回字符串的 MD5 散列结果 var md5: String! { // let str = self.cStringUsingEncoding(NSUTF8StringEncoding) // let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) // let digestLen = Int(CC_MD5_DIGEST_LENGTH) // let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) // // CC_MD5(str!, strLen, result) // // var hash = NSMutableString() // for i in 0..<digestLen { // hash.appendFormat("%02x", result[i]) // } // // result.dealloc(digestLen) // // return hash.copy() as! String return "" } }
mit
d8f9470cce4b4fa4b22ce95ff2d18a7c
25.942857
85
0.590668
3.392086
false
false
false
false
xixi197/XXColorTheme
XXColorTheme/ViewController.swift
1
3372
// // ViewController.swift // XXColorTheme // // Created by xixi197 on 16/1/15. // Copyright © 2016年 xixi197. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var changeButton: TCButton! @IBOutlet weak var defaultColLabel: UILabel! @IBOutlet weak var lightColLabel: UILabel! @IBOutlet weak var tintColLabel: UILabel! @IBOutlet weak var normalRowLabel: UILabel! @IBOutlet weak var selectedRowLabel: UILabel! @IBOutlet weak var borderRowLabel: UILabel! @IBOutlet weak var textRowLabel: UILabel! @IBOutlet weak var defaultButton: TCButton! @IBOutlet weak var lightButton: TCButton! @IBOutlet weak var tintButton: TCButton! @IBOutlet weak var defaultSelectedButton: TCButton! // @IBOutlet weak var lightSelectedButton: TCButton! // @IBOutlet weak var tintSelectedButton: TCButton! @IBOutlet weak var defaultBorderButton: TCButton! @IBOutlet weak var lightBorderButton: TCButton! // @IBOutlet weak var tintBorderButton: TCButton! @IBOutlet weak var defaultTextButton: TCButton! // @IBOutlet weak var lightTextButton: TCButton! @IBOutlet weak var tintTextButton: TCButton! override func viewDidLoad() { super.viewDidLoad() view.styled(.Back) // changeButton.xx_colorStyle = .Light // defaultColLabel.xx_colorStyle = .Light // lightColLabel.xx_colorStyle = .Light // tintColLabel.xx_colorStyle = .Light // normalRowLabel.xx_colorStyle = .Light // selectedRowLabel.xx_colorStyle = .Light // borderRowLabel.xx_colorStyle = .Light // textRowLabel.xx_colorStyle = .Light // defaultButton.styled(.Middle(normalImage: UIImage(named: "download")!)) // lightButton.styled(.Light(normalImage: UIImage(named: "download")!)) tintButton.styled(.MiddleMark(normalImage: UIImage(named: "like")!, highlightedImage: UIImage(named: "liked")!)) defaultSelectedButton.styled(.MiddleHighlighted(normalImage: UIImage(named: "download")!, highlightedImage: UIImage(named: "downloaded")!)) // lightSelectedButton.xx_colorStyle = .Light3 // tintSelectedButton.xx_colorStyle = .Tint defaultBorderButton.styled(.LargeHighlighted(normalImage: UIImage(named: "download")!, highlightedImage: UIImage(named: "downloaded")!)) // lightBorderButton.xx_colorStyle = .Light3 // tintBorderButton.xx_colorStyle = .Tint defaultTextButton.styled(.TextLight) // lightTextButton.xx_colorStyle = .Light3 // tintTextButton.xx_colorStyle = .Tint update() } func update() { changeButton.setTitle(XXColorCategory.preferredColorCategory.value.rawValue, forState: .Normal) } @IBAction func change(button: UIButton) { if (XXColorCategory.preferredColorCategory.value == XXColorCategory.Dark) { XXColorCategory.preferredColorCategory.value = XXColorCategory.Light } else if (XXColorCategory.preferredColorCategory.value == XXColorCategory.Light) { XXColorCategory.preferredColorCategory.value = XXColorCategory.Custom } else { XXColorCategory.preferredColorCategory.value = XXColorCategory.Dark } update() } @IBAction func selected(button: UIButton) { button.selected = !button.selected } }
mit
6a8790900d21b7bc6641b57d872cf9a6
36.433333
147
0.699911
4.659751
false
false
false
false
zj-insist/QSImageBucket
QSIMageBucket/QS-AliOSS/OSSBucketModel.swift
1
927
// // OSSBucketModel.swift // AliOSSTest // // Created by ZJ-Jie on 2017/8/8. // Copyright © 2017年 Jie. All rights reserved. // import Cocoa class OSSBucketModel: NSObject { var creationDate:String = "" var extranetEndpoint:String = "" var intranetEndpoint:String = "" var location:String = "" var name:String = "" init(creationDate:String, extranetEndpoint:String, intranetEndpoint:String, location:String, name:String) { self.creationDate = creationDate self.extranetEndpoint = extranetEndpoint self.intranetEndpoint = intranetEndpoint self.location = location self.name = name } override init() {} override var description: String { return "creationDate:" + creationDate + "\nextranetEndpoint:" + extranetEndpoint + "\nintranetEndpoint:" + intranetEndpoint + "\nlocation:" + location + "\nname:" + name } }
mit
931267f6c8cc3aa18f2dec93d6ed4c30
27.875
177
0.658009
4.219178
false
false
false
false
OverSwift/VisualReader
MangaReader/Modules/UIModule/UIModule/Classes/Scenes/Reader/ReaderViewController.swift
1
1249
// // ReaderViewController.swift // UIModule // // Created by Sergiy Loza on 26.12.16. // Copyright (c) 2016 Sergiy Loza. All rights reserved. // import UIKit struct ReaderViewModel { } class ReaderViewController: UIViewController { // MARK: - Public properties lazy var presenter:ReaderPresenterProtocol = ReaderPresenter(view: self) var viewModel:ReaderViewModel = ReaderViewModel() { didSet { updateUI() } } // MARK: - Private properties // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateUI() } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let collection = segue.destination as? ReaderCollectionViewController { collection.presenter = presenter presenter.collectionView = collection } } // MARK: - Display logic // MARK: - Actions // MARK: - Overrides // MARK: - Private functions private func updateUI() { } } extension ReaderViewController: ReaderView { internal func reloadData() { } func addToFavorite() { } }
bsd-3-clause
7eae6b26b2ce6c2f4a95badad84c76b1
16.591549
78
0.648519
4.625926
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Core/VIPER/MediaPicker/Interactor/MediaPickerInteractorImpl.swift
1
6393
import ImageSource final class MediaPickerInteractorImpl: MediaPickerInteractor { private let latestLibraryPhotoProvider: PhotoLibraryLatestPhotoProvider private let deviceOrientationService: DeviceOrientationService let maxItemsCount: Int? let cropCanvasSize: CGSize private(set) var items = [MediaPickerItem]() private var autocorrectionFilters = [Filter]() private(set) var photoLibraryItems = [PhotoLibraryItem]() private(set) var selectedItem: MediaPickerItem? private var mode: MediaPickerCropMode = .normal let cameraEnabled: Bool let photoLibraryEnabled: Bool init( items: [MediaPickerItem], autocorrectionFilters: [Filter], selectedItem: MediaPickerItem?, maxItemsCount: Int?, cropCanvasSize: CGSize, cameraEnabled: Bool, photoLibraryEnabled: Bool, deviceOrientationService: DeviceOrientationService, latestLibraryPhotoProvider: PhotoLibraryLatestPhotoProvider ) { self.items = items self.autocorrectionFilters = autocorrectionFilters self.selectedItem = selectedItem self.maxItemsCount = maxItemsCount self.cropCanvasSize = cropCanvasSize self.cameraEnabled = cameraEnabled self.photoLibraryEnabled = photoLibraryEnabled self.deviceOrientationService = deviceOrientationService self.latestLibraryPhotoProvider = latestLibraryPhotoProvider } // MARK: - MediaPickerInteractor func setCropMode(_ mode: MediaPickerCropMode) { self.mode = mode } func cropMode() -> MediaPickerCropMode { return mode } func observeDeviceOrientation(handler: @escaping (DeviceOrientation) -> ()) { deviceOrientationService.onOrientationChange = handler handler(deviceOrientationService.currentOrientation) } func observeLatestPhotoLibraryItem(handler: @escaping (ImageSource?) -> ()) { latestLibraryPhotoProvider.observePhoto(handler: handler) } func addItems( _ items: [MediaPickerItem] ) -> (addedItems: [MediaPickerItem], startIndex: Int) { let numberOfItemsToAdd = min(items.count, maxItemsCount.flatMap { $0 - self.items.count } ?? Int.max) let itemsToAdd = items[0..<numberOfItemsToAdd] let startIndex = self.items.count self.items.append(contentsOf: itemsToAdd) return (Array(itemsToAdd), startIndex) } func addPhotoLibraryItems( _ photoLibraryItems: [PhotoLibraryItem] ) -> (addedItems: [MediaPickerItem], startIndex: Int) { let mediaPickerItems = photoLibraryItems.map { MediaPickerItem( image: $0.image, source: .photoLibrary ) } self.photoLibraryItems.append(contentsOf: photoLibraryItems) return addItems(mediaPickerItems) } func updateItem(_ item: MediaPickerItem) { if let index = items.firstIndex(of: item) { items[index] = item } if let selectedItem = selectedItem, item == selectedItem { self.selectedItem = item } } func removeItem(_ item: MediaPickerItem) -> MediaPickerItem? { var adjacentItem: MediaPickerItem? if let index = items.firstIndex(of: item) { items.remove(at: index) // TODO: хорошо бы если это фото с камеры, удалять также и файл из папки temp (куда они сейчас складываются) // Соседним считаем элемент, следующий за удаленным, иначе — предыдущий, если он есть if index < items.count { adjacentItem = items[index] } else if index > 0 { adjacentItem = items[index - 1] } } if let matchingPhotoLibraryItemIndex = photoLibraryItems.firstIndex(where: { $0.image == item.image }) { photoLibraryItems.remove(at: matchingPhotoLibraryItemIndex) } return adjacentItem } func selectItem(_ item: MediaPickerItem?) { selectedItem = item } func moveItem(from sourceIndex: Int, to destinationIndex: Int) { items.moveElement(from: sourceIndex, to: destinationIndex) } func indexOfItem(_ item: MediaPickerItem) -> Int? { return items.firstIndex(of: item) } func numberOfItemsAvailableForAdding() -> Int? { return maxItemsCount.flatMap { $0 - items.count } } func canAddItems() -> Bool { return maxItemsCount.flatMap { self.items.count < $0 } ?? true } func autocorrectItem( onResult: @escaping (_ updatedItem: MediaPickerItem?) -> (), onError: @escaping (_ errorMessage: String?) -> ()) { guard let originalItem = selectedItem else { onError(nil) return } var image = originalItem.image DispatchQueue.global(qos: .userInitiated).async { let filtersGroup = DispatchGroup() var errorMessages = [String]() self.autocorrectionFilters.forEach { filter in filtersGroup.enter() filter.apply(image) { resultItem in let isFilterFailed = resultItem == image if isFilterFailed, let errorMessage = filter.fallbackMessage { errorMessages.append(errorMessage) } image = resultItem filtersGroup.leave() } filtersGroup.wait() } DispatchQueue.main.async { guard image !== originalItem.image else { onError(errorMessages.first) return } let updatedItem = MediaPickerItem( image: image, source: originalItem.source, originalItem: originalItem ) onResult(updatedItem) } } } }
mit
db29567a65c61a4045daa53928e4e126
32.417112
120
0.590655
5.539894
false
false
false
false
ragnar/VindsidenApp
VindsidenKit/CDStation.swift
1
12310
// // CDStation.swift // VindsidenApp // // Created by Ragnar Henriksen on 15.06.15. // Copyright © 2015 RHC. All rights reserved. // import Foundation import CoreData import MapKit @objc(CDStation) open class CDStation: NSManagedObject, MKAnnotation { // MARK: - MKAnnotation open var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: (self.coordinateLat?.doubleValue)!, longitude: (self.coordinateLon?.doubleValue)!) } open var title: String? { return self.stationName } open var subtitle: String? { return self.city } @objc open class func existingStationWithId( _ stationId:Int, inManagedObjectContext managedObjectContext: NSManagedObjectContext) throws -> CDStation { let request: NSFetchRequest<CDStation> = CDStation.fetchRequest() request.predicate = NSPredicate(format: "stationId == \(stationId)") request.fetchLimit = 1 let result = try managedObjectContext.fetch(request) if result.count > 0 { return result.first! } throw NSError(domain: AppConfig.Bundle.appName, code: -1, userInfo: nil) } open class func newOrExistingStationWithId( _ stationId: Int, inManagedObectContext managedObjectContext: NSManagedObjectContext) -> CDStation { do { let existing = try CDStation.existingStationWithId(stationId, inManagedObjectContext: managedObjectContext) return existing } catch { let entity = CDStation.entity() let station = CDStation(entity: entity, insertInto: managedObjectContext) return station } } open class func searchForStationName( _ stationName: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> CDStation? { let request: NSFetchRequest<CDStation> = CDStation.fetchRequest() request.predicate = NSPredicate(format: "stationName contains[cd] %@", argumentArray: [stationName]) request.fetchLimit = 1 do { let result = try managedObjectContext.fetch(request) if result.count > 0 { return result.first! } } catch { return nil } return nil } open class func maxOrderForStationsInManagedObjectContext( _ managedObjectContext: NSManagedObjectContext) -> Int { let request: NSFetchRequest<NSFetchRequestResult> = CDStation.fetchRequest() request.fetchLimit = 1 let expression = NSExpression(forFunction: "max:", arguments: [NSExpression(forKeyPath: "order")]) let expressionDescription = NSExpressionDescription() expressionDescription.expression = expression expressionDescription.expressionResultType = .integer16AttributeType expressionDescription.name = "nextNumber" request.propertiesToFetch = [expressionDescription] request.resultType = .dictionaryResultType do { let result = try managedObjectContext.fetch(request) if let first = result.first as? [String:Any], let max = first["nextNumber"] as? Int { return max } } catch { return 0 } return 0 } @objc open class func numberOfVisibleStationsInManagedObjectContext( _ managedObjectContext: NSManagedObjectContext) -> Int { let request: NSFetchRequest<CDStation> = CDStation.fetchRequest() request.predicate = NSPredicate(format: "isHidden == NO") do { let count = try managedObjectContext.count(for: request) return count } catch { return 0 } } @objc open class func visibleStationsInManagedObjectContext( _ managedObjectContext: NSManagedObjectContext, limit: Int = 0) -> [CDStation] { let request: NSFetchRequest<CDStation> = CDStation.fetchRequest() request.fetchBatchSize = 20 request.predicate = NSPredicate(format: "isHidden == NO") request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)] if limit > 0 { request.fetchLimit = limit } do { let result = try managedObjectContext.fetch(request) return result } catch { return [] } } @objc open func lastRegisteredPlot() -> CDPlot? { let inDate = Date().addingTimeInterval(-1*(AppConfig.Global.plotHistory-1)*3600) let gregorian = Calendar(identifier: Calendar.Identifier.gregorian) let inputComponents = (gregorian as NSCalendar).components([.year, .month, .day, .hour], from: inDate) guard let outDate = gregorian.date(from: inputComponents) else { DLOG("Outdate missing") return nil } let request: NSFetchRequest<CDPlot> = CDPlot.fetchRequest() request.fetchLimit = 1 request.predicate = NSPredicate(format: "station == %@ AND plotTime >= %@", argumentArray: [self, outDate] ) request.sortDescriptors = [NSSortDescriptor(key: "plotTime", ascending: false)] do { let result = try self.managedObjectContext!.fetch(request) if let first = result.first { return first } } catch { return nil } return nil } @objc open class func updateWithFetchedContent( _ content: [[String:String]], inManagedObjectContext managedObjectContext: NSManagedObjectContext, completionHandler: ((Bool) -> Void)? = nil) { if content.count == 0 { completionHandler?(false) return } DataManager.shared.performBackgroundTask { (context) in var order = CDStation.maxOrderForStationsInManagedObjectContext(context) var newStations = false if order == 0 { order = 200 } let stationIds = content.map { return Int($0["StationID"]!)! } DataManager.shared.removeStaleStationsIds(stationIds, inManagedObjectContext: context) for stationContent in content { guard let stationIdString = stationContent["StationID"] else { DLOG("No stationId") continue } let stationId = Int(stationIdString)! let station = CDStation.newOrExistingStationWithId(stationId, inManagedObectContext: context) station.updateWithContent(stationContent) #if Debug if station.stationId == 1 { station.webCamImage = "http://www.tasken.no/webcam/capture1000M.jpg" } #endif if station.isInserted { newStations = true if station.stationId == 3 { station.order = 101 station.isHidden = false #if os(iOS) DataManager.shared.addStationToIndex(station) #endif } else { order += 1 station.order = order as NSNumber? station.isHidden = true } } } do { try context.save() DispatchQueue.main.async { completionHandler?(newStations) } return } catch let error as NSError { DLOG("Error: \(error.userInfo.keys)") DispatchQueue.main.async { completionHandler?(newStations) } return } catch { DLOG("Error: \(error)") DispatchQueue.main.async { completionHandler?(newStations) } return } } } open class func updateWithWatchContent( _ content: [[String:AnyObject]], inManagedObjectContext managedObjectContext: NSManagedObjectContext, completionHandler: ((Bool) -> Void)? = nil) { DataManager.shared.performBackgroundTask { (context) in for stationContent in content { guard let stationId = stationContent["stationId"] as? Int else { DLOG("No stationId") continue } let station = CDStation.newOrExistingStationWithId(stationId, inManagedObectContext: context) station.updateWithWatchContent(stationContent) } let stationIds: [Int] = content.map { return $0["stationId"] as! Int } DataManager.shared.removeStaleStationsIds(stationIds, inManagedObjectContext: context) do { try context.save() DispatchQueue.main.async { completionHandler?(false) } return } catch let error as NSError { DLOG("Error: \(error.userInfo.keys)") DispatchQueue.main.async { completionHandler?(false) } return } catch { DLOG("Error: \(error)") DispatchQueue.main.async { completionHandler?(false) } return } } } func updateWithContent( _ content: [String:String] ) { if let unwrapped = content["StationID"], let stationId = Int(unwrapped) { self.stationId = stationId as NSNumber? } if let name = content["Name"] { self.stationName = name.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let text = content["Text"] { self.stationText = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let city = content["City"] { self.city = city.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let copyright = content["Copyright"] { self.copyright = copyright.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let statusMessage = content["StatusMessage"] { self.statusMessage = statusMessage.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let coordinate = content["Latitude"], let lat = Double(coordinate) { self.coordinateLat = lat as NSNumber? } if let coordinate = content["Longitude"], let lng = Double(coordinate) { self.coordinateLon = lng as NSNumber? } if let yrURL = content["MeteogramUrl"] { self.yrURL = yrURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let webCamImage = content["WebcamImage"] { self.webCamImage = webCamImage.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let webCamText = content["WebcamText"] { self.webCamText = webCamText.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let webCamURL = content["WebcamUrl"] { self.webCamURL = webCamURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } if let lastMeasurement = content["LastMeasurementTime"] { self.lastMeasurement = DataManager.shared.dateFromString(lastMeasurement) } } func updateWithWatchContent( _ content: [String:AnyObject] ) { if let hidden = content["hidden"] as? Int { self.isHidden = hidden as NSNumber? } if let order = content["order"] as? Int { self.order = order as NSNumber? } if let stationId = content["stationId"] as? Int { self.stationId = stationId as NSNumber? } if let stationName = content["stationName"] as? String { self.stationName = stationName } if let lat = content["latitude"] as? Double { self.coordinateLat = lat as NSNumber? } if let lon = content["longitude"] as? Double { self.coordinateLon = lon as NSNumber? } } }
bsd-2-clause
cf6b2634310eb0d42c585b4d00e7ea1c
33.382682
196
0.586563
5.465808
false
false
false
false
coderLL/DYTV
DYTV/DYTV/Classes/Main/Controller/BaseAnchorViewController.swift
1
5443
// // BaseAnchorViewController.swift // DYTV // // Created by CodeLL on 2016/10/15. // Copyright © 2016年 coderLL. All rights reserved. // import UIKit // MARK:- 常量 let kItemMargin : CGFloat = 10 let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2 let kNormalItemH = kNormalItemW * 3 / 4 let kPrettyItemH = kNormalItemW * 4 / 3 let kHeaderViewH : CGFloat = 50 let kNormalCellID = "kNormalCellID" let kHeaderViewID = "kHeaderViewID" let kPrettyCellID = "kPrettyCellID" class BaseAnchorViewController: BaseViewController { // MARK:- 懒加载属性 var baseVM : BaseViewModel! lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 // 行间距 layout.minimumInteritemSpacing = kItemMargin // Item之间的间距 layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.white collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionViewNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionViewPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() // MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() // 设置UI界面 self.setupUI() // 请求数据 self.loadData() } } // MARK:- 设置UI界面 extension BaseAnchorViewController { override func setupUI() { // 1.给父类中的内容view引用进行赋值 self.baseContentView = collectionView // 2.添加collectionView self.view.addSubview(collectionView) // 3.调用父类的setupUI() super.setupUI() } } // MARK:- 请求数据 extension BaseAnchorViewController { func loadData() { } } // MARK:- 遵守UICollectionViewDelegate, UICollectionViewDataSource extension BaseAnchorViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return self.baseVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = self.baseVM.anchorGroups[section] return group.anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.取出Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionViewNormalCell // 2.取出模型对象 let anchor = self.baseVM.anchorGroups[(indexPath as NSIndexPath).section].anchors[(indexPath as NSIndexPath).item] // 4.将模型赋值给cell cell.anchor = anchor return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出section的HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.取出模型赋值 let group = self.baseVM.anchorGroups[(indexPath as NSIndexPath).section] headerView.group = group return headerView } } // MARK:- 遵守UICollectionView的代理协议 extension BaseAnchorViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 1.取出对应的主播信息 let anchor = self.baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] // 2.判断是主播房间还是秀场房间 anchor.isVertical == 0 ? pushNormalRoomVc(anchor) : presentShowRoomVc(anchor) } func pushNormalRoomVc(_ anchor : AnchorModel) { // 1.创建normalRoomVc let normalRoomVc = RoomNormalViewController() // 2.传递数据模型 normalRoomVc.anchor = anchor // 3.以push方式推出 navigationController?.pushViewController(normalRoomVc, animated: true) } func presentShowRoomVc(_ anchor : AnchorModel) { // 1.创建ShowRoomVc let showRoomVc = RoomShowViewController() // 2.传递数据模型 showRoomVc.anchor = anchor // 3.以modal方式弹出 present(showRoomVc, animated: true, completion: nil) } }
mit
7026d36c9f6b9f1650269cdc0c640f59
32.064103
186
0.676813
5.588299
false
false
false
false
Binur/SubscriptionPrompt
SubscriptionPrompt/OptionTableViewCell.swift
1
1205
// // OptionTableViewCell.swift // SubscriptionPrompt // // Created by Binur Konarbayev on 7/16/16. // // import UIKit final class OptionTableViewCell: UITableViewCell { fileprivate var disclosureType: UITableViewCellAccessoryType? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUpViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpViews() } fileprivate func setUpViews() { let backgroundView = UIView() backgroundView.backgroundColor = .orange selectedBackgroundView = backgroundView textLabel?.textAlignment = .center } } extension OptionTableViewCell { func setUp(withOption option: Option) { accessoryType = option.checked ? (disclosureType ?? .checkmark) : .none textLabel?.text = option.title } func setUp(withOptionStyle style: OptionStyle) { backgroundColor = style.backgroundColor textLabel?.font = style.textFont textLabel?.textColor = style.textColor disclosureType = style.accessoryType } }
mit
04d1c6713d41baa1fd7d220f28fcc89b
26.386364
79
0.674689
5.149573
false
false
false
false
aschwaighofer/swift
test/IDE/structure.swift
2
14231
// RUN: %swift-ide-test -structure -source-filename %s | %FileCheck %s // CHECK: <class>class <name>MyCls</name> : <inherited><elem-typeref>OtherClass</elem-typeref></inherited> { // CHECK: <property>var <name>bar</name> : <type>Int</type></property> // CHECK: <property>var <name>anotherBar</name> : <type>Int</type> = 42</property> // CHECK: <cvar>class var <name>cbar</name> : <type>Int</type> = 0</cvar> class MyCls : OtherClass { var bar : Int var anotherBar : Int = 42 class var cbar : Int = 0 // CHECK: <ifunc>func <name>foo(<param>_ arg1: <type>Int</type></param>, <param><name>name</name>: <type>String</type></param>, <param><name>param</name> par: <type>String</type></param>)</name> { // CHECK: <lvar>var <name>abc</name></lvar> // CHECK: <if>if <elem-condexpr>1</elem-condexpr> <brace>{ // CHECK: <call><name>foo</name>(<arg>1</arg>, <arg><name>name</name>:"test"</arg>, <arg><name>param</name>:"test2"</arg>)</call> // CHECK: }</brace> // CHECK: }</ifunc> func foo(_ arg1: Int, name: String, param par: String) { var abc if 1 { foo(1, name:"test", param:"test2") } } // CHECK: <ifunc><name>init (<param><name>x</name>: <type>Int</type></param>)</name></ifunc> init (x: Int) // CHECK: <cfunc>class func <name>cfoo()</name></cfunc> class func cfoo() // CHECK: }</class> } // CHECK: <struct>struct <name>MyStruc</name> { // CHECK: <property>var <name>myVar</name>: <type>Int</type></property> // CHECK: <svar>static var <name>sbar</name> : <type>Int</type> = 0</svar> // CHECK: <sfunc>static func <name>cfoo()</name></sfunc> // CHECK: }</struct> struct MyStruc { var myVar: Int static var sbar : Int = 0 static func cfoo() } // CHECK: <protocol>protocol <name>MyProt</name> { // CHECK: <ifunc>func <name>foo()</name></ifunc> // CHECK: <ifunc>func <name>foo2()</name> throws</ifunc> // CHECK: <ifunc>func <name>foo3()</name> throws -> <type>Int</type></ifunc> // CHECK: <ifunc>func <name>foo4<<generic-param><name>T</name></generic-param>>()</name> where T: MyProt</ifunc> // CHECK: <ifunc><name>init()</name></ifunc> // CHECK: <ifunc><name>init(<param><name>a</name>: <type>Int</type></param>)</name> throws</ifunc> // CHECK: <ifunc><name>init<<generic-param><name>T</name></generic-param>>(<param><name>a</name>: <type>T</type></param>)</name> where T: MyProt</ifunc> // CHECK: }</protocol> protocol MyProt { func foo() func foo2() throws func foo3() throws -> Int func foo4<T>() where T: MyProt init() init(a: Int) throws init<T>(a: T) where T: MyProt } // CHECK: <extension>extension <name>MyStruc</name> { // CHECK: <ifunc>func <name>foo()</name> { // CHECK: }</ifunc> // CHECK: }</extension> extension MyStruc { func foo() { } } // CHECK: <gvar>var <name>gvar</name> : <type>Int</type> = 0</gvar> var gvar : Int = 0 // CHECK: <ffunc>func <name>ffoo()</name> {}</ffunc> func ffoo() {} // CHECK: <foreach>for <elem-id><lvar><name>i</name></lvar></elem-id> in <elem-expr>0...5</elem-expr> <brace>{}</brace></foreach> for i in 0...5 {} // CHECK: <foreach>for <elem-id>var (<lvar><name>i</name></lvar>, <lvar><name>j</name></lvar>)</elem-id> in <elem-expr>array</elem-expr> <brace>{}</brace></foreach> for var (i, j) in array {} // CHECK: <while>while <elem-condexpr>var <lvar><name>v</name></lvar> = o, <lvar><name>z</name></lvar> = o where v > z</elem-condexpr> <brace>{}</brace></while> while var v = o, z = o where v > z {} // CHECK: <while>while <elem-condexpr>v == 0</elem-condexpr> <brace>{}</brace></while> while v == 0 {} // CHECK: <repeat-while>repeat <brace>{}</brace> while <elem-expr>v == 0</elem-expr></repeat-while> repeat {} while v == 0 // CHECK: <if>if <elem-condexpr>var <lvar><name>v</name></lvar> = o, <lvar><name>z</name></lvar> = o where v > z</elem-condexpr> <brace>{}</brace></if> if var v = o, z = o where v > z {} // CHECK: <switch>switch <elem-expr>v</elem-expr> { // CHECK: <case>case <elem-pattern>1</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern>2</elem-pattern>, <elem-pattern>3</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern><call><name>Foo</name>(<arg>var <lvar><name>x</name></lvar></arg>, <arg>var <lvar><name>y</name></lvar></arg>)</call> where x < y</elem-pattern>: break;</case> // CHECK: <case>case <elem-pattern>2 where <call><name>foo</name>()</call></elem-pattern>, <elem-pattern>3 where <call><name>bar</name>()</call></elem-pattern>: break;</case> // CHECK: <case><elem-pattern>default</elem-pattern>: break;</case> // CHECK: }</switch> switch v { case 1: break; case 2, 3: break; case Foo(var x, var y) where x < y: break; case 2 where foo(), 3 where bar(): break; default: break; } // CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>]</array></gvar> let myArray = [1, 2, 3] // CHECK: <gvar>let <name>myDict</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>, <elem-expr>2</elem-expr>:<elem-expr>2</elem-expr>, <elem-expr>3</elem-expr>:<elem-expr>3</elem-expr>]</dictionary></gvar> let myDict = [1:1, 2:2, 3:3] // CHECK: <gvar>let <name>myArray2</name> = <array>[<elem-expr>1</elem-expr>]</array></gvar> let myArray2 = [1] // CHECK: <gvar>let <name>myDict2</name> = <dictionary>[<elem-expr>1</elem-expr>:<elem-expr>1</elem-expr>]</dictionary></gvar> let myDict2 = [1:1] // CHECK: <foreach>for <brace>{}</brace></foreach> for {} // CHECK: <class>class <name><#MyCls#></name> : <inherited><elem-typeref><#OtherClass#></elem-typeref></inherited> {} class <#MyCls#> : <#OtherClass#> {} // CHECK: <ffunc>func <name><#test1#> ()</name> { // CHECK: <foreach>for <elem-id><lvar><name><#name#></name></lvar></elem-id> in <elem-expr><#items#></elem-expr> <brace>{}</brace></foreach> // CHECK: }</ffunc> func <#test1#> () { for <#name#> in <#items#> {} } // CHECK: <gvar>let <name>myArray</name> = <array>[<elem-expr><#item1#></elem-expr>, <elem-expr><#item2#></elem-expr>]</array></gvar> let myArray = [<#item1#>, <#item2#>] // CHECK: <ffunc>func <name>test1()</name> { // CHECK: <call><name>dispatch_async</name>(<arg><call><name>dispatch_get_main_queue</name>()</call></arg>, <arg><closure><brace>{}</brace></closure></arg>)</call> // CHECK: <call><name>dispatch_async</name>(<arg><call><name>dispatch_get_main_queue</name>()</call></arg>) <arg><closure><brace>{}</brace></closure></arg></call> // CHECK: }</ffunc> func test1() { dispatch_async(dispatch_get_main_queue(), {}) dispatch_async(dispatch_get_main_queue()) {} } // CHECK: <enum>enum <name>SomeEnum</name> { // CHECK: <enum-case>case <enum-elem><name>North</name></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>South</name></enum-elem>, <enum-elem><name>East</name></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>QRCode(<param><type>String</type></param>)</name></enum-elem></enum-case> // CHECK: <enum-case>case</enum-case> // CHECK: }</enum> enum SomeEnum { case North case South, East case QRCode(String) case } // CHECK: <enum>enum <name>Rawness</name> : <inherited><elem-typeref>Int</elem-typeref></inherited> { // CHECK: <enum-case>case <enum-elem><name>One</name> = <elem-initexpr>1</elem-initexpr></enum-elem></enum-case> // CHECK: <enum-case>case <enum-elem><name>Two</name> = <elem-initexpr>2</elem-initexpr></enum-elem>, <enum-elem><name>Three</name> = <elem-initexpr>3</elem-initexpr></enum-elem></enum-case> // CHECK: }</enum> enum Rawness : Int { case One = 1 case Two = 2, Three = 3 } // CHECK: <ffunc>func <name>rethrowFunc(<param>_ f: <type>() throws -> ()</type> = <closure><brace>{}</brace></closure></param>)</name> rethrows {}</ffunc> func rethrowFunc(_ f: () throws -> () = {}) rethrows {} class NestedPoundIf{ func foo1() { #if os(macOS) var a = 1 #if USE_METAL var b = 2 #if os(iOS) var c = 3 #else var c = 3 #endif #else var b = 2 #endif #else var a = 1 #endif } func foo2() {} func foo3() {} } // CHECK: <ifunc>func <name>foo2()</name> {}</ifunc> // CHECK: <ifunc>func <name>foo3()</name> {}</ifunc> class A { func foo(_ i : Int, animations: () -> ()) {} func perform() {foo(5, animations: {})} // CHECK: <ifunc>func <name>perform()</name> {<call><name>foo</name>(<arg>5</arg>, <arg><name>animations</name>: <closure><brace>{}</brace></closure></arg>)</call>}</ifunc> } // CHECK: <typealias>typealias <name>OtherA</name> = A</typealias> typealias OtherA = A // CHECK: <typealias>typealias <name>EqBox</name><<generic-param><name>Boxed</name></generic-param>> = Box<Boxed> where Boxed: Equatable</typealias> typealias EqBox<Boxed> = Box<Boxed> where Boxed: Equatable class SubscriptTest { subscript(index: Int) -> Int { return 0 } // CHECK: <subscript><name>subscript(<param>index: <type>Int</type></param>)</name> -> <type>Int</type> { // CHECK: return 0 // CHECK: }</subscript> subscript(string: String) -> Int { get { return 0 } set(value) { print(value) } } // CHECK: <subscript><name>subscript(<param>string: <type>String</type></param>)</name> -> <type>Int</type> { // CHECK: get { // CHECK: return 0 // CHECK: } // CHECK: set(<param>value</param>) { // CHECK: <call><name>print</name>(value)</call> // CHECK: }</subscript> } class ReturnType { func foo() -> Int { return 0 } // CHECK: <ifunc>func <name>foo()</name> -> <type>Int</type> { // CHECK: return 0 // CHECK: }</ifunc> func foo2<T>() -> T {} // CHECK: <ifunc>func <name>foo2<<generic-param><name>T</name></generic-param>>()</name> -> <type>T</type> {}</ifunc> func foo3() -> () -> Int {} // CHECK: <ifunc>func <name>foo3()</name> -> <type>() -> Int</type> {}</ifunc> } protocol FooProtocol { associatedtype Bar // CHECK: <associatedtype>associatedtype <name>Bar</name></associatedtype> associatedtype Baz: Equatable // CHECK: <associatedtype>associatedtype <name>Baz</name>: Equatable</associatedtype> associatedtype Qux where Qux: Equatable // CHECK: <associatedtype>associatedtype <name>Qux</name> where Qux: Equatable</associatedtype> associatedtype Bar2 = Int // CHECK: <associatedtype>associatedtype <name>Bar2</name> = Int</associatedtype> associatedtype Baz2: Equatable = Int // CHECK: <associatedtype>associatedtype <name>Baz2</name>: Equatable = Int</associatedtype> associatedtype Qux2 = Int where Qux2: Equatable // CHECK: <associatedtype>associatedtype <name>Qux2</name> = Int where Qux2: Equatable</associatedtype> } // CHECK: <struct>struct <name>Generic</name><<generic-param><name>T</name>: <inherited><elem-typeref>Comparable</elem-typeref></inherited></generic-param>, <generic-param><name>X</name></generic-param>> { // CHECK: <subscript><name>subscript<<generic-param><name>U</name></generic-param>>(<param>generic: <type>U</type></param>)</name> -> <type>Int</type> { return 0 }</subscript> // CHECK: <typealias>typealias <name>Foo</name><<generic-param><name>Y</name></generic-param>> = Bar<Y></typealias> // CHECK: }</struct> struct Generic<T: Comparable, X> { subscript<U>(generic: U) -> Int { return 0 } typealias Foo<Y> = Bar<Y> } a.b(c: d?.e?.f, g: h) // CHECK: <call><name>a.b</name>(<arg><name>c</name>: d?.e?.f</arg>, <arg><name>g</name>: h</arg>)</call> struct Tuples { var foo: (Int, String) { return (1, "test") // CHECK: <tuple>(<elem-expr>1</elem-expr>, <elem-expr>"test"</elem-expr>)</tuple> } func foo2() { foo3(x: (1, 20)) // CHECK: <call><name>foo3</name>(<arg><name>x</name>: <tuple>(<elem-expr>1</elem-expr>, <elem-expr>20</elem-expr>)</tuple></arg>)</call> let y = (x, foo4(a: 0)) // CHECK: <lvar>let <name>y</name> = <tuple>(<elem-expr>x</elem-expr>, <elem-expr><call><name>foo4</name>(<arg><name>a</name>: 0</arg>)</call></elem-expr>)</tuple></lvar> let z = (name1: 1, name2: 2) // CHECK: <lvar>let <name>z</name> = <tuple>(name1: <elem-expr>1</elem-expr>, name2: <elem-expr>2</elem-expr>)</tuple></lvar> } } completion(a: 1) { (x: Any, y: Int) -> Int in return x as! Int + y } // CHECK: <call><name>completion</name>(<arg><name>a</name>: 1</arg>) <arg><closure>{ (<param>x: <type>Any</type></param>, <param>y: <type>Int</type></param>) -> <type>Int</type> in // CHECK: return x as! Int + y // CHECK: }</closure></arg></call> myFunc(foo: 0, bar: baz == 0) // CHECK: <call><name>myFunc</name>(<arg><name>foo</name>: 0</arg>, // CHECK: <arg><name>bar</name>: baz == 0</arg>)</call> enum FooEnum { // CHECK: <enum>enum <name>FooEnum</name> { case blah(x: () -> () = { // CHECK: <enum-case>case <enum-elem><name>blah(<param><name>x</name>: <type>() -> ()</type> = <closure><brace>{ @Tuples func foo(x: MyStruc) {} // CHECK: @Tuples <ffunc>func <name>foo(<param><name>x</name>: <type>MyStruc</type></param>)</name> {}</ffunc> }) // CHECK: }</brace></closure></param>)</name></enum-elem></enum-case> } // CHECK: }</enum> firstCall("\(1)", 1) // CHECK: <call><name>firstCall</name>(<arg>"\(1)"</arg>, <arg>1</arg>)</call> secondCall("\(a: {struct Foo {let x = 10}; return Foo().x}())", 1) // CHECK: <call><name>secondCall</name>(<arg>"\(a: <call><name><closure><brace>{<struct>struct <name>Foo</name> {<property>let <name>x</name> = 10</property>}</struct>; return <call><name>Foo</name>()</call>.x}</brace></closure></name>()</call>)"</arg>, <arg>1</arg>)</call> thirdCall(""" \(""" \({ return a() }()) """) """) // CHECK: <call><name>thirdCall</name>(""" // CHECK-NEXT: \(""" // CHECK-NEXT: \(<call><name><closure>{ // CHECK-NEXT: return <call><name>a</name>()</call> // CHECK-NEXT: }</closure></name>()</call>) // CHECK-NEXT: """) // CHECK-NEXT: """)</call> fourthCall(a: @escaping () -> Int) // CHECK: <call><name>fourthCall</name>(<arg><name>a</name>: @escaping () -> Int</arg>)</call> // CHECK: <call><name>foo</name> <closure>{ [unowned <lvar><name>self</name></lvar>, <lvar><name>x</name></lvar>] in _ }</closure></call> foo { [unowned self, x] in _ }
apache-2.0
1ed66e6dfa7ca799fdeb1dd5ba1b3f64
41.607784
274
0.603612
2.963557
false
false
false
false