repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/Extensions/NoResultsViewController+Model.swift
gpl-2.0
2
import Foundation extension NoResultsViewController { struct Model { let titleText: String let subtitleText: String? let buttonText: String? var imageName: String? let accessoryView: UIView? init(title: String, subtitle: String? = nil, buttonText: String? = nil, imageName: String? = nil, accessoryView: UIView? = nil) { self.titleText = title self.subtitleText = subtitle self.buttonText = buttonText self.imageName = imageName self.accessoryView = accessoryView } } func bindViewModel(_ viewModel: Model) { configure(title: viewModel.titleText, buttonTitle: viewModel.buttonText, subtitle: viewModel.subtitleText, image: viewModel.imageName, accessoryView: viewModel.accessoryView) } }
2adedf9488dfb90540b66b5e662cd2a5
35.130435
182
0.65704
false
false
false
false
CodaFi/swift
refs/heads/master
test/Interop/Cxx/class/synthesized-initializers-silgen.swift
apache-2.0
5
// RUN: %target-swift-frontend -I %S/Inputs -enable-cxx-interop -emit-silgen %s | %FileCheck %s import SynthesizedInitializers // CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo11EmptyStructVABycfC : $@convention(method) (@thin EmptyStruct.Type) -> EmptyStruct // CHECK: bb0(%{{[0-9]+}} : $@thin EmptyStruct.Type): // CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var EmptyStruct } // CHECK-NEXT: [[UNINIT:%.*]] = mark_uninitialized [rootself] [[BOX]] : ${ var EmptyStruct } // CHECK-NEXT: [[PTR:%.*]] = project_box [[UNINIT]] : ${ var EmptyStruct }, 0 // CHECK-NEXT: [[OBJ:%.*]] = builtin "zeroInitializer"<EmptyStruct>() : $EmptyStruct // CHECK-NEXT: [[PA:%.*]] = begin_access [modify] [unknown] [[PTR]] : $*EmptyStruct // CHECK-NEXT: assign [[OBJ]] to [[PA]] // CHECK-NEXT: end_access [[PA]] // CHECK-NEXT: [[OUT:%.*]] = load [trivial] [[PTR]] // CHECK-NEXT: destroy_value [[UNINIT]] // CHECK-NEXT: return [[OUT]] // CHECK-LABEL: end sil function '$sSo11EmptyStructVABycfC' public func emptyTypeNoArgInit() { let e = EmptyStruct() } // CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo6IntBoxVABycfC : $@convention(method) (@thin IntBox.Type) -> IntBox // CHECK: bb0(%{{[0-9]+}} : $@thin IntBox.Type): // CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var IntBox } // CHECK-NEXT: [[UNINIT:%.*]] = mark_uninitialized [rootself] [[BOX]] : ${ var IntBox } // CHECK-NEXT: [[PTR:%.*]] = project_box [[UNINIT]] : ${ var IntBox }, 0 // CHECK-NEXT: [[OBJ:%.*]] = builtin "zeroInitializer"<IntBox>() : $IntBox // CHECK-NEXT: [[PA:%.*]] = begin_access [modify] [unknown] [[PTR]] : $*IntBox // CHECK-NEXT: assign [[OBJ]] to [[PA]] // CHECK-NEXT: end_access [[PA]] // CHECK-NEXT: [[OUT:%.*]] = load [trivial] [[PTR]] // CHECK-NEXT: destroy_value [[UNINIT]] // CHECK-NEXT: return [[OUT]] // CHECK-LABEL: end sil function '$sSo6IntBoxVABycfC' public func singleMemberTypeNoArgInit() { let i = IntBox() } // CHECK-LABEL: sil shared [transparent] [serializable] [ossa] @$sSo6IntBoxV1xABs5Int32V_tcfC : $@convention(method) (Int32, @thin IntBox.Type) -> IntBox // CHECK: bb0([[I:%[0-9]+]] : $Int32, %{{[0-9]+}} : $@thin IntBox.Type): // CHECK-NEXT: [[S:%.*]] = struct $IntBox ([[I]] : $Int32) // CHECK-NEXT: return [[S]] // CHECK-LABEL: end sil function '$sSo6IntBoxV1xABs5Int32V_tcfC' public func singleMemberTypeValueInit() { let i = IntBox(x: 42) }
e7737826b35524a842d9748fbe1d0002
50.456522
153
0.634559
false
false
false
false
finder39/resumod
refs/heads/master
Resumod/Constants.swift
mit
1
// // Constants.swift // Resumod // // Created by Joseph Neuman on 7/23/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation import UIKit struct CONSTANTS { /*enum Palette { case VeryLightPastelRedBlueYellow case DarkRedBlueYellow } let paletteToUse = Palette.VeryLightPastelRedBlueYellow switch (paletteToUse) { case .VeryLightPastelRedBlueYellow: let color1 = "a" }*/ // http://www.paletton.com/#uid=33K0I0kiCFn8GVde7NVmtwSqXtg let color1 = UIColor(red: 1, green: 0.945, blue: 0.42, alpha: 1) let color2 = UIColor(red: 0.369, green: 0.498, blue: 0.776, alpha: 1) let color3 = UIColor(red: 1, green: 0.576, blue: 0.42, alpha: 1) } /*class Constants { /*class var sharedInstance:Constants { struct Static { static let instance = Constants() } return Static.instance }*/ let constants = constantsStruct() }*/ extension String { func md5() -> String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(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.destroy() return String(format: hash) } }
f2e4279d3f4ec2707db305740b6ff9a8
23.016667
84
0.675
false
false
false
false
Lollipop95/WeiBo
refs/heads/master
WeiBo/WeiBo/Classes/View/Compose/WBComposeViewController.swift
mit
1
// // WBComposeViewController.swift // WeiBo // // Created by Ning Li on 2017/5/6. // Copyright © 2017年 Ning Li. All rights reserved. // import UIKit import SVProgressHUD class WBComposeViewController: UIViewController { @IBOutlet weak var textView: WBComposeTextView! @IBOutlet weak var toolbar: UIToolbar! /// 工具栏底部约束 @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint! /// 发布按钮 @IBOutlet var sendButton: UIButton! /// 懒加载表情键盘视图 lazy var emoticonKeyboardView: WBEmoticonInputView = WBEmoticonInputView.inputView { [weak self] (emoticon) in self?.textView.insertEmoticon(emoticon: emoticon) } override func viewDidLoad() { super.viewDidLoad() setupUI() // 注册键盘通知 NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 激活键盘 textView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // 退出键盘 textView.resignFirstResponder() } deinit { // 注销通知 NotificationCenter.default.removeObserver(self) } // MARK: - 监听方法 /// 关闭按钮监听方法 @objc fileprivate func close() { dismiss(animated: true, completion: nil) } /// 发布微博 @IBAction func postStatus() { textView.resignFirstResponder() let text = textView.emoticonText SVProgressHUD.show() let image: UIImage? = nil //#imageLiteral(resourceName: "notification.png") WBNetworkManager.shared.postStatus(text: text, image: image) { (result, isSuccess) in let message = isSuccess ? "发布成功" : "网络不给了,请稍后重试" SVProgressHUD.showInfo(withStatus: message) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { self.close() // 如果发布成功, 刷新数据 if isSuccess { let mainVC = UIApplication.shared.keyWindow?.rootViewController as? WBMainViewController let nav = mainVC?.childViewControllers[0] as? WBNavigationViewController let homeVC = nav?.childViewControllers[0] as? WBHomeViewController homeVC?.loadData() } }) } } /// 键盘frame监听方法 @objc private func keyboardChanged(n: Notification) { guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } let yOffset: CGFloat = view.bounds.height - rect.origin.y toolbarBottomCons.constant = yOffset UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } /// 切换表情键盘 - 如果使用系统默认键盘, inputView 为 nil @objc private func emoticonKeyboard() { textView.inputView = (textView.inputView == nil) ? emoticonKeyboardView : nil textView.reloadInputViews() } } // MARK: - 设置界面 extension WBComposeViewController { fileprivate func setupUI() { view.backgroundColor = UIColor.white setupNavigationBar() setupToolbar() } /// 设置导航栏 private func setupNavigationBar() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close)) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton) navigationItem.title = "发微博" sendButton.isEnabled = false } /// 设置工具栏 private func setupToolbar() { /// 图片信息数组 let itemsInfo: [[String: String]] = [["imageName": "compose_toolbar_picture"], ["imageName": "compose_mentionbutton_background"], ["imageName": "compose_trendbutton_background"], ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"], ["imageName": "compose_add_background"]] var items = [UIBarButtonItem]() for dict in itemsInfo { guard let imageName = dict["imageName"] else { return } let image = UIImage(named: imageName) let imageHL = UIImage(named: imageName + "_highlighted") let btn: UIButton = UIButton() btn.setBackgroundImage(image, for: []) btn.setBackgroundImage(imageHL, for: .highlighted) btn.sizeToFit() if let actionName = dict["actionName"] { btn.addTarget(self, action: Selector(actionName), for: .touchUpInside) } items.append(UIBarButtonItem(customView: btn)) // 添加弹簧 items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)) } // 删除末尾的弹簧 items.removeLast() toolbar.items = items } } // MARK: - UITextViewDelegate extension WBComposeViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { // 修改 '发布' 按钮状态 sendButton.isEnabled = textView.hasText } }
e59165d7081a0dfd4416734194279fc4
28.591837
158
0.556897
false
false
false
false
toggl/superday
refs/heads/develop
teferi/UI/Modules/Timeline/TimeIntervalHelper.swift
bsd-3-clause
1
import UIKit func calculatedLineHeight(for duration: TimeInterval) -> CGFloat { let minutes = (duration > 1 ? duration : 1) / 60 let height: Double let minHeight: Double = 16 guard minutes > 0 else { return CGFloat(minHeight) } if minutes <= 60 { height = 8/(15*minutes) + 120/15 } else { height = (480 + minutes) / 13.5 } return CGFloat(max(height, minHeight)) } func formatedElapsedTimeText(for duration: TimeInterval) -> String { let hourMask = "%01d h %01d min" let minuteMask = "%01d min" let components = elapsedTimeComponents(for: duration) return components.hour! > 0 ? String(format: hourMask, components.hour!, components.minute!) : String(format: minuteMask, components.minute!) } func formatedElapsedTimeLongText(for duration: TimeInterval) -> String { let components = elapsedTimeComponents(for: duration) guard let hours = components.hour, let minutes = components.minute else { return "0 hours" } if hours > 0 { if minutes > 0 { return String(format: "%.1f hours", (Double(hours) + Double(minutes) / 60)) } if hours == 1 { return "1 hour" } return String(format: "%01d hours", hours) } if minutes == 1 { return "1 minute" } return String(format: "%01d minutes", minutes) } func elapsedTimeComponents(for duration: TimeInterval) -> DateComponents { let minutes = (Int(duration) / 60) % 60 let hours = (Int(duration) / 3600) let components = DateComponents(hour: hours, minute: minutes) return components }
c240a38204662e67098dcb4bd66fa2b3
25.935484
96
0.617365
false
false
false
false
onmyway133/Github.swift
refs/heads/master
Carthage/Checkouts/Sugar/Source/iOS/Extensions/UITableView+Indexes.swift
mit
1
import UIKit public extension UITableView { func insert(indexes: [Int], section: Int = 0, animation: UITableViewRowAnimation = .Automatic) { let indexPaths = indexes.map { NSIndexPath(forRow: $0, inSection: section) } if animation == .None { UIView.setAnimationsEnabled(false) } performUpdates { insertRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } if animation == .None { UIView.setAnimationsEnabled(true) } } func reload(indexes: [Int], section: Int = 0, animation: UITableViewRowAnimation = .Automatic) { let indexPaths = indexes.map { NSIndexPath(forRow: $0, inSection: section) } if animation == .None { UIView.setAnimationsEnabled(false) } performUpdates { reloadRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } if animation == .None { UIView.setAnimationsEnabled(true) } } func delete(indexes: [Int], section: Int = 0, animation: UITableViewRowAnimation = .Automatic) { let indexPaths = indexes.map { NSIndexPath(forRow: $0, inSection: section) } if animation == .None { UIView.setAnimationsEnabled(false) } performUpdates { deleteRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } if animation == .None { UIView.setAnimationsEnabled(true) } } func reloadSection(section: Int = 0, animation: UITableViewRowAnimation = .Automatic) { if animation == .None { UIView.setAnimationsEnabled(false) } performUpdates { reloadSections(NSIndexSet(index: section), withRowAnimation: animation) } if animation == .None { UIView.setAnimationsEnabled(true) } } private func performUpdates(@noescape closure: () -> Void) { beginUpdates() closure() endUpdates() } }
7d2673abc6610a45b2f0ac4f1471a704
41.45
98
0.717314
false
false
false
false
wonderkiln/WKAwesomeMenu
refs/heads/master
Pods/SnapKit/Source/ConstraintMakerExtendable.swift
mit
1
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public class ConstraintMakerExtendable: ConstraintMakerRelatable { public var left: ConstraintMakerExtendable { self.description.attributes += .left return self } public var top: ConstraintMakerExtendable { self.description.attributes += .top return self } public var bottom: ConstraintMakerExtendable { self.description.attributes += .bottom return self } public var right: ConstraintMakerExtendable { self.description.attributes += .right return self } public var leading: ConstraintMakerExtendable { self.description.attributes += .leading return self } public var trailing: ConstraintMakerExtendable { self.description.attributes += .trailing return self } public var width: ConstraintMakerExtendable { self.description.attributes += .width return self } public var height: ConstraintMakerExtendable { self.description.attributes += .height return self } public var centerX: ConstraintMakerExtendable { self.description.attributes += .centerX return self } public var centerY: ConstraintMakerExtendable { self.description.attributes += .centerY return self } @available(*, deprecated:0.40.0, message:"Use lastBaseline instead") public var baseline: ConstraintMakerExtendable { self.description.attributes += .lastBaseline return self } public var lastBaseline: ConstraintMakerExtendable { self.description.attributes += .lastBaseline return self } @available(iOS 8.0, OSX 10.11, *) public var firstBaseline: ConstraintMakerExtendable { self.description.attributes += .firstBaseline return self } @available(iOS 8.0, *) public var leftMargin: ConstraintMakerExtendable { self.description.attributes += .leftMargin return self } @available(iOS 8.0, *) public var rightMargin: ConstraintMakerExtendable { self.description.attributes += .rightMargin return self } @available(iOS 8.0, *) public var bottomMargin: ConstraintMakerExtendable { self.description.attributes += .bottomMargin return self } @available(iOS 8.0, *) public var leadingMargin: ConstraintMakerExtendable { self.description.attributes += .leadingMargin return self } @available(iOS 8.0, *) public var trailingMargin: ConstraintMakerExtendable { self.description.attributes += .trailingMargin return self } @available(iOS 8.0, *) public var centerXWithinMargins: ConstraintMakerExtendable { self.description.attributes += .centerXWithinMargins return self } @available(iOS 8.0, *) public var centerYWithinMargins: ConstraintMakerExtendable { self.description.attributes += .centerYWithinMargins return self } public var edges: ConstraintMakerExtendable { self.description.attributes += .edges return self } public var size: ConstraintMakerExtendable { self.description.attributes += .size return self } @available(iOS 8.0, *) public var margins: ConstraintMakerExtendable { self.description.attributes += .margins return self } @available(iOS 8.0, *) public var centerWithinMargins: ConstraintMakerExtendable { self.description.attributes += .centerWithinMargins return self } }
73d0ec3bee15e3d964f0743199db52bb
29.325153
81
0.668015
false
false
false
false
jeffreybergier/udacity-animation
refs/heads/master
animation-playground.playground/Pages/Gesture Recognizers.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import UIKit import XCPlayground // MARK: Custom View Controller Subclass class SpringViewController: UIViewController { // MARK: Custom Properties let redView: UIView = { let view = UIView() view.backgroundColor = UIColor.redColor() view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var xConstraint: NSLayoutConstraint = { self.redView.centerXAnchor.constraintEqualToAnchor(vc.view.centerXAnchor, constant: 0) }() lazy var yConstraint: NSLayoutConstraint = { self.redView.centerYAnchor.constraintEqualToAnchor(vc.view.centerYAnchor, constant: 0) }() // MARK: Configure the View Controller override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.configureRedView() } // MARK: Add View to Animate // and configure constraints func configureRedView() { vc.view.addSubview(self.redView) NSLayoutConstraint.activateConstraints( [ self.xConstraint, self.yConstraint, self.redView.heightAnchor.constraintEqualToConstant(60), self.redView.widthAnchor.constraintEqualToConstant(60) ] ) } // MARK: Handle Animations from Gesture Recognizer func animateBackToCenter() { UIView.animateWithDuration( 0.6, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 1.5, options: [], animations: { self.xConstraint.constant = 0 self.yConstraint.constant = 0 vc.view.setNeedsLayout() }, completion: { finished in print("Snapped Back") } ) } func gestureFired(sender: UIPanGestureRecognizer) { switch sender.state { case .Began, .Possible: // don't need to do anything to start break case .Changed: // get the amount of change cause by the finger moving let translation = sender.translationInView(vc.view) // add that change to our autolayout constraints xConstraint.constant += translation.x yConstraint.constant += translation.y // tell the view to update vc.view.setNeedsLayout() // reset the translation in the gesture recognizer to 0 // try removing this line of code and see what happens when dragging sender.setTranslation(CGPoint.zero, inView: vc.view) case .Cancelled, .Ended, .Failed: // animate back to the center when done animateBackToCenter() } } } // MARK: Instantiate Spring View Controller let vc = SpringViewController() vc.view.frame = CGRect(x: 0, y: 0, width: 400, height: 600) XCPlaygroundPage.currentPage.liveView = vc.view // MARK: Configure Gesture Recognizer let panGestureRecognizer = UIPanGestureRecognizer(target: vc, action: #selector(vc.gestureFired(_:))) vc.redView.addGestureRecognizer(panGestureRecognizer)
15cfea5ef80f3050a8364fada71290d7
30.970588
139
0.611469
false
false
false
false
titi-us/StarlingDemoKit
refs/heads/master
StarlingKit/MovieScene.swift
mit
1
// // MovieScene.swift // StarlingKit // // Created by Thibaut Crenn on 11/13/14. // Copyright (c) 2014 Thibaut Crenn. All rights reserved. // import Foundation import SpriteKit class MovieScene:BaseScene { override init() { var textures:[SKTexture] = []; var i = 0; for (i; i < 14; i++) { let dec = Int(i/10) let rem = i - dec*10 textures.append(SKTexture(imageNamed: "flight_"+String(dec)+String(rem))) } let movieClip = SKSpriteNode(texture: textures[0]) let action = SKAction.repeatActionForever(SKAction.animateWithTextures(textures, timePerFrame: 0.05)) movieClip.runAction(action) super.init() self.addChild(movieClip) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
b27545287b90e15ed46bab04a5e4461d
22.74359
109
0.573434
false
false
false
false
laszlokorte/reform-swift
refs/heads/master
ReformCore/ReformCore/RotateInstruction.swift
mit
1
// // RotateInstruction.swift // ReformCore // // Created by Laszlo Korte on 14.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath public struct RotateInstruction : Instruction { public typealias PointType = LabeledPoint public typealias AngleType = RuntimeRotationAngle & Labeled public var target : FormIdentifier? { return formId } public let formId : FormIdentifier public let angle : AngleType public let fixPoint : PointType public init(formId: FormIdentifier, angle: AngleType, fixPoint: PointType) { self.formId = formId self.angle = angle self.fixPoint = fixPoint } public func evaluate<T:Runtime>(_ runtime: T) { guard let form = runtime.get(formId) as? Rotatable else { runtime.reportError(.unknownForm) return } guard let fix : Vec2d = fixPoint.getPositionFor(runtime) else { runtime.reportError(.invalidFixPoint) return } guard let a : Angle = angle.getAngleFor(runtime) else { runtime.reportError(.invalidAngle) return } form.rotator.rotate(runtime, angle: a, fix: fix) } public func getDescription(_ stringifier: Stringifier) -> String { let formName = stringifier.labelFor(formId) ?? "???" return "Rotate \(formName) around \(fixPoint.getDescription(stringifier)) by \(angle.getDescription(stringifier))" } public func analyze<T:Analyzer>(_ analyzer: T) { } public var isDegenerated : Bool { return angle.isDegenerated } } extension RotateInstruction : Mergeable { public func mergeWith(_ other: RotateInstruction, force: Bool) -> RotateInstruction? { guard formId == other.formId else { return nil } if force { return other } guard fixPoint.isEqualTo(other.fixPoint) else { return nil } guard let angleA = angle as? ConstantAngle, let angleB = other.angle as? ConstantAngle else { return nil } return RotateInstruction(formId: formId, angle: combine(angle: angleA, angle: angleB), fixPoint: fixPoint) } }
0e9b64bda9d8b867287976aefc504c22
26.819277
130
0.614985
false
false
false
false
TinyCrayon/TinyCrayon-iOS-SDK
refs/heads/master
TCMask/ImageScrollView.swift
mit
1
// // ImageScrollView.swift // TinyCrayon // // Created by Xin Zeng on 1/4/16. // // import UIKit enum FitMode { case inner, outer } class ImageScrollView: UIScrollView, UIScrollViewDelegate { var baseView: UIView var zoomFactor: CGFloat = 1 var minScale: CGFloat = 1 var fitMode = FitMode.inner var draggingDisabled = false override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if let gesture = gestureRecognizer as? UIPanGestureRecognizer { if draggingDisabled && gesture.numberOfTouches == 1 { return false } } return true } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if (draggingDisabled) { targetContentOffset.pointee = scrollView.contentOffset } } weak var _zoomView: UIView? var zoomView: UIView? { willSet { _zoomView?.removeFromSuperview() if let view = newValue { baseView.addSubview(view) } _zoomView = newValue } } required init?(coder aDecoder: NSCoder) { baseView = UIView() super.init(coder: aDecoder) self.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] self.clipsToBounds = true self.bounces = true self.bouncesZoom = true self.delegate = self self.delaysContentTouches = true self.addSubview(baseView) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return baseView } func refresh() { self.resetImageViewFrame() self.resetZoomScale(false, resetScale: true) } func resetImageViewFrame() -> (){ if let view = _zoomView { view.frame.origin = CGPoint(x: 0, y: 0) baseView.bounds = view.bounds } } func resetZoomScale(_ animated: Bool, resetScale: Bool = false) -> (){ if let view = _zoomView { let rw = self.width / view.width let rh = self.height / view.height if (self.fitMode == FitMode.inner) { self.minimumZoomScale = min(rw, rh) self.maximumZoomScale = max(max(rw, rh) * zoomFactor, self.minimumZoomScale) } else { self.minimumZoomScale = max(rw, rh) self.maximumZoomScale = self.minimumZoomScale * zoomFactor } if (resetScale) { self.contentSize = view.frame.size self.setZoomScale(minimumZoomScale, animated: animated) } else { self.setZoomScale(zoomScale, animated: animated) } scrollViewDidZoom(self) } } func scrollViewDidZoom(_ scrollView: UIScrollView) { let ws = scrollView.width - scrollView.contentInset.left - scrollView.contentInset.right let hs = scrollView.height - scrollView.contentInset.top - scrollView.contentInset.bottom let w = baseView.width let h = baseView.height var rct = baseView.frame rct.origin.x = max((ws-w)/2, 0) rct.origin.y = max((hs-h)/2, 0) baseView.frame = rct } }
6ed7a5a156d570b5b5ed7759077153d8
29.469027
148
0.585536
false
false
false
false
duzexu/ARuler
refs/heads/master
ARuler/ViewController/SupportViewController.swift
gpl-2.0
1
// // SupportViewController.swift // ARuler // // Created by duzexu on 2017/9/21. // Copyright © 2017年 duzexu. All rights reserved. // import UIKit import StoreKit import SafariServices class SupportViewController: UIViewController { var values: Array<String>! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. SKStoreReviewController.requestReview() values = ["去 APP Store 评价","分享给你的朋友","给此开源项目 Star","打赏作者"] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension SupportViewController : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return values.count } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UILabel() header.font = UIFont.systemFont(ofSize: 14) header.textColor = UIColor.headerTextColor header.text = " 可以通过以下方式表达对ARuler的支持" return header } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.supportCell.identifier, for: indexPath) cell.accessoryType = .none cell.textLabel?.font = UIFont.systemFont(ofSize: 16) cell.textLabel?.textColor = UIColor.textColor cell.textLabel?.text = values[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: let url = "itms-apps://itunes.apple.com/app/id1255077231?action=write-review" UIApplication.shared.open(URL(string: url)!, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) break case 1: let share = UIActivityViewController(activityItems: [R.image.logo()!,URL(string: "https://itunes.apple.com/us/app/aruler/id1255077231?l=zh&mt=8")!,"我正在使用ARuler测距离,快来试试吧!"], applicationActivities: nil) self.navigationController?.present(share, animated: true, completion: nil) break case 2: let vc = WebViewController(url: "https://github.com/duzexu/ARuler") self.navigationController?.pushViewController(vc, animated: true) break case 3: self.navigationController?.pushViewController(R.storyboard.main.donateViewController()!, animated: true) break default: break } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
5d81a69738c4c643ce9f3d7c403e7394
36.686047
212
0.682197
false
false
false
false
SwiftKickMobile/SwiftMessages
refs/heads/master
SwiftMessages/Animator.swift
mit
1
// // Animator.swift // SwiftMessages // // Created by Timothy Moose on 6/4/17. // Copyright © 2017 SwiftKick Mobile. All rights reserved. // import UIKit public typealias AnimationCompletion = (_ completed: Bool) -> Void public protocol AnimationDelegate: AnyObject { func hide(animator: Animator) func panStarted(animator: Animator) func panEnded(animator: Animator) } /** An option set representing the known types of safe area conflicts that could require margin adjustments on the message view in order to get the layouts to look right. */ public struct SafeZoneConflicts: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// Message view behind status bar public static let statusBar = SafeZoneConflicts(rawValue: 1 << 0) /// Message view behind the sensor notch on iPhone X public static let sensorNotch = SafeZoneConflicts(rawValue: 1 << 1) /// Message view behind home indicator on iPhone X public static let homeIndicator = SafeZoneConflicts(rawValue: 1 << 2) /// Message view is over the status bar on an iPhone 8 or lower. This is a special /// case because we logically expect the top safe area to be zero, but it is reported as 20 /// (which seems like an iOS bug). We use the `overStatusBar` to indicate this special case. public static let overStatusBar = SafeZoneConflicts(rawValue: 1 << 3) } public class AnimationContext { public let messageView: UIView public let containerView: UIView public let safeZoneConflicts: SafeZoneConflicts public let interactiveHide: Bool init(messageView: UIView, containerView: UIView, safeZoneConflicts: SafeZoneConflicts, interactiveHide: Bool) { self.messageView = messageView self.containerView = containerView self.safeZoneConflicts = safeZoneConflicts self.interactiveHide = interactiveHide } } public protocol Animator: AnyObject { /// Adopting classes should declare as `weak`. var delegate: AnimationDelegate? { get set } func show(context: AnimationContext, completion: @escaping AnimationCompletion) func hide(context: AnimationContext, completion: @escaping AnimationCompletion) /// The show animation duration. If the animation duration is unknown, such as if using `UIDynamicAnimator`, /// then provide an estimate. This value is used by `SwiftMessagesSegue`. var showDuration: TimeInterval { get } /// The hide animation duration. If the animation duration is unknown, such as if using `UIDynamicAnimator`, /// then provide an estimate. This value is used by `SwiftMessagesSegue`. var hideDuration: TimeInterval { get } }
cc3c27ef56daca5f53b7af6ed79e0439
33.948718
115
0.728173
false
false
false
false
anhnc55/fantastic-swift-library
refs/heads/master
Example/Pods/paper-onboarding/Source/PageView/PageContainerView/PageContainer.swift
mit
1
// // PageContaineView.swift // AnimatedPageView // // Created by Alex K. on 13/04/16. // Copyright © 2016 Alex K. All rights reserved. // import UIKit class PageContrainer: UIView { var items: [PageViewItem]? let space: CGFloat // space between items var currentIndex = 0 private let itemRadius: CGFloat private let selectedItemRadius: CGFloat private let itemsCount: Int private let animationKey = "animationKey" init(radius: CGFloat, selectedRadius: CGFloat, space: CGFloat, itemsCount: Int) { self.itemsCount = itemsCount self.space = space self.itemRadius = radius self.selectedItemRadius = selectedRadius super.init(frame: CGRect.zero) items = createItems(itemsCount, radius: radius, selectedRadius: selectedRadius) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: public extension PageContrainer { func currenteIndex(index: Int, duration: Double, animated: Bool) { guard let items = self.items where index != currentIndex else {return} animationItem(items[index], selected: true, duration: duration) let fillColor = index > currentIndex ? true : false animationItem(items[currentIndex], selected: false, duration: duration, fillColor: fillColor) currentIndex = index } } // MARK: animations extension PageContrainer { private func animationItem(item: PageViewItem, selected: Bool, duration: Double, fillColor: Bool = false) { let toValue = selected == true ? selectedItemRadius * 2 : itemRadius * 2 item.constraints .filter{ $0.identifier == "animationKey" } .forEach { $0.constant = toValue } UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) item.animationSelected(selected, duration: duration, fillColor: fillColor) } } // MARK: create extension PageContrainer { private func createItems(count: Int, radius: CGFloat, selectedRadius: CGFloat) -> [PageViewItem] { var items = [PageViewItem]() // create first item var item = createItem(radius, selectedRadius: selectedRadius, isSelect: true) addConstraintsToView(item, radius: selectedRadius) items.append(item) for _ in 1..<count { let nextItem = createItem(radius, selectedRadius: selectedRadius) addConstraintsToView(nextItem, leftItem: item, radius: radius) items.append(nextItem) item = nextItem } return items } private func createItem(radius: CGFloat, selectedRadius: CGFloat, isSelect: Bool = false) -> PageViewItem { let item = Init(PageViewItem(radius: radius, selectedRadius: selectedRadius, isSelect: isSelect)) { $0.translatesAutoresizingMaskIntoConstraints = false $0.backgroundColor = .clearColor() } self.addSubview(item) return item } private func addConstraintsToView(item: UIView, radius: CGFloat) { [NSLayoutAttribute.Left, NSLayoutAttribute.CenterY].forEach { attribute in (self, item) >>>- { $0.attribute = attribute } } [NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in item >>>- { $0.attribute = attribute $0.constant = radius * 2.0 $0.identifier = animationKey } } } private func addConstraintsToView(item: UIView, leftItem: UIView, radius: CGFloat) { (self, item) >>>- { $0.attribute = .CenterY } (self, item, leftItem) >>>- { $0.attribute = .Leading $0.secondAttribute = .Trailing $0.constant = space } [NSLayoutAttribute.Width, NSLayoutAttribute.Height].forEach { attribute in item >>>- { $0.attribute = attribute $0.constant = radius * 2.0 $0.identifier = animationKey } } } }
4633c9d48180d2ef06f264fd81acc427
28.857143
109
0.657179
false
false
false
false
kickstarter/ios-oss
refs/heads/main
KsApi/models/graphql/adapters/Reward+RewardFragmentTests.swift
apache-2.0
1
@testable import KsApi import Prelude import XCTest final class Reward_RewardFragmentTests: XCTestCase { func test() { do { let variables = ["includeShippingRules": true, "includeLocalPickup": true] let fragment = try GraphAPI.RewardFragment(jsonObject: rewardDictionary(), variables: variables) XCTAssertNotNil(fragment) let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) dateFormatter.dateFormat = "yyyy-MM-dd" guard let v1Reward = Reward.reward( from: fragment, dateFormatter: dateFormatter ) else { XCTFail("reward should be created from fragment") return } XCTAssertEqual(v1Reward.backersCount, 13) XCTAssertEqual(v1Reward.convertedMinimum, 31.0) XCTAssertEqual(v1Reward.description, "Description") XCTAssertEqual(v1Reward.endsAt, nil) XCTAssertEqual(v1Reward.estimatedDeliveryOn, 1_638_316_800.0) XCTAssertEqual(v1Reward.id, 8_173_901) XCTAssertEqual(v1Reward.limit, nil) XCTAssertEqual(v1Reward.limitPerBacker, 1) XCTAssertEqual(v1Reward.minimum, 25.0) XCTAssertEqual(v1Reward.localPickup?.country, "US") XCTAssertEqual(v1Reward.localPickup?.localizedName, "San Jose") XCTAssertEqual(v1Reward.localPickup?.displayableName, "San Jose, CA") XCTAssertEqual(v1Reward.localPickup?.id, decompose(id: "TG9jYXRpb24tMjQ4ODA0Mg==")) XCTAssertEqual(v1Reward.localPickup?.name, "San Jose") XCTAssertTrue(v1Reward.hasAddOns) XCTAssertEqual(v1Reward.remaining, nil) XCTAssertEqual(v1Reward.rewardsItems[0].item.id, 1_170_799) XCTAssertEqual(v1Reward.rewardsItems[0].item.name, "Soft-Cover Book (Signed)") XCTAssertEqual(v1Reward.rewardsItems[0].quantity, 2) XCTAssertEqual(v1Reward.rewardsItems[1].item.id, 1_170_813) XCTAssertEqual(v1Reward.rewardsItems[1].item.name, "Custom Bookmark") XCTAssertEqual(v1Reward.rewardsItems[1].quantity, 1) XCTAssertEqual(v1Reward.shipping.enabled, true) XCTAssertEqual(v1Reward.shipping.preference, .unrestricted) XCTAssertEqual(v1Reward.shipping.summary, "Ships worldwide") XCTAssertEqual(v1Reward.shippingRules?.count, 2) XCTAssertEqual(v1Reward.startsAt, nil) XCTAssertEqual(v1Reward.title, "Soft Cover Book (Signed)") XCTAssertEqual(v1Reward.isLimitedQuantity, false) XCTAssertEqual(v1Reward.isLimitedTime, false) } catch { XCTFail(error.localizedDescription) } } } private func rewardDictionary() -> [String: Any] { let json = """ { "__typename": "Reward", "allowedAddons": { "__typename": "RewardConnection", "pageInfo": { "__typename": "PageInfo", "startCursor": "WzIsODMzNzczN10=" } }, "localReceiptLocation": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "San Jose, CA", "id": "TG9jYXRpb24tMjQ4ODA0Mg==", "name": "San Jose" }, "amount": { "__typename": "Money", "amount": "25.0", "currency": "USD", "symbol": "$" }, "backersCount": 13, "convertedAmount": { "__typename": "Money", "amount": "31.0", "currency": "CAD", "symbol": "$" }, "description": "Description", "displayName": "Soft Cover Book (Signed) ($25)", "endsAt": null, "estimatedDeliveryOn": "2021-12-01", "id": "UmV3YXJkLTgxNzM5MDE=", "isMaxPledge": false, "items": { "__typename": "RewardItemsConnection", "edges": [ { "__typename": "RewardItemEdge", "quantity": 2, "node": { "__typename": "RewardItem", "id": "UmV3YXJkSXRlbS0xMTcwNzk5", "name": "Soft-Cover Book (Signed)" } }, { "__typename": "RewardItemEdge", "quantity": 1, "node": { "__typename": "RewardItem", "id": "UmV3YXJkSXRlbS0xMTcwODEz", "name": "Custom Bookmark" } } ] }, "limit": null, "limitPerBacker": 1, "name": "Soft Cover Book (Signed)", "project": { "__typename": "Project", "id": "UHJvamVjdC0xNTk2NTk0NDYz" }, "remainingQuantity": null, "shippingSummary": "Ships worldwide", "shippingPreference": "unrestricted", "shippingRules": [{ "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExNDEzMzc5", "location": { "__typename": "Location", "country": "ZZ", "countryName": null, "displayableName": "Earth", "id": "TG9jYXRpb24tMQ==", "name": "Rest of World" } }, { "__typename": "ShippingRule", "cost": { "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" }, "id": "U2hpcHBpbmdSdWxlLTExMjc4NzUy", "location": { "__typename": "Location", "country": "US", "countryName": "United States", "displayableName": "United States", "id": "TG9jYXRpb24tMjM0MjQ5Nzc=", "name": "United States" } } ], "startsAt": null } """ let data = Data(json.utf8) return (try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]) ?? [:] }
27c526870ff185f8f0d79b427364dec6
30.451977
102
0.587031
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/Parse/matching_patterns.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-source-import import imported_enums // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int,Int), y: (Int,Int,Int)) -> Bool { return true } var x:Int func square(_ x: Int) -> Int { return x*x } struct A<B> { struct C<D> { } } switch x { // Expressions as patterns. case 0: () case 1 + 2: () case square(9): () // 'var' and 'let' patterns. case var a: a = 1 case let a: a = 1 // expected-error {{cannot assign}} case var var a: // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} a += 1 case var let a: // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} print(a, terminator: "") case var (var b): // expected-error {{'var' cannot appear nested inside another 'var'}} b += 1 // 'Any' pattern. case _: () // patterns are resolved in expression-only positions are errors. case 1 + (_): // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} () } switch (x,x) { case (var a, var a): // expected-error {{definition conflicts with previous value}} expected-note {{previous definition of 'a' is here}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} fallthrough case _: () } var e : Any = 0 switch e { // expected-error {{switch must be exhaustive, consider adding a default clause:}} // 'is' pattern. case is Int, is A<Int>, is A<Int>.C<Int>, is (Int, Int), is (a: Int, b: Int): () } // Enum patterns. enum Foo { case A, B, C } func == <T>(_: Voluntary<T>, _: Voluntary<T>) -> Bool { return true } enum Voluntary<T> : Equatable { case Naught case Mere(T) case Twain(T, T) func enumMethod(_ other: Voluntary<T>, foo: Foo) { switch self { case other: () case .Naught, .Naught(), .Naught(_, _): // expected-error{{tuple pattern has the wrong length for tuple type '()'}} () case .Mere, .Mere(), // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} .Mere(_), .Mere(_, _): // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} () case .Twain(), // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} .Twain(_), .Twain(_, _), .Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} () } switch foo { case .Naught: // expected-error{{pattern cannot match values of type 'Foo'}} () case .A, .B, .C: () } } } var n : Voluntary<Int> = .Naught switch n { case Foo.A: // expected-error{{enum case 'A' is not a member of type 'Voluntary<Int>'}} () case Voluntary<Int>.Naught, Voluntary<Int>.Naught(), Voluntary<Int>.Naught(_, _), // expected-error{{tuple pattern has the wrong length for tuple type '()'}} Voluntary.Naught, .Naught: () case Voluntary<Int>.Mere, Voluntary<Int>.Mere(_), Voluntary<Int>.Mere(_, _), // expected-error{{tuple pattern cannot match values of the non-tuple type 'Int'}} Voluntary.Mere, Voluntary.Mere(_), .Mere, .Mere(_): () case .Twain, .Twain(_), .Twain(_, _), .Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(Int, Int)'}} () } var notAnEnum = 0 switch notAnEnum { case .Foo: // expected-error{{pattern cannot match values of type 'Int'}} () } struct ContainsEnum { enum Possible<T> { case Naught case Mere(T) case Twain(T, T) } func member(_ n: Possible<Int>) { switch n { // expected-error {{switch must be exhaustive, consider adding missing cases:}} // expected-note@-1 {{missing case: '.Mere(_)'}} // expected-note@-2 {{missing case: '.Twain(_, _)'}} case ContainsEnum.Possible<Int>.Naught, ContainsEnum.Possible.Naught, Possible<Int>.Naught, Possible.Naught, .Naught: () } } } func nonmemberAccessesMemberType(_ n: ContainsEnum.Possible<Int>) { switch n { // expected-error {{switch must be exhaustive, consider adding missing cases:}} // expected-note@-1 {{missing case: '.Mere(_)'}} // expected-note@-2 {{missing case: '.Twain(_, _)'}} case ContainsEnum.Possible<Int>.Naught, .Naught: () } } var m : ImportedEnum = .Simple switch m { case imported_enums.ImportedEnum.Simple, ImportedEnum.Simple, .Simple: () case imported_enums.ImportedEnum.Compound, imported_enums.ImportedEnum.Compound(_), ImportedEnum.Compound, ImportedEnum.Compound(_), .Compound, .Compound(_): () } // Check that single-element tuple payloads work sensibly in patterns. enum LabeledScalarPayload { case Payload(name: Int) } var lsp: LabeledScalarPayload = .Payload(name: 0) func acceptInt(_: Int) {} func acceptString(_: String) {} switch lsp { case .Payload(0): () case .Payload(name: 0): () case let .Payload(x): acceptInt(x) acceptString("\(x)") case let .Payload(name: x): acceptInt(x) acceptString("\(x)") case let .Payload((name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let x): acceptInt(x) acceptString("\(x)") case .Payload((let x)): acceptInt(x) acceptString("\(x)") } // Property patterns. struct S { static var stat: Int = 0 var x, y : Int var comp : Int { return x + y } func nonProperty() {} } // Tuple patterns. var t = (1, 2, 3) prefix operator +++ infix operator +++ prefix func +++(x: (Int,Int,Int)) -> (Int,Int,Int) { return x } func +++(x: (Int,Int,Int), y: (Int,Int,Int)) -> (Int,Int,Int) { return (x.0+y.0, x.1+y.1, x.2+y.2) } switch t { case (_, var a, 3): a += 1 case var (_, b, 3): b += 1 case var (_, var c, 3): // expected-error{{'var' cannot appear nested inside another 'var'}} c += 1 case (1, 2, 3): () // patterns in expression-only positions are errors. case +++(_, var d, 3): // expected-error@-1{{'+++' is not a prefix unary operator}} () case (_, var e, 3) +++ (1, 2, 3): // expected-error@-1{{'_' can only appear in a pattern}} // expected-error@-2{{'var' binding pattern cannot appear in an expression}} () } // FIXME: We don't currently allow subpatterns for "isa" patterns that // require interesting conditional downcasts. class Base { } class Derived : Base { } switch [Derived(), Derived(), Base()] { case let ds as [Derived]: // expected-error{{downcast pattern value of type '[Derived]' cannot be used}} () default: () } // Optional patterns. let op1 : Int? let op2 : Int?? switch op1 { case nil: break case 1?: break case _?: break } switch op2 { case nil: break case _?: break case (1?)?: break case (_?)?: break } // <rdar://problem/20365753> Bogus diagnostic "refutable pattern match can fail" let (responseObject: Int?) = op1 // expected-error @-1 {{expected ',' separator}} {{25-25=,}} // expected-error @-2 {{expected pattern}}
1917725646bc03f44c452386ac3aa3f9
22.120635
322
0.612385
false
false
false
false
PiXeL16/SwiftTMDB
refs/heads/master
swifttmdb/Movie.swift
mit
2
// // Movie.swift // swifttmdb // // Created by Christopher Jimenez on 7/1/15. // Copyright (c) 2015 greenpixels. All rights reserved. // import UIKit import SwiftyJSON /// Movie Model public class Movie:JSONAble { public var id: Int = 0 public var title: String public var overview: String public var releaseDate: String? public var backdropImagePath: NSURL? public var posterImagePath: NSURL? public var rating : Double? /** Inits Model with values :param: id movie ID :param: title movie Title :param: overview movie overview :param: releaseDate movie release date :param: backdropImagePath movie backdrop image path :param: posterImagePath movie poster image path :param: rating movie average rating :returns: <#return value description#> */ init(id: Int, title: String, overview: String, releaseDate: String?, backdropImagePath: NSURL?, posterImagePath: NSURL?, rating :Double?){ self.id = id self.title = title self.overview = overview self.releaseDate = releaseDate self.backdropImagePath = backdropImagePath self.posterImagePath = posterImagePath self.rating = rating } /// Parse movie from Json Representation override class func fromJSON(source:[String:AnyObject]) -> JSONAble{ let json = JSON(source) let id = json["id"].intValue let title = json["title"].stringValue let overview = json["overview"].stringValue let releaseDate = json["release_date"].stringValue let backdropImagePath = TMDB.createImageURL(image: json["backdrop_path"].stringValue, imageWidth: 342) let posterImagePath = TMDB.createImageURL(image: json["poster_path"].stringValue, imageWidth: 342) let rating = json["vote_average"].doubleValue return Movie(id: id, title: title, overview: overview, releaseDate: releaseDate, backdropImagePath: backdropImagePath, posterImagePath: posterImagePath, rating: rating) } }
e63ab2c4c313a37d83e26a025c838fce
32.641791
176
0.6189
false
false
false
false
grandiere/box
refs/heads/master
box/View/GridVisor/VGridVisorBar.swift
mit
1
import UIKit class VGridVisorBar:UIView { private(set) weak var viewEnergy:VGridVisorBarEnergy! private(set) weak var viewRange:VGridVisorBarRange! private weak var viewBack:VGridVisorBarBack! private weak var controller:CGridVisor! private let kBackSize:CGFloat = 70 private let kEnergyWidth:CGFloat = 70 private let kRangeWidth:CGFloat = 75 private let kRangeLeft:CGFloat = -5 init(controller:CGridVisor) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let viewBack:VGridVisorBarBack = VGridVisorBarBack( controller:self.controller) self.viewBack = viewBack let viewRange:VGridVisorBarRange = VGridVisorBarRange( controller:self.controller) self.viewRange = viewRange let viewEnergy:VGridVisorBarEnergy = VGridVisorBarEnergy( controller:controller) self.viewEnergy = viewEnergy addSubview(viewRange) addSubview(viewEnergy) addSubview(viewBack) NSLayoutConstraint.topToTop( view:viewBack, toView:self) NSLayoutConstraint.leftToLeft( view:viewBack, toView:self) NSLayoutConstraint.size( view:viewBack, constant:kBackSize) NSLayoutConstraint.equalsVertical( view:viewRange, toView:viewBack) NSLayoutConstraint.leftToRight( view:viewRange, toView:viewBack, constant:kRangeLeft) NSLayoutConstraint.width( view:viewRange, constant:kRangeWidth) NSLayoutConstraint.equalsVertical( view:viewEnergy, toView:self) NSLayoutConstraint.rightToRight( view:viewEnergy, toView:self) NSLayoutConstraint.width( view:viewEnergy, constant:kEnergyWidth) } required init?(coder:NSCoder) { return nil } }
a36d5e6263643cee4d1c3f60864aaec6
28.527027
65
0.617391
false
false
false
false
ahoppen/swift
refs/heads/main
test/Generics/generic_types.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift protocol MyFormattedPrintable { func myFormat() -> String } func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {} extension Int : MyFormattedPrintable { func myFormat() -> String { return "" } } struct S<T : MyFormattedPrintable> { var c : T static func f(_ a: T) -> T { return a } func f(_ a: T, b: Int) { return myPrintf("%v %v %v", a, b, c) } } func makeSInt() -> S<Int> {} typealias SInt = S<Int> var a : S<Int> = makeSInt() a.f(1,b: 2) var b : Int = SInt.f(1) struct S2<T> { @discardableResult static func f() -> T { S2.f() } } struct X { } var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}} enum Optional<T> { case element(T) case none init() { self = .none } init(_ t: T) { self = .element(t) } } typealias OptionalInt = Optional<Int> var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element var uniontest2 : Optional<Int> = OptionalInt.none var uniontest3 = OptionalInt(1) // FIXME: Stuff that should work, but doesn't yet. // var uniontest4 : OptInt = .none // var uniontest5 : OptInt = .Some(1) func formattedTest<T : MyFormattedPrintable>(_ a: T) { myPrintf("%v", a) } struct formattedTestS<T : MyFormattedPrintable> { func f(_ a: T) { formattedTest(a) } } struct GenericReq<T : IteratorProtocol, U : IteratorProtocol> where T.Element == U.Element { } func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element { var r = r return r.next()! } func testGetFirst(ir: Range<Int>) { _ = getFirst(ir.makeIterator()) as Int } struct XT<T> { init(t : T) { prop = (t, t) } static func f() -> T {} func g() -> T {} var prop : (T, T) } class YT<T> { init(_ t : T) { prop = (t, t) } deinit {} class func f() -> T {} func g() -> T {} var prop : (T, T) } struct ZT<T> { var x : T, f : Float } struct Dict<K, V> { subscript(key: K) -> V { get {} set {} } } class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}} subscript(key: K) -> V { get {} set {} } } typealias XI = XT<Int> typealias YI = YT<Int> typealias ZI = ZT<Int> var xi = XI(t: 17) var yi = YI(17) var zi = ZI(x: 1, f: 3.0) var i : Int = XI.f() i = XI.f() i = xi.g() i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}} i = yi.g() var xif : (XI) -> () -> Int = XI.g var gif : (YI) -> () -> Int = YI.g var ii : (Int, Int) = xi.prop ii = yi.prop xi.prop = ii yi.prop = ii var d1 : Dict<String, Int> var d2 : Dictionary<String, Int> d1["hello"] = d2["world"] i = d2["blarg"] struct RangeOfPrintables<R : Sequence> where R.Iterator.Element : MyFormattedPrintable { var r : R func format() -> String { var s : String for e in r { s = s + e.myFormat() + " " } return s } } struct Y {} struct SequenceY : Sequence, IteratorProtocol { typealias Iterator = SequenceY typealias Element = Y func next() -> Element? { return Y() } func makeIterator() -> Iterator { return self } } func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) { var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}} var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'SequenceY.Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}} } var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}} var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}} var notgenericNested : Array<Int<Float>> // expected-error{{cannot specialize non-generic type 'Int'}}{{33-40=}} // Make sure that redundant typealiases (that map to the same // underlying type) don't break protocol conformance or use. class XArray : ExpressibleByArrayLiteral { typealias Element = Int init() { } required init(arrayLiteral elements: Int...) { } } class YArray : XArray { typealias Element = Int required init(arrayLiteral elements: Int...) { super.init() } } var yarray : YArray = [1, 2, 3] var xarray : XArray = [1, 2, 3] // Type parameters can be referenced only via unqualified name lookup struct XParam<T> { // expected-note{{'XParam' declared here}} func foo(_ x: T) { _ = x as T } static func bar(_ x: T) { _ = x as T } } var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of generic struct 'generic_types.XParam<Swift.Int>'}} // Diagnose failure to meet a superclass requirement. class X1 { } class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}} class X3 { } var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}} protocol P { associatedtype AssocP } protocol Q { associatedtype AssocQ } struct X4 : P, Q { typealias AssocP = Int typealias AssocQ = String } struct X5<T, U> where T: P, T: Q, T.AssocP == T.AssocQ { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}} var y: X5<X4, Int> // expected-error{{'X5' requires the types 'X4.AssocP' (aka 'Int') and 'X4.AssocQ' (aka 'String') be equivalent}} // Recursive generic signature validation. class Top {} class Bottom<T : Bottom<Top>> {} // expected-error@-1 {{'Bottom' requires that 'Top' inherit from 'Bottom<Top>'}} // expected-note@-2 {{requirement specified as 'T' : 'Bottom<Top>' [with T = Top]}} // expected-error@-3 *{{generic class 'Bottom' has self-referential generic requirements}} // Invalid inheritance clause struct UnsolvableInheritance1<T : T.A> {} // expected-error@-1 {{'A' is not a member type of type 'T'}} // expected-error@-2 {{type 'T' constrained to non-protocol, non-class type 'T.A'}} struct UnsolvableInheritance2<T : U.A, U : T.A> {} // expected-error@-1 {{'A' is not a member type of type 'U'}} // expected-error@-2 {{'A' is not a member type of type 'T'}} // expected-error@-3 {{type 'T' constrained to non-protocol, non-class type 'U.A'}} // expected-error@-4 {{type 'U' constrained to non-protocol, non-class type 'T.A'}} enum X7<T> where X7.X : G { case X } // expected-error{{enum case 'X' is not a member type of 'X7<T>'}} // expected-error@-1{{cannot find type 'G' in scope}} // Test that contextual type resolution for generic metatypes is consistent // under a same-type constraint. protocol MetatypeTypeResolutionProto {} struct X8<T> { static var property1: T.Type { T.self } static func method1() -> T.Type { T.self } } extension X8 where T == MetatypeTypeResolutionProto { static var property2: T.Type { property1 } // ok, still .Protocol static func method2() -> T.Type { method1() } // ok, still .Protocol }
489a0e7588e9c888e2682333852a94f0
24.965385
148
0.641979
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01120-clang-codegen-codegenfunction-emitlvalueforfield.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse } b() { } protocol d { } } } func a: A, T) { } struct A { let end = i() func a<T : a = D>?) in 0)([0x31] = T, V, 3] as String) enum b = { enum a return ") enum S<H : String { } class B { func c enum B : [Int) { protocol P { return "a()) let foo as String) -> U) extension String { class A where T -> U) -> Any) in a { func c, V>) { let v: a { } return self.d.init(T: A> S(v: a { protocol C { } protocol a { class func ^(#object1, range.c, q: } } case c(a(start: A, q: self] { [0x31] in () protocol b = { } } } return p: a { } func d, d: Sequence> { } f = b> : Any, Any) {} extension String = b init(x() } struct B convenience init()() } protocol c { func b) typealias f : ExtensibleCollectionType>(x, range.E == [Int print(self.b { return self.E protocol A { } } } func c) { typealias B typealias B class A where d class A, T : c(T! { func i<j : A> T>() { self.c] = A, b = { c } } class B : c: A> { return $0.Type) -> { } } class a(): func b> { } extension Array { struct c : Array<T>?) -> String { } } enum A { protocol a { class a([self.b in func e() { let start = "\(i: a { protocol B { } protocol a { extension NSData { protocol c { return " } protocol b = B<T protocol A { case C typealias B { protocol P { import Foundation } class d<d == b } } var f : String = true { func g, 3] { let t: T.C> (z(range: [unowned self.startIndex) let foo as [$0 func a enum A = e(bytes: a { enum A { }) var d where B = i<T> Any) { } init() -> T : (c(T: b: Array) -> String { protocol a { } extension A { } typealias g, U.Iterator.<c<T>() import Foundation } (h> String { } () class a typealias f = B func f(a(") A<Int>(z(a struct S { class func b> T>) -> Any) -> { func f<b) } return { c, let h, a) } } func compose<U>(Any, g<T>(AnyObject) + seq: e: () { struct A { case s: A { } class A = 1)) class c } func i> e: c> T>(s: a {} print(f: T) -> { } } class A? { import Foundation } protocol d = e(T, f() -> String { print(") struct c: Bool], object2: A, e, length: start, T][c<T where T>) -> (".Type) -> { } print(n: String } S.e == [] typealias e : () { } class b } protocol B { let f == g: Range<h : T] in import Foundation } import Foundation } } public var b, V, Bool) { struct X.E } let foo as Boolean, AnyObject, T : B<Q<h
fce36ee1317d8d428d69217cff0d9199
13.494444
80
0.597547
false
false
false
false
richeterre/jumu-nordost-ios
refs/heads/master
JumuNordost/Models/Changeset.swift
mit
1
// // Changeset.swift // JumuNordost // // Created by Martin Richter on 03/03/16. // Copyright © 2016 Martin Richter. All rights reserved. // import Foundation struct Changeset<T: Equatable> { var deletions: [NSIndexPath] var modifications: [NSIndexPath] var insertions: [NSIndexPath] typealias ContentMatches = (T, T) -> Bool // MARK: - Lifecycle init(oldItems: [T], newItems: [T], contentMatches: ContentMatches) { deletions = oldItems.difference(newItems).map { item in return Changeset.indexPathForIndex(oldItems.indexOf(item)!) } modifications = oldItems.intersection(newItems) .filter({ item in let newItem = newItems[newItems.indexOf(item)!] return !contentMatches(item, newItem) }) .map({ item in return Changeset.indexPathForIndex(oldItems.indexOf(item)!) }) insertions = newItems.difference(oldItems).map { item in return NSIndexPath(forRow: newItems.indexOf(item)!, inSection: 0) } } // MARK: - Private Helpers private static func indexPathForIndex(index: Int) -> NSIndexPath { return NSIndexPath(forRow: index, inSection: 0) } }
a7347d84500604eff1d547524dde3794
26.478261
77
0.622627
false
false
false
false
GitHubCha2016/ZLSwiftFM
refs/heads/master
ZLSwiftFM/ZLSwiftFM/Classes/Tools/网络请求/HttpManager.swift
mit
1
// // HttpManager.swift // XLing // // Created by ZXL on 17/1/4. // Copyright © 2017年 zxl. All rights reserved. // import UIKit import Foundation import Alamofire import SwiftyJSON private let shareManager = HttpManager() class HttpManager: NSObject { class var share : HttpManager { return shareManager } } extension HttpManager { //MARK: - GET 请求 // let tools : NetworkRequest.shareInstance! func getRequest(urlString: String, params : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) { //使用Alamofire进行网络请求时,调用该方法的参数都是通过getRequest(urlString, params, success :, failture :)传入的,而success传入的其实是一个接受 [String : AnyObject]类型 返回void类型的函数 Alamofire.request(urlString, method: .get, parameters: params) .responseJSON { (response) in/*这里使用了闭包*/ //当请求后response是我们自定义的,这个变量用于接受服务器响应的信息 //使用switch判断请求是否成功,也就是response的result switch response.result { case .success(let value): //当响应成功是,使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success // if let value = response.result.value as? [String: AnyObject] { success(value as! [String : AnyObject]) // } let json = JSON(value) customLog(json) case .failure(let error): failture(error) print("请求错误 --- error:\(error)") } } } //MARK: - POST 请求 func postRequest(urlString : String, params : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) { Alamofire.request(urlString, method: HTTPMethod.post, parameters: params).responseJSON { (response) in switch response.result{ case .success: if let value = response.result.value as? [String: AnyObject] { success(value) let json = JSON(value) customLog(json) } case .failure(let error): failture(error) customLog("请求错误 --- error:\(error)") } } } //MARK: - 照片上传 /// /// - Parameters: /// - urlString: 服务器地址 /// - params: ["flag":"","userId":""] - flag,userId 为必传参数 /// flag - 666 信息上传多张 -999 服务单上传 -000 头像上传 /// - data: image转换成Data /// - name: fileName /// - success: /// - failture: func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){ let headers = ["content-type":"multipart/form-data"] Alamofire.upload( multipartFormData: { multipartFormData in //666多张图片上传 let flag = params["flag"] let userId = params["userId"] multipartFormData.append((flag?.data(using: String.Encoding.utf8)!)!, withName: "flag") multipartFormData.append( (userId?.data(using: String.Encoding.utf8)!)!, withName: "userId") for i in 0..<data.count { multipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png") } }, to: urlString, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in if let value = response.result.value as? [String: AnyObject]{ success(value) let json = JSON(value) customLog(json) } } case .failure(let encodingError): customLog(encodingError) failture(encodingError) } } ) } }
f09ea6027825ddc94e5467f0e2b05549
37.043478
206
0.509029
false
false
false
false
KyoheiG3/RxSwift
refs/heads/master
RxSwift/Observables/Implementations/Optional.swift
mit
1
// // Optional.swift // RxSwift // // Created by tarunon on 2016/12/13. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation class ObservableOptionalScheduledSink<O: ObserverType> : Sink<O> { typealias E = O.E typealias Parent = ObservableOptionalScheduled<E> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return _parent._scheduler.schedule(_parent._optional) { (optional: E?) -> Disposable in if let next = optional { self.forwardOn(.next(next)) return self._parent._scheduler.schedule(()) { _ in self.forwardOn(.completed) self.dispose() return Disposables.create() } } else { self.forwardOn(.completed) self.dispose() return Disposables.create() } } } } class ObservableOptionalScheduled<E> : Producer<E> { fileprivate let _optional: E? fileprivate let _scheduler: ImmediateSchedulerType init(optional: E?, scheduler: ImmediateSchedulerType) { _optional = optional _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } class ObservableOptional<E>: Producer<E> { private let _optional: E? init(optional: E?) { _optional = optional } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if let element = _optional { observer.on(.next(element)) } observer.on(.completed) return Disposables.create() } }
1f1898c277ef5c4dad44a27b19b2c603
28.828571
139
0.595307
false
false
false
false
ozgur/AutoLayoutAnimation
refs/heads/master
UserCollectionViewCell.swift
mit
1
// // UserCollectionViewCell.swift // AutoLayoutAnimation // // Created by Ozgur Vatansever on 10/26/15. // Copyright © 2015 Techshed. All rights reserved. // import UIKit @objc protocol UserCollectionViewCellDelegate: class { optional func cell(_ cell: UserCollectionViewCell, detailButtonTapped button: UIButton) } class UserCollectionViewCell: UICollectionViewCell { @IBOutlet fileprivate weak var nameLabel: UILabel! @IBOutlet fileprivate weak var someLabel: UILabel! weak var delegate: UserCollectionViewCellDelegate! var height: CGFloat = 0 var user: User! { didSet { nameLabel?.text = user?.firstName } } override func awakeFromNib() { super.awakeFromNib() nameLabel?.text = user?.firstName } @IBAction func detailTapped(_ sender: UIButton) { delegate?.cell?(self, detailButtonTapped: sender) } override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) let attributes = layoutAttributes as! UserCollectionViewLayoutAttributes someLabel?.text = "\(attributes.row) - \(attributes.column)" height = attributes.height } }
c3eb49992e21efdec0cb52aa230f2ba3
24.326087
89
0.728755
false
false
false
false
ubi-naist/SenStick
refs/heads/master
SenStickSDK/SenStickSDK/GyroSensorService.swift
mit
1
// // GyroSensorService.swift // SenStickSDK // // Created by AkihiroUehara on 2016/05/24. // Copyright © 2016年 AkihiroUehara. All rights reserved. // import Foundation import CoreMotion // ジャイロセンサーの範囲設定値。列挙側の値は、BLEでの設定値に合わせている。 public enum RotationRange : UInt16, CustomStringConvertible { case rotationRange250DPS = 0x00 case rotationRange500DPS = 0x01 case rotationRange1000DPS = 0x02 case rotationRange2000DPS = 0x03 public var description : String { switch self { case .rotationRange250DPS: return "250DPS" case .rotationRange500DPS: return "500DPS" case .rotationRange1000DPS: return "1000DPS" case .rotationRange2000DPS: return "2000DPS" } } } // ジャイロのデータ構造体 // 16ビット 符号付き数値。フルスケールは設定レンジ値による。250, 500, 1000, 2000 DPS。 struct RotationRawData { typealias T = Int16 var xRawValue : Int16 var yRawValue : Int16 var zRawValue : Int16 init(xRawValue:Int16, yRawValue:Int16, zRawValue:Int16) { self.xRawValue = xRawValue self.yRawValue = yRawValue self.zRawValue = zRawValue } // 物理センサーの1deg/sあたりのLBSの値 static func getLSBperDegS(_ range: RotationRange) -> Double { switch range { case .rotationRange250DPS: return (32768.0 / 250.0) case .rotationRange500DPS: return (32768.0 / 500.0) case .rotationRange1000DPS: return (32768.0 / 1000.0) case .rotationRange2000DPS: return (32768.0 / 2000.0) } } static func unpack(_ data: [Byte]) -> RotationRawData { let x = Int16.unpack(data[0..<2]) let y = Int16.unpack(data[2..<4]) let z = Int16.unpack(data[4..<6]) return RotationRawData(xRawValue: x!, yRawValue: y!, zRawValue: z!) } } extension CMRotationRate : SensorDataPackableType { public typealias RangeType = RotationRange public static func unpack(_ range:RotationRange, value: [UInt8]) -> CMRotationRate? { guard value.count >= 6 else { return nil } let rawData = RotationRawData.unpack(value) let lsbPerDeg = RotationRawData.getLSBperDegS(range) // FIXME 右手系/左手系などの座標変換など確認すること。 // deg/s なので rad/sに変換 let k = Double.pi / Double(180) //debugPrint("x:\(rawData.xRawValue), y:\(rawData.yRawValue), z: \(rawData.zRawValue), lsbPerDeg:\(lsbPerDeg)") return CMRotationRate(x: k * Double(rawData.xRawValue) / Double(lsbPerDeg), y: k * Double(rawData.yRawValue) / Double(lsbPerDeg), z: k * Double(rawData.zRawValue) / Double(lsbPerDeg)) } } // センサー各種のベースタイプ, Tはセンサデータ独自のデータ型, Sはサンプリングの型、 open class GyroSensorService: SenStickSensorService<CMRotationRate, RotationRange> { required public init?(device:SenStickDevice) { super.init(device: device, sensorType: SenStickSensorType.gyroSensor) } }
31664c4feab79b864333c6b792e2c607
29.694737
191
0.653635
false
false
false
false
younata/RSSClient
refs/heads/master
TethysKit/Services/ArticleService/ArticleCoordinator.swift
mit
1
import Result import CBGPromise public class ArticleCoordinator { private let localArticleService: ArticleService private let networkArticleService: () -> ArticleService init(localArticleService: ArticleService, networkArticleServiceProvider: @escaping () -> ArticleService) { self.localArticleService = localArticleService self.networkArticleService = networkArticleServiceProvider } private var markArticleSubscriptions: [MarkArticleCall: Subscription<Result<Article, TethysError>>] = [:] public func mark(article: Article, asRead read: Bool) -> Subscription<Result<Article, TethysError>> { let call = MarkArticleCall(articleId: article.identifier, read: read) if let subscription = self.markArticleSubscriptions[call], subscription.isFinished == false { return subscription } let publisher = Publisher<Result<Article, TethysError>>() self.markArticleSubscriptions[call] = publisher.subscription let networkFuture = self.networkArticleService().mark(article: article, asRead: read) self.localArticleService.mark(article: article, asRead: read).then { localResult in publisher.update(with: localResult) networkFuture.then { networkResult in if localResult.error != nil || networkResult.error != nil { publisher.update(with: networkResult) } publisher.finish() self.markArticleSubscriptions.removeValue(forKey: call) } } return publisher.subscription } public func remove(article: Article) -> Future<Result<Void, TethysError>> { return self.localArticleService.remove(article: article) } public func authors(of article: Article) -> String { return self.localArticleService.authors(of: article) } public func date(for article: Article) -> Date { return self.localArticleService.date(for: article) } public func estimatedReadingTime(of article: Article) -> TimeInterval { return self.localArticleService.estimatedReadingTime(of: article) } } private struct MarkArticleCall: Hashable { let articleId: String let read: Bool }
fd70102bc9aa5c4a274bba02d4842e41
39.196429
110
0.689916
false
false
false
false
zxwWei/SwfitZeng
refs/heads/master
XWWeibo接收数据/XWWeibo/Classes/Module(公共模型)/XWStatus.swift
apache-2.0
1
// // XWStatus.swift // XWWeibo // // Created by apple1 on 15/10/31. // Copyright © 2015年 ZXW. All rights reserved. // import UIKit import SDWebImage class XWSatus: NSObject { // 修改 Status 模型的 loadStatus方法,添加 since_id 和 max_id 参数 // ///加载大于since_id大的微博 // var since_id: Int? // // /// 加载小于或等于max_id的微博 // var max_id: Int? /// 微博创建时间 var created_at: String? /// 字符串型的微博ID var id: Int = 0 /// 微博信息内容 var text: String? /// 微博来源 var source: String? /// 微博的配图 此时是字典数组 需要将其转换成url数组 var pic_urls: [[String: AnyObject]]? { didSet{ // 当字典转模型的时候 将 pic_urls 转换成url赋给pictureUrlS数组 // 判断有没有图片 let count = pic_urls?.count ?? 0 if count == 0 { return } // 创建url数组 pictureUrlS = [NSURL]() /// 创建大图URL数组 largePictureUrls = [NSURL]() for dict in pic_urls! { // 当是这个字典的时候 if let urlStr = dict["thumbnail_pic"] as? String { // 拼接数组 pictureUrlS?.append(NSURL(string: urlStr)!) // 转成大图URL字符串 let largeUrlStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") // 拼接数组 largePictureUrls?.append(NSURL(string: largeUrlStr)!) } } } } /// 微博配图 url数组 var pictureUrlS: [NSURL]? /// 微博配图 返回的大图数组 var largePictureUrls: [NSURL]? /// 计算型属性 如果是转发的返回原创微博的图片 ,转发的返回转发的图片 var realPictureUrls: [NSURL]? { get { // 当模型里面没有 retweeted_status的属性的时候 返回模型原有的pictureUrlS return retweeted_status == nil ? pictureUrlS : retweeted_status!.pictureUrlS } } /// 发的返回原创微博的大图片 ,转发的返回转发的大图片 var realLargePictureUrls: [NSURL]?{ get { return retweeted_status == nil ? largePictureUrls : retweeted_status!.largePictureUrls } } /// 被转发微博 var retweeted_status: XWSatus? // 根据模型里面的retweeted_status来判断是原创微博还是转发微博 /// 返回微博cell对应的Identifier func cellID() -> String { // retweeted_status == nil表示原创微博 return retweeted_status == nil ? XWCellReuseIndentifier.ownCell.rawValue : XWCellReuseIndentifier.forWardCell.rawValue } /// 用户模型 var user: XWUser? /// 缓存行高 var rowHeight: CGFloat? /*-------------------------模型转换-----------------------------------*/ // MARK: - the dictionary transform to model init(dict: [String: AnyObject]){ super.init() setValuesForKeysWithDictionary(dict) } // KVC赋值每个属性的时候都会调用 因为status里面有这些字典 现在将他们转成模型 override func setValue(value: AnyObject?, forKey key: String) { // because the user is model // 判断user赋值时, 自己字典转模型 // print("key:\(key), value:\(value)") if key == "user" { // let the dictionnary which include the message of user into its class let it transform to dictionary itself if let dict = value as? [String: AnyObject] { // 字典转模型 // 赋值 user = XWUser(dict: dict) // 一定要记得return return } } // 将转发的微博转成模型 注意 {} 啊 else if key == "retweeted_status" { if let dict = value as? [String: AnyObject]{ // 将转发的微博转成模型 retweeted_status = XWSatus(dict: dict) } return } return super.setValue(value, forKey: key) } // MARK: - when some properties from netWork , but we did not has in this dictionary, must override func setValue(value: AnyObject?, forUndefinedKey key: String) {} // MARK: - the ouput override var description: String { // "access_token:\(access_token), expires_in:\(expires_in), uid:\(uid): expires_date:\(expires_date), name:\(name), avatar_large:\(avatar_large)" let p = ["created_at", "idStr", "text", "source", "pic_urls", "user"] // 数组里面的每个元素,找到对应的value,拼接成字典 // \n 换行, \t table since_id return "\n\t微博模型:\(dictionaryWithValuesForKeys(p))" } // MARK: - 加载微博信息 模型从网络处加载数据 该方法让控制器调用 class func loadTheBlogifnos(since_id: Int ,max_id: Int ,finished:(statuses: [XWSatus]? , error: NSError?)->()){ // let netWorkTool load the blogStatus // 从网络工具类处加载数据 XWNetworkTool.shareInstance.getblogInfo(since_id , max_id: max_id) { (result, error) -> () in if (error != nil){ finished(statuses: nil, error: error) return } // statuses result?["statuses"] // when status has value , we append it, then give to other [[String: AnyObject]] the array of dictionary if let array = result?["statuses"] as? [[String: AnyObject]]{ // 创建微博数组 var statues = [XWSatus]() for dict in array { statues.append(XWSatus(dict: dict)) } // 将图片缓存下来 cacheWedImage(statues, finised: finished) finished(statuses: statues, error: nil) } else{ finished(statuses: nil, error: nil) } } } // MARK: TODO: 缓存图片 class func cacheWedImage(status: [XWSatus]? , finised:(status: [XWSatus]? , error: NSError?) -> ()){ // 定义任务组 let group = dispatch_group_create() guard let statusList = status else { return } // 长度 var length = 0 // 遍历list数组里面的微博,获取到urlss数组 for status in statusList{ //获得url数组 guard let urls = status.realPictureUrls else { // 没有的时候继续遍历list中的status continue } // 根据遍历url数组来缓存图片 for url in urls { // 进入任务组 dispatch_group_enter(group) // 下载图片 SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error , _ , _ , _ ) -> Void in // 离开任务组 dispatch_group_leave(group) if (error != nil){ finised(status: nil, error: error) return } // 拼接长度 if let data = UIImagePNGRepresentation(image){ length += data.length } //print("长度:\(length / 1024)") })// 注意这个括号 } } // 出任务组 dispatch_group_notify( group, dispatch_get_main_queue() ) { () -> Void in finised(status: status, error: nil) } } }
7483156b9f0bd424e11624bd1e93cd92
27.336996
183
0.458764
false
false
false
false
DianQK/RxExample
refs/heads/master
RxZhihuDaily/Theme/ThemeViewController.swift
mit
1
// // ThemeViewController.swift // RxExample // // Created by 宋宋 on 16/2/16. // Copyright © 2016年 DianQK. All rights reserved. // import UIKit import RxSwift import RxCocoa import SWRevealViewController import Kingfisher class ThemeViewController: UITableViewController { var id: Int! let disposeBag = DisposeBag() let sections = Variable([NewsModel]()) let imageURL = Variable(NSURL()) override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = nil tableView.delegate = nil let revealController = self.revealViewController() view.addGestureRecognizer(revealController.tapGestureRecognizer()) view.addGestureRecognizer(revealController.panGestureRecognizer()) navigationController?.navigationBar.lt_backgroundColor = UIColor.clearColor() navigationController?.navigationBar.shadowImage = UIImage() let navImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, 64)) navImageView.contentMode = UIViewContentMode.ScaleAspectFill navImageView.clipsToBounds = true let headerView = ParallaxHeaderView.parallaxThemeHeaderViewWithSubView(navImageView, size: CGSizeMake(self.view.frame.width, 64), image: navImageView.image) tableView.tableHeaderView = headerView ZhihuDailyProvider.request(.Theme(id: id)) .mapObject(ThemeNewsListModel) .subscribeNext { [unowned self] in self.sections.value = $0.stories self.imageURL.value = NSURL(string: $0.image)! }.addDisposableTo(disposeBag) sections.asObservable().bindTo(tableView.rx_itemsWithCellIdentifier("\(ThemeNewCell.self)", cellType: ThemeNewCell.self)) { (row, element, cell) in cell.nameLabel.text = element.title if let imageStr = element.images?.first { cell.contentImageView.kf_setImageWithURL(NSURL(string: imageStr)!) cell.trailingLayoutConstraint.priority = 700 } else { cell.trailingLayoutConstraint.priority = 900 } }.addDisposableTo(disposeBag) // TODO: UPDATE CODE imageURL.asObservable().subscribeNext { navImageView.kf_setImageWithURL($0, placeholderImage: nil, optionsInfo: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in headerView.blurViewImage = image headerView.refreshBlurViewForNewsImage() }) }.addDisposableTo(disposeBag) tableView.rx_contentOffset.subscribeNext { [unowned self] in headerView.layoutThemeHeaderViewForScrollViewOffset($0) if self.tableView.contentOffset.y < -80 { self.tableView.contentOffset.y = -80 } }.addDisposableTo(disposeBag) } //设置StatusBar为白色 override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
1145e8279be3ea5a760e3e17bbe3a014
36.54878
164
0.654108
false
false
false
false
CulturaMobile/culturamobile-api
refs/heads/master
Sources/App/Models/EventGuestList.swift
mit
1
import Vapor import FluentProvider import AuthProvider import HTTP final class EventGuestList: Model { fileprivate static let databaseTableName = "event_guest_lists" static var entity = "event_guest_lists" let storage = Storage() static let idKey = "id" static let foreignIdKey = "event_guest_list_id" var user: Identifier? var event: Identifier? init(user: User, event: Event) { self.user = user.id self.event = event.id } // MARK: Row /// Initializes from the database row init(row: Row) throws { user = try row.get("user_id") event = try row.get("event_id") } // Serializes object to the database func makeRow() throws -> Row { var row = Row() try row.set("user_id", user) try row.set("event_id", event) return row } } // MARK: Preparation extension EventGuestList: Preparation { /// Prepares a table/collection in the database for storing objects static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.int("user_id") builder.int("event_id") } } /// Undoes what was done in `prepare` static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: JSON // How the model converts from / to JSON. // extension EventGuestList: JSONConvertible { convenience init(json: JSON) throws { try self.init( user: json.get("user_id"), event: json.get("event_id") ) id = try json.get("id") } func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id) let currentUser = try User.find(user)?.makeJSON() try json.set("user", currentUser) try json.set("event_id", event) return json } } // MARK: HTTP // This allows User models to be returned // directly in route closures extension EventGuestList: ResponseRepresentable { } extension EventGuestList: Timestampable { static var updatedAtKey: String { return "updated_at" } static var createdAtKey: String { return "created_at" } }
8927aa80a5f07a63bbad668679117a64
23.615385
71
0.60625
false
false
false
false
sihekuang/SKUIComponents
refs/heads/master
SKUIComponents/Classes/SKRoundedGradientFilledView.swift
mit
1
// // SKRoundedGradientFilledView.swift // SKUIComponents // // Created by Daniel Lee on 12/28/17. // import UIKit @IBDesignable open class SKRoundedGradientFilledView: SKRoundedFilledView{ @IBInspectable open var endColor: UIColor? @IBInspectable open var isGradientHorizontal: Bool = true override open func draw(_ rect: CGRect) { let startColor = self.fillColor ?? UIColor.white let endColor = self.endColor ?? startColor let radius = self.cornerRadius let bezierPath = SKUIHelper.drawRectGradient(rect: rect, startColor: startColor, endColor: endColor, cornerRadius: radius, isHorizontal: isGradientHorizontal) guard let path = bezierPath else {return} if showShadow{ SKUIHelper.drawShadow(view: self, bezierPath: path, cornerRadius: cornerRadius, shadowOffsetX: shadowOffsetX, shadowOffsetY: shadowOffsetY, shadowRadius: shadowRadius, color: outlineShadowColor) } } }
4285f2d124a3413d100987b704d841d5
31.483871
206
0.696127
false
false
false
false
letsspeak/Stock
refs/heads/master
Sources/Run/main.swift
mit
1
import App import XFPMiddleware /// We have isolated all of our App's logic into /// the App module because it makes our app /// more testable. /// /// In general, the executable portion of our App /// shouldn't include much more code than is presented /// here. /// /// We simply initialize our Droplet, optionally /// passing in values if necessary /// Then, we pass it to our App's setup function /// this should setup all the routes and special /// features of our app /// /// .run() runs the Droplet's commands, /// if no command is given, it will default to "serve" let config = try Config() try config.setup() let xfpMiddleware = XFPMiddleware() config.addConfigurable(middleware: xfpMiddleware, name: "xfp-middleware") let assetDirs = [ "js/", "styles/", "images/", ] let assetMiddleware = AssetMiddleware(assetDirs: assetDirs, publicDir: config.publicDir) config.addConfigurable(middleware: assetMiddleware, name: "asset-middleware") let drop = try Droplet(config) try drop.setup() try drop.run()
83e77f39df47ac146ce58c4b8a414da1
25.973684
88
0.72
false
true
false
false
GraphKit/MaterialKit
refs/heads/v1.x.x
Sources/iOS/Reminders/Reminders.swift
agpl-3.0
1
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import EventKit @objc(RemindersAuthorizationStatus) public enum RemindersAuthorizationStatus: Int { case authorized case denied } @objc(RemindersDelegate) public protocol RemindersDelegate { /** A delegation method that is executed when the Reminder status is updated. - Parameter reminders: A reference to the Reminder. - Parameter status: A reference to the ReminderAuthorizationStatus. */ @objc optional func reminders(reminders: Reminders, status: RemindersAuthorizationStatus) /** A delegation method that is executed when Reminders is authorized. - Parameter reminders: A reference to the Reminders. */ @objc optional func reminders(authorized reminders: Reminders) /** A delegation method that is executed when Reminders is denied. - Parameter reminders: A reference to the Reminders. */ @objc optional func reminders(denied reminders: Reminders) /** A delegation method that is executed when a new Reminders list is created - Parameter reminders: A reference to the Reminders. - Parameter list: A reference to the calendar created - Parameter created: A boolean describing if the operation succeeded or not. */ @objc optional func reminders(reminders: Reminders, list: EKCalendar, created: Bool) /** A delegation method that is executed when a new Reminders list is created - Parameter reminders: A reference to the Reminder. - Parameter list: A reference to the calendar created - Parameter deleted: A boolean describing if the operation succeeded or not. */ @objc optional func reminders(reminders: Reminders, list: EKCalendar, deleted: Bool) /** A delegation method that is executed when a new Reminders list is created - Parameter reminders: A reference to the Reminder. - Parameter created: A boolean describing if the operation succeeded or not. */ @objc optional func reminders(reminders: Reminders, created: Bool) /** A delegation method that is executed when a new Reminders list is created - Parameter reminders: A reference to the Reminder. - Parameter deleted: A boolean describing if the operation succeeded or not. */ @objc optional func reminders(reminders: Reminders, deleted: Bool) } @objc(Reminders) open class Reminders: NSObject { /// A reference to the eventStore. fileprivate let eventStore = EKEventStore() /// The current ReminderAuthorizationStatus. open var authorizationStatus: RemindersAuthorizationStatus { return .authorized == EKEventStore.authorizationStatus(for: .reminder) ? .authorized : .denied } /// A reference to a RemindersDelegate. open weak var delegate: RemindersDelegate? open func requestAuthorization(_ completion: ((RemindersAuthorizationStatus) -> Void)? = nil) { eventStore.requestAccess(to: .reminder) { [weak self, completion = completion] (permission, _) in DispatchQueue.main.async { [weak self, completion = completion] in guard let s = self else { return } if permission { s.delegate?.reminders?(reminders: s, status: .authorized) s.delegate?.reminders?(authorized: s) completion?(.authorized) } else { s.delegate?.reminders?(reminders: s, status: .denied) s.delegate?.reminders?(denied: s) completion?(.denied) } } } } } // List CRUD operations extension Reminders { /** A method for creating new Reminder lists - Parameter list title: the name of the list - Parameter completion: optional completion call back */ open func create(list title: String, completion: ((Bool, Error?) -> Void)? = nil) { DispatchQueue.global(qos: .default).async { [weak self, completion = completion] in guard let s = self else { return } let list = EKCalendar(for: .reminder, eventStore: s.eventStore) list.title = title for source in s.eventStore.sources { if .local == source.sourceType { list.source = source var created = false var error: Error? do { try s.eventStore.saveCalendar(list, commit: true) created = true } catch let e { error = e } DispatchQueue.main.async { [weak self, completion = completion] in guard let s = self else { return } s.delegate?.reminders?(reminders: s, list: list, created: created) completion?(created, error) } } } } } /** A method for deleting existing Reminder lists - Parameter list identifier: the name of the list - Parameter completion: optional completion call back */ open func delete(list identifier: String, completion: ((Bool, Error?) -> Void)? = nil) { DispatchQueue.global(qos: .default).async { [weak self, completion = completion] in guard let s = self else { return } guard let list = s.eventStore.calendar(withIdentifier: identifier) else { return } var deleted = false var error: Error? do { try s.eventStore.removeCalendar(list, commit: true) deleted = true } catch let e { error = e } DispatchQueue.main.async { [weak self, completion = completion] in guard let s = self else { return } s.delegate?.reminders?(reminders: s, list: list, deleted: deleted) completion?(deleted, error) } } } /** A method for retrieving reminder lists - Parameter completion: completion call back */ public func fetchLists(completion: ([EKCalendar]) -> Void) { completion(eventStore.calendars(for: .reminder)) } } // Reminder list CRUD operations extension Reminders { /** A method for retrieving reminders from an optionally existing list. if the list does not exist the reminders will be retrieved from the default reminders list - Parameter list: An optional EKCalendar. - Parameter completion: completion call back */ open func fetchReminders(list: EKCalendar, completion: @escaping ([EKReminder]) -> Void) { var lists = [EKCalendar]() lists.append(list) eventStore.fetchReminders(matching: eventStore.predicateForReminders(in: lists), completion: { [completion = completion] (reminders) in DispatchQueue.main.async { [completion = completion] in completion(reminders ?? []) } }) } // FIX ME: Should we use the calendar identifier here instead of the title for finding the right cal? /** A method for adding a new reminder to an optionally existing list. if the list does not exist it will be added to the default reminders list. - Parameter completion: optional completion call back */ open func create(title: String, dateComponents: DateComponents, in list: EKCalendar? = nil, completion: ((Error?) -> Void)? = nil) { var reminderCal = [EKCalendar]() if list != nil { fetchLists(completion: { (calendars) in for calendar in calendars { if calendar.title == list!.title { reminderCal.append(calendar) } } }) } let reminder = EKReminder(eventStore: eventStore) reminder.title = title reminder.dueDateComponents = dateComponents reminder.calendar = reminderCal.last! var created: Bool = false var error: Error? do { try eventStore.save(reminder, commit: true) created = true } catch let e { error = e } DispatchQueue.main.async { [weak self] in guard let s = self else { return } s.delegate?.reminders?(reminders: s, created: created) if let c = completion { c(error) } } } // FIX ME: Should we use the calendar identifier here instead of the title for finding the right cal? /** A method for adding a new reminder to an optionally existing list. if the list does not exist it will be added to the default reminders list. - Parameter completion: optional completion call back */ open func delete(reminder: EKReminder, completion: ((Error?) -> Void)? = nil) { var deleted: Bool = false var error: Error? do { try eventStore.remove(reminder, commit: true) deleted = true } catch let e { error = e } DispatchQueue.main.async { [weak self] in guard let s = self else { return } s.delegate?.reminders?(reminders: s, deleted: deleted) if let c = completion { c(error) } } } }
de1035114fd9b2564629cd4dd05265ca
36.619672
143
0.600924
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01066-swift-typebase-getcanonicaltype.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol b { struct e = e> () { class C) { } } class A<T -> { func x(seq: Int = Swift.Iterator.d(b<f == A<S { convenience init({ func a: T.f = """""""]() } } protocol a { func b> { } typealias d>(() -> String { func c, """ protocol A { }) protocol a { } typealias e : d = F>) } } var e(b
34952676cc9917dbcab90763b862ac5b
20.4375
79
0.658892
false
false
false
false
VBVMI/VerseByVerse-iOS
refs/heads/master
VBVMI/LessonTableViewCell.swift
mit
1
// // LessonTableViewCell.swift // VBVMI // // Created by Thomas Carey on 25/02/16. // Copyright © 2016 Tom Carey. All rights reserved. // import UIKit import FontAwesome_swift import ACPDownload extension ResourceManager.LessonType { func button(_ cell: LessonTableViewCell) -> ACPDownloadView { switch self { case .audio: return cell.audioView.button case .studentAid: return cell.studentAidView.button case .teacherAid: return cell.teacherAidView.button case .transcript: return cell.transcriptView.button case .video: return cell.videoView.button } } func view(_ cell: LessonTableViewCell) -> ResourceIconView { switch self { case .audio: return cell.audioView case .studentAid: return cell.studentAidView case .teacherAid: return cell.teacherAidView case .transcript: return cell.transcriptView case .video: return cell.videoView } } } class LessonTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var numberLabel: UILabel! @IBOutlet weak var progressIndicator: UIProgressView! @IBOutlet weak var descriptionLabel: UILabel! let videoView = ResourceIconView(frame: CGRect.zero) let teacherAidView = ResourceIconView(frame: CGRect.zero) let transcriptView = ResourceIconView(frame: CGRect.zero) let audioView = ResourceIconView(frame: CGRect.zero) let studentAidView = ResourceIconView(frame: CGRect.zero) @IBOutlet weak var resourcesStackView: UIStackView! fileprivate static let buttonFont = UIFont.fontAwesome(ofSize: 20) var urlButtonCallback: ((_ downloadView: ACPDownloadView, _ status: ACPDownloadStatus, _ buttonType: ResourceManager.LessonType) -> ())? let transcriptDownload = ACPDownloadView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) override func awakeFromNib() { super.awakeFromNib() // Initialization code resourcesStackView.addArrangedSubview(videoView) resourcesStackView.addArrangedSubview(teacherAidView) resourcesStackView.addArrangedSubview(studentAidView) resourcesStackView.addArrangedSubview(transcriptView) resourcesStackView.addArrangedSubview(audioView) videoView.isHidden = true teacherAidView.isHidden = true studentAidView.isHidden = true transcriptView.isHidden = true audioView.isHidden = true let buttonTintColor = StyleKit.darkGrey let videoImage = IconImages(string: String.fontAwesomeIcon(name: .youTubePlay)) videoImage.strokeColor = buttonTintColor videoView.button.setImages(videoImage) videoView.button.tintColor = buttonTintColor videoView.button.setActionForTap { [weak self] (view, status) -> Void in self?.urlButtonCallback?(view!, status, .video) } let videoTapGesture = UITapGestureRecognizer(target: self, action: #selector(LessonTableViewCell.videoTap(_:))) videoView.addGestureRecognizer(videoTapGesture) let teacherAidImage = IconImages(string: String.fontAwesomeIcon(name: .fileO)) teacherAidImage.strokeColor = buttonTintColor teacherAidView.button.setImages(teacherAidImage) teacherAidView.button.tintColor = buttonTintColor teacherAidView.button.setActionForTap { [weak self] (view, status) -> Void in self?.urlButtonCallback?(view!, status, .teacherAid) } let teacherAidGesture = UITapGestureRecognizer(target: self, action: #selector(LessonTableViewCell.teacherAidTap(_:))) teacherAidView.addGestureRecognizer(teacherAidGesture) let studentAidImage = IconImages(string: String.fontAwesomeIcon(name: .filePowerpointO)) studentAidImage.strokeColor = buttonTintColor studentAidView.button.setImages(studentAidImage) studentAidView.button.tintColor = buttonTintColor studentAidView.button.setActionForTap { [weak self] (view, status) -> Void in self?.urlButtonCallback?(view!, status, .studentAid) } let studentAidGesture = UITapGestureRecognizer(target: self, action: #selector(LessonTableViewCell.studentAidTap(_:))) studentAidView.addGestureRecognizer(studentAidGesture) let transcriptImage = IconImages(string: String.fontAwesomeIcon(name: .fileTextO)) transcriptImage.strokeColor = buttonTintColor transcriptView.button.setImages(transcriptImage) transcriptView.button.tintColor = buttonTintColor transcriptView.button.setActionForTap { [weak self] (view, status) -> Void in self?.urlButtonCallback?(view!, status, .transcript) } let transcriptGesture = UITapGestureRecognizer(target: self, action: #selector(LessonTableViewCell.transcriptTap(_:))) transcriptView.addGestureRecognizer(transcriptGesture) let audioImage = IconImages(string: String.fontAwesomeIcon(name: .play)) audioImage.strokeColor = buttonTintColor audioView.button.setImages(audioImage) audioView.button.tintColor = buttonTintColor audioView.button.setActionForTap { [weak self] (view, status) -> Void in self?.urlButtonCallback?(view!, status, .audio) } let audioGesture = UITapGestureRecognizer(target: self, action: #selector(LessonTableViewCell.audioTap(_:))) audioView.addGestureRecognizer(audioGesture) descriptionLabel.textColor = StyleKit.midGrey timeLabel.textColor = StyleKit.midGrey progressIndicator.progressTintColor = StyleKit.lightGrey.withAlpha(0.2) progressIndicator.progress = 0 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func audioTap(_ sender: AnyObject) { //audioButton.handleSingleTap urlButtonCallback?(audioView.button, audioView.button.currentStatus, .audio) } @IBAction func transcriptTap(_ sender: AnyObject) { urlButtonCallback?(transcriptView.button, transcriptView.button.currentStatus, .transcript) } @IBAction func studentAidTap(_ sender: AnyObject) { urlButtonCallback?(studentAidView.button, studentAidView.button.currentStatus, .studentAid) } @IBAction func teacherAidTap(_ sender: AnyObject) { urlButtonCallback?(teacherAidView.button, teacherAidView.button.currentStatus, .teacherAid) } @IBAction func videoTap(_ sender: AnyObject) { urlButtonCallback?(videoView.button, videoView.button.currentStatus, .video) } override func prepareForReuse() { super.prepareForReuse() videoView.isHidden = true teacherAidView.isHidden = true studentAidView.isHidden = true transcriptView.isHidden = true audioView.isHidden = true } }
c4cdb816d3808aee226fbc3e05450c1a
39.780899
140
0.688387
false
false
false
false
achimk/Cars
refs/heads/master
CarsApp/Repositories/Cars/Formatters/CarManufactureFormatter.swift
mit
1
// // CarManufactureFormatter.swift // CarsApp // // Created by Joachim Kret on 29/07/2017. // Copyright © 2017 Joachim Kret. All rights reserved. // import Foundation struct CarManufactureFormatter { static var yearFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "YYYY" return formatter }() static var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "YYYY-MM-dd HH:mm:ss zzz" return formatter }() }
ab0518e98e840937f67098c76c0aa048
21.833333
56
0.656934
false
false
false
false
jfosterdavis/Charles
refs/heads/develop
Charles/Clue.swift
apache-2.0
1
// // Clue.swift // Charles // // Created by Jacob Foster Davis on 6/16/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit /******************************************************/ /*******************///MARK: Data needed to present the user with a clue on how to play this flipping game. /******************************************************/ class Clue: NSObject { var clueTitle: String var part1: String? var part1Image: UIImage? var part2: String? var part2Image: UIImage? var part3: String? var part3Image: UIImage? // MARK: Initializers init(clueTitle: String, part1: String? = nil, part1Image: UIImage? = nil, part2: String? = nil, part2Image: UIImage? = nil, part3: String? = nil, part3Image: UIImage? = nil ) { self.clueTitle = clueTitle self.part1 = part1 self.part1Image = part1Image self.part2 = part2 self.part2Image = part2Image self.part3 = part3 self.part3Image = part3Image super.init() } }
53c9fbfa8a098285a8a54ae7d2806834
21.882353
107
0.513282
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
refs/heads/master
HTWDresden/HTWDresden/Detail/MealDetailViewController.swift
gpl-2.0
1
import UIKit import Kingfisher class MealDetailViewController: UIViewController { var tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() tableView.frame = view.bounds tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] tableView.delegate = self tableView.dataSource = self tableView.registerClass(MealDetailViewCell.self, forCellReuseIdentifier: "cell") view.addSubview(tableView) } } extension MealDetailViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) } }
a0b17f823214fdf46ca9f4cb0705915b
27.37931
106
0.798054
false
false
false
false
awsdocs/aws-doc-sdk-examples
refs/heads/main
swift/example_code/s3/basics/Sources/ServiceHandler/ServiceHandler.swift
apache-2.0
1
/* A class containing functions that interact with AWS services. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ // snippet-start:[s3.swift.basics.handler] // snippet-start:[s3.swift.basics.handler.imports] import Foundation import AWSS3 import ClientRuntime import AWSClientRuntime // snippet-end:[s3.swift.basics.handler.imports] /// A class containing all the code that interacts with the AWS SDK for Swift. public class ServiceHandler { let client: S3Client /// Initialize and return a new ``ServiceHandler`` object, which is used to drive the AWS calls /// used for the example. /// /// - Returns: A new ``ServiceHandler`` object, ready to be called to /// execute AWS operations. // snippet-start:[s3.swift.basics.handler.init] public init() async { do { client = try await S3Client() } catch { print("ERROR: ", dump(error, name: "Initializing s3 client")) exit(1) } } // snippet-end:[s3.swift.basics.handler.init] /// Create a new user given the specified name. /// /// - Parameters: /// - name: Name of the bucket to create. /// Throws an exception if an error occurs. // snippet-start:[s3.swift.basics.handler.createbucket] public func createBucket(name: String) async throws { let config = S3ClientTypes.CreateBucketConfiguration( locationConstraint: .usEast2 ) let input = CreateBucketInput( bucket: name, createBucketConfiguration: config ) _ = try await client.createBucket(input: input) } // snippet-end:[s3.swift.basics.handler.createbucket] /// Delete a bucket. /// - Parameter name: Name of the bucket to delete. // snippet-start:[s3.swift.basics.handler.deletebucket] public func deleteBucket(name: String) async throws { let input = DeleteBucketInput( bucket: name ) _ = try await client.deleteBucket(input: input) } // snippet-end:[s3.swift.basics.handler.deletebucket] /// Upload a file from local storage to the bucket. /// - Parameters: /// - bucket: Name of the bucket to upload the file to. /// - key: Name of the file to create. /// - file: Path name of the file to upload. // snippet-start:[s3.swift.basics.handler.uploadfile] public func uploadFile(bucket: String, key: String, file: String) async throws { let fileUrl = URL(fileURLWithPath: file) let fileData = try Data(contentsOf: fileUrl) let dataStream = ByteStream.from(data: fileData) let input = PutObjectInput( body: dataStream, bucket: bucket, key: key ) _ = try await client.putObject(input: input) } // snippet-end:[s3.swift.basics.handler.uploadfile] /// Create a file in the specified bucket with the given name. The new /// file's contents are uploaded from a `Data` object. /// /// - Parameters: /// - bucket: Name of the bucket to create a file in. /// - key: Name of the file to create. /// - data: A `Data` object to write into the new file. // snippet-start:[s3.swift.basics.handler.createfile] public func createFile(bucket: String, key: String, withData data: Data) async throws { let dataStream = ByteStream.from(data: data) let input = PutObjectInput( body: dataStream, bucket: bucket, key: key ) _ = try await client.putObject(input: input) } // snippet-end:[s3.swift.basics.handler.createfile] /// Download the named file to the given directory on the local device. /// /// - Parameters: /// - bucket: Name of the bucket that contains the file to be copied. /// - key: The name of the file to copy from the bucket. /// - to: The path of the directory on the local device where you want to /// download the file. // snippet-start:[s3.swift.basics.handler.downloadfile] public func downloadFile(bucket: String, key: String, to: String) async throws { let fileUrl = URL(fileURLWithPath: to).appendingPathComponent(key) let input = GetObjectInput( bucket: bucket, key: key ) let output = try await client.getObject(input: input) // Get the data stream object. Return immediately if there isn't one. guard let body = output.body else { return } let data = body.toBytes().toData() try data.write(to: fileUrl) } // snippet-end:[s3.swift.basics.handler.downloadfile] /// Read the specified file from the given S3 bucket into a Swift /// `Data` object. /// /// - Parameters: /// - bucket: Name of the bucket containing the file to read. /// - key: Name of the file within the bucket to read. /// /// - Returns: A `Data` object containing the complete file data. // snippet-start:[s3.swift.basics.handler.readfile] public func readFile(bucket: String, key: String) async throws -> Data { let input = GetObjectInput( bucket: bucket, key: key ) let output = try await client.getObject(input: input) // Get the stream and return its contents in a `Data` object. If // there is no stream, return an empty `Data` object instead. guard let body = output.body else { return "".data(using: .utf8)! } let data = body.toBytes().toData() return data } // snippet-end:[s3.swift.basics.handler.readfile] /// Copy a file from one bucket to another. /// /// - Parameters: /// - sourceBucket: Name of the bucket containing the source file. /// - name: Name of the source file. /// - destBucket: Name of the bucket to copy the file into. // snippet-start:[s3.swift.basics.handler.copyfile] public func copyFile(from sourceBucket: String, name: String, to destBucket: String) async throws { let srcUrl = ("\(sourceBucket)/\(name)").addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) let input = CopyObjectInput( bucket: destBucket, copySource: srcUrl, key: name ) _ = try await client.copyObject(input: input) } // snippet-end:[s3.swift.basics.handler.copyfile] /// Deletes the specified file from Amazon S3. /// /// - Parameters: /// - bucket: Name of the bucket containing the file to delete. /// - key: Name of the file to delete. /// // snippet-start:[s3.swift.basics.handler.deletefile] public func deleteFile(bucket: String, key: String) async throws { let input = DeleteObjectInput( bucket: bucket, key: key ) do { _ = try await client.deleteObject(input: input) } catch { throw error } } // snippet-end:[s3.swift.basics.handler.deletefile] /// Returns an array of strings, each naming one file in the /// specified bucket. /// /// - Parameter bucket: Name of the bucket to get a file listing for. /// - Returns: An array of `String` objects, each giving the name of /// one file contained in the bucket. // snippet-start:[s3.swift.basics.handler.listbucketfiles] public func listBucketFiles(bucket: String) async throws -> [String] { let input = ListObjectsV2Input( bucket: bucket ) let output = try await client.listObjectsV2(input: input) var names: [String] = [] guard let objList = output.contents else { return [] } for obj in objList { if let objName = obj.key { names.append(objName) } } return names } // snippet-end:[s3.swift.basics.handler.listbucketfiles] } // snippet-end:[s3.swift.basics.handler]
337629d961be791e2c1ee9afbe0c04e6
34.937778
110
0.611874
false
false
false
false
aioriash/ASHInfiteScrollTableViewController
refs/heads/master
Example/Example/ViewController.swift
mit
1
// // ViewController.swift // Example // // Created by Gustavo B Tagliari on 09/03/17. // Copyright © 2017 AIORIA SOFTWARE HOUSE. All rights reserved. // import UIKit class ViewController: LoadMoreTableViewController { // MARK: - Models var models = [String]() { didSet { debugPrint("newModels: \(models)") } } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = models[indexPath.row] return cell } } // MARK: - LoadMoreDelegate extension ViewController { override var records: [Any] { get { return self.models } set { if let models = newValue as? [String] { self.models = models } } } override func fetchDataFromWS(withOffset offset: Int, andLimit limit: Int, completionBlock completion: @escaping ([Any]?, Error?) -> Void) { var strings = [String]() for i in offset ..< (offset+limit) { strings.append("Line \(i)") } completion(strings, nil) } }
c1b93bd27103eafe9c2f7628bc72f87d
24.490196
144
0.580769
false
false
false
false
ibari/StationToStation
refs/heads/master
StationToStation/DataStoreClient.swift
gpl-2.0
1
// // DataStoreClient.swift // StationToStation // // Created by Benjamin Tsai on 6/6/15. // Copyright (c) 2015 Ian Bari. All rights reserved. // import UIKit class DataStoreClient { func onApplicationLaunch() { let applicationId = Utils.sharedInstance.getSecret("parse_application_id") let clientKey = Utils.sharedInstance.getSecret("parse_client_key") Parse.setApplicationId(applicationId, clientKey: clientKey) } class var sharedInstance: DataStoreClient { struct Static { static let instance = DataStoreClient() } return Static.instance } // MARK: - Station private static let station_ClassName = "Station" private static let station_ObjectId = "objectId" private static let station_OwnerKey = "owner_key" private static let station_PlaylistKey = "playlist_key" private static let station_Name = "name" private static let station_Description = "description" private static let station_ImageFile = "imageFile" private static let station_PlaylistMeta = "playlist_meta" func getAllStations(completion: (stations: [Station]?, error: NSError?) -> Void) { getCollaboratingStations(completion) } class func loadAll(completion: (stations: [Station]?, error: NSError?) -> Void) { DataStoreClient.sharedInstance.getAllStations(completion) } func getStations(completion: (stations: [Station]?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.station_ClassName) query.whereKey(DataStoreClient.station_OwnerKey, equalTo: User.currentUser!.key) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(stations: nil, error: error) return } if let objects = objects as? [PFObject] { var stations = [Station]() for obj in objects { stations.append(self.pfoToStation(obj)) } self.loadStationProperties(stations, completion: completion) } else { completion(stations: [], error: nil) return } } } func getStations(ids: [String], completion: (stations: [Station]?, error: NSError?) -> Void) { NSLog("getStations \(ids)") var query: PFQuery = PFQuery(className: DataStoreClient.station_ClassName) query.whereKey("objectId", containedIn: ids) query.findObjectsInBackgroundWithBlock { (objs: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(stations: nil, error: error) return } var stations = [Station]() for obj in objs! { stations.append(self.pfoToStation(obj as! PFObject)) } self.loadStationProperties(stations, completion: completion) } } func getInvitedStations(completion: (stations: [Station]?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.invite_ClassName) query.whereKey(DataStoreClient.invite_toUserKey, equalTo: User.currentUser!.key) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(stations: nil, error: error) return } if let objects = objects as? [PFObject] { var stationIds = [String]() for obj in objects { stationIds.append(obj[DataStoreClient.invite_stationObjectId] as! String) } self.getStations(stationIds, completion: completion) return } else { completion(stations: [], error: nil) return } } } func getCollaboratingStations(completion: (stations: [Station]?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName) query.whereKey(DataStoreClient.collaborator_userKey, equalTo: User.currentUser!.key) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(stations: nil, error: error) return } if let objects = objects as? [PFObject] { var stationIds = [String]() for obj in objects { stationIds.append(obj[DataStoreClient.collaborator_stationObjectId] as! String) } self.getStations(stationIds, completion: completion) return } else { completion(stations: [], error: nil) return } } } func getStation(objectId: String, completion: (station: Station?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.station_ClassName) query.getObjectInBackgroundWithId(objectId) { (obj: PFObject?, error: NSError?) -> Void in if error == nil && obj != nil { let stationObj = self.pfoToStation(obj!) self.loadStationProperties([stationObj]) { (stations, error) in var station = stations?.first completion(station: station, error: error) } } else { completion(station: nil, error: error) } } } func handleOnComplete(stations: [Station], collabCount: Int, playlistCount: Int, commentsCount: Int, completion: (stations: [Station]?, error: NSError?) -> Void) { if stations.count == collabCount && stations.count == playlistCount && stations.count == commentsCount { completion(stations: stations, error: nil) } } func loadStationProperties(stations: [Station], completion: (stations: [Station]?, error: NSError?) -> Void) { var loadedStationCollaboratorCount = 0 var loadedStationPlaylistCount = 0 var loadedStationCommentsCount = 0 for station in stations { getCollaborators(station, completion: { (users, error) -> Void in if let error = error { NSLog("Error while loading collaborators in loadStationProperties: \(error)") return } station.collaborators = users loadedStationCollaboratorCount += 1 self.handleOnComplete(stations, collabCount: loadedStationCollaboratorCount, playlistCount: loadedStationPlaylistCount, commentsCount: loadedStationCommentsCount, completion: completion) }) getStationComments(station.objectId!, completion: { (comments, error) -> Void in if let error = error { NSLog("Error while loading comments for station in loadStationProperties: \(error)") return } station.comments = comments loadedStationCommentsCount += 1 self.handleOnComplete(stations, collabCount: loadedStationCollaboratorCount, playlistCount: loadedStationPlaylistCount, commentsCount: loadedStationCommentsCount, completion: completion) }) RdioClient.sharedInstance.getPlaylist(station.playlistKey, withMeta: station.playlistMeta, completion: { (playlist: Playlist?, error: NSError?) in if let error = error { NSLog("Error while loading playlist in loadStationProperties: \(error)") return } station.playlist = playlist loadedStationPlaylistCount += 1 self.handleOnComplete(stations, collabCount: loadedStationCollaboratorCount, playlistCount: loadedStationPlaylistCount, commentsCount: loadedStationCommentsCount, completion: completion) }) } } func saveStation(station: Station, completion: (success: Bool, error: NSError?) -> Void) { if let objectId = station.objectId { // Update let pfo = stationToPfo(station) pfo.objectId = objectId pfo.saveInBackgroundWithBlock(completion) } else { // Create let pfo = stationToPfo(station) pfo.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in station.objectId = pfo.objectId completion(success: success, error: error) }) } } func pfoToStation(obj: PFObject) -> Station { var image: UIImage? /*if let imageData = obj[DataStoreClient.station_ImageFile] as? NSData { image = UIImage(data: imageData) }*/ let station = Station( ownerKey: obj[DataStoreClient.station_OwnerKey] as! String, playlistKey: obj[DataStoreClient.station_PlaylistKey] as! String, name: obj[DataStoreClient.station_Name] as! String, description: obj[DataStoreClient.station_Description] as! String, image: image, playlistMetaDict: obj[DataStoreClient.station_PlaylistMeta] as? [String: AnyObject] ) station.objectId = obj.objectId! if let imageFile = obj[DataStoreClient.station_ImageFile] as? PFFile { station.imageUrl = imageFile.url! } return station } func stationToPfo(station: Station) -> PFObject { var obj = PFObject(className: DataStoreClient.station_ClassName) if let image = station.image { let imageData = UIImageJPEGRepresentation(image, 0.7) let imageFile = PFFile(name: "header-image.jpg", data: imageData) obj[DataStoreClient.station_ImageFile] = imageFile } obj[DataStoreClient.station_OwnerKey] = station.ownerKey obj[DataStoreClient.station_Name] = station.name obj[DataStoreClient.station_Description] = station.description obj[DataStoreClient.station_PlaylistKey] = station.playlistKey obj[DataStoreClient.station_PlaylistMeta] = station.playlistMeta.getData() return obj } // MARK: - Invite private static let invite_ClassName = "Invite" private static let invite_fromUserKey = "fromUserKey" private static let invite_toUserKey = "toUserkey" private static let invite_stationObjectId = "stationObjectId" private static let invite_accepted = "accepted" func getInvites(completion: (invites: [Invite]?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.invite_ClassName) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(invites: nil, error: error) return } if let objects = objects as? [PFObject] { var invites = [Invite]() for obj in objects { invites.append(self.pfoToInvite(obj)) } completion(invites: invites, error: nil) } else { completion(invites: [], error: nil) return } } } func saveInvite(invite: Invite, completion: (success: Bool, error: NSError?) -> Void) { inviteToPfo(invite).saveInBackgroundWithBlock(completion) } func pfoToInvite(obj: PFObject) -> Invite { return Invite( fromUserKey: obj[DataStoreClient.invite_fromUserKey] as! String, toUserKey: obj[DataStoreClient.invite_toUserKey] as! String, stationObjectId: obj[DataStoreClient.invite_stationObjectId] as! String, accepted: obj[DataStoreClient.invite_accepted] as! Bool ) } func inviteToPfo(invite: Invite) -> PFObject { var obj = PFObject(className: DataStoreClient.invite_ClassName) obj[DataStoreClient.invite_fromUserKey] = invite.fromUserKey obj[DataStoreClient.invite_toUserKey] = invite.toUserKey obj[DataStoreClient.invite_stationObjectId] = invite.stationObjectId obj[DataStoreClient.invite_accepted] = invite.accepted return obj } // MARK: - Collaborator private static let collaborator_ClassName = "Collaborator" private static let collaborator_objectId = "objectId" private static let collaborator_userKey = "userKey" private static let collaborator_stationObjectId = "stationObjectId" func getCollaborators(station: Station, completion: (users: [User]?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName) query.whereKey(DataStoreClient.collaborator_stationObjectId, equalTo: station.objectId!) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(users: nil, error: error) return } if let objects = objects as? [PFObject] { var userKeys = [String]() for obj in objects { userKeys.append(obj[DataStoreClient.collaborator_userKey] as! String) } RdioClient.sharedInstance.getUsers(userKeys, completion: completion) return } else { completion(users: [], error: nil) return } } } func saveCollaborator(collaborator: User, station: Station, completion: (success: Bool, error: NSError?) -> Void) { collaboratorToPfo(collaborator, station: station).saveInBackgroundWithBlock(completion) } func deleteCollaborator(collaborator: User, station: Station, completion: (success: Bool, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName) query.whereKey(DataStoreClient.collaborator_userKey, equalTo: collaborator.key) query.whereKey(DataStoreClient.collaborator_stationObjectId, equalTo: station.objectId!) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(success: false, error: error) return } if let objects = objects as? [PFObject] { for obj in objects { obj.deleteInBackgroundWithBlock(completion) } } else { completion(success: false, error: nil) return } } } func collaboratorToPfo(collaborator: User, station: Station) -> PFObject { var obj = PFObject(className: DataStoreClient.collaborator_ClassName) obj[DataStoreClient.collaborator_userKey] = collaborator.key obj[DataStoreClient.collaborator_stationObjectId] = station.objectId return obj } func isCollaborator(user: User, station: Station, completion: (collaborator: Bool?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName) query.whereKey(DataStoreClient.collaborator_userKey, equalTo: user.key) query.whereKey(DataStoreClient.collaborator_stationObjectId, equalTo: station.objectId!) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(collaborator: nil, error: error) return } if let objects = objects as? [PFObject] { var collaborators = [String]() for obj in objects { collaborators.append(obj[DataStoreClient.collaborator_userKey] as! String) } let collaborator = (collaborators.first != nil) ? true : false completion(collaborator: collaborator, error: nil) return } else { completion(collaborator: false, error: nil) return } } } // MARK: - Comment private static let comment_ClassName = "Comment" private static let comment_stationObjectId = "stationObjectId" private static let comment_trackKey = "trackKey" private static let comment_userKey = "userKey" private static let comment_text = "text" func getTrackComments(trackKey: String, completion: (comments: [Comment]?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.comment_ClassName) query.whereKey(DataStoreClient.comment_trackKey, equalTo: trackKey) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(comments: nil, error: error) return } if let objects = objects as? [PFObject] { var comments = [Comment]() for obj in objects { comments.append(self.pfoToComment(obj)) } self.loadCommentProperties(comments, completion: completion) } else { completion(comments: [], error: nil) return } } } func getStationComments(objectId: String, completion: (comments: [Comment]?, error: NSError?) -> Void) { var query: PFQuery = PFQuery(className: DataStoreClient.comment_ClassName) query.whereKey(DataStoreClient.comment_stationObjectId, equalTo: objectId) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if let error = error { completion(comments: nil, error: error) return } if let objects = objects as? [PFObject] { var comments = [Comment]() for obj in objects { comments.append(self.pfoToComment(obj)) } self.loadCommentProperties(comments, completion: completion) } else { completion(comments: [], error: nil) return } } } func loadCommentProperties(comments: [Comment], completion: (comments: [Comment]?, error: NSError?) -> Void) { var loadedCommentUserCount = 0 if comments.count == 0 { completion(comments: comments, error: nil) return } var userToComments = [String: [Comment]]() for comment in comments { if userToComments[comment.userKey!] == nil { userToComments[comment.userKey!] = [Comment]() } userToComments[comment.userKey!]!.append(comment) } var loadedUserCount = 0 for userKey in userToComments.keys { RdioClient.sharedInstance.getUser(userKey, completion: { (user, error) -> Void in if let error = error { NSLog("Error while loading user \(userKey) in loadCommentProperties: \(error)") return } NSLog("Loaded user \(userKey) for comments \(userToComments[userKey])") loadedUserCount += 1 for comment in userToComments[userKey]! { comment.user = user! } if userToComments.count == loadedUserCount { completion(comments: comments, error: nil) } }) } } func saveComment(comment: Comment, completion: (success: Bool, error: NSError?) -> Void) { commentToPfo(comment).saveInBackgroundWithBlock(completion) } func pfoToComment(obj: PFObject) -> Comment { return Comment( stationObjectId: obj[DataStoreClient.comment_stationObjectId] as! String, trackKey: obj[DataStoreClient.comment_trackKey] as! String, userKey: obj[DataStoreClient.comment_userKey] as! String, text: obj[DataStoreClient.comment_text] as! String ) } func commentToPfo(comment: Comment) -> PFObject { var obj = PFObject(className: DataStoreClient.comment_ClassName) obj[DataStoreClient.comment_stationObjectId] = comment.stationObjectId obj[DataStoreClient.comment_trackKey] = comment.trackKey obj[DataStoreClient.comment_userKey] = comment.userKey obj[DataStoreClient.comment_text] = comment.text return obj } }
4f706f32b644e130bc40f263550cb814
39.977143
202
0.585367
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
refs/heads/master
Playground Collection/Part 7 - Alien Adventure 4/MapAndReduce/MapAndReduce.playground/Pages/ReduceExample_ArrayMaxOrMin.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) //: ## Reduce() //: //: ### Example: Find an array's max or min import Foundation // Find the maximum number in an array let numbers = [7, 89, 48, 20, 38, 89, 29] let highestNumber = numbers.reduce(0, {(currentMax, number) -> Int in return max(currentMax, number) }) // Written in shorthand let maxNumber = numbers.reduce(0, { max($0, $1) }) // And with a trailing closure let maximum = numbers.reduce(0) { max($0, $1) } // Find the minimum of an array of words let words = ["zombify", "zip","zoology", "zest","zone", "zebra"] let firstAlphabeticalWord = words.reduce("zzz", {(currentMin, word) -> String in min(currentMin, word) }) print(firstAlphabeticalWord) // Alphabetical minimum in shorthand let alphabeticalMin = words.reduce("zzz", { min($0,$1) }) // And with a trailing closure let minimumWord = words.reduce("zzz") { min($0,$1) } //: [Next](@next)
d6364e150d080f66411253917f722ad1
21.9
80
0.650655
false
false
false
false
exevil/Keys-For-Sketch
refs/heads/master
Source/Update/FileObserver.swift
mit
1
// // FileObserver.swift // KeysForSketch // // Created by Vyacheslav Dubovitsky on 29/06/2017. // Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved. // // FileObserver observes changes made in plugin file. If user or Sketch modifying it (on update or reinstall, for instance) an alert asking to Restart Sketch should appear. public class FileObserver: NSObject { @objc public static let shared = FileObserver() /// https://github.com/soh335/FileWatch var fileWatch: FileWatch? @objc public func startObserving() { fileWatch = try! FileWatch(paths: [Keys.pluginPath], createFlag: [.UseCFTypes, .FileEvents], runLoop: RunLoop.current, latency: 0.5, eventHandler: { event in inDebug { print(""" \(event.path) == pluginURL: \(event.path == Keys.pluginPath) .ItemCreated: \(event.flag.contains(.ItemCreated)) .ItemRemoved: \(event.flag.contains(.ItemRemoved)) .ItemInodeMetaMod: \(event.flag.contains(.ItemInodeMetaMod)) .ItemRenamed: \(event.flag.contains(.ItemRenamed)) .ItemModified: \(event.flag.contains(.ItemModified)) .ItemFinderInfoMod: \(event.flag.contains(.ItemFinderInfoMod)) .ItemChangeOwner: \(event.flag.contains(.ItemChangeOwner)) .ItemXattrMod: \(event.flag.contains(.ItemXattrMod)) """) } if event.flag.contains(.ItemModified) // Manual Plugin Installation || event.path == Keys.pluginPath && event.flag.contains(.ItemRenamed) // Automatic update by Sketch { // Most of changes should appear through latency period but to make sure that all files passed, delay displaying of update alert until all files will be copied. self.cancelPreviousPerformRequiestsAndPerform(#selector(self.fileChanged), with: nil, afterDelay: 0.75) } }) } @objc func fileChanged() { let alert = UpdateCompletionAlert() alert.completionHandler(with: alert.runModal()) } } extension NSObject { /// Cancel previous perform requests with given arguments for object and register new one /// - note: Useful when you need to run a selector after a bunch of repetitive actions. Each action should cancel previous perform request and register a new delayed request afterwards. Selector will perform after the last action registers its perform request and its delay time will expire. func cancelPreviousPerformRequiestsAndPerform(_ aSelector: Selector, with anArgument: Any?, afterDelay delay: TimeInterval) { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: aSelector, object: anArgument) self.perform(aSelector, with: anArgument, afterDelay: delay) } }
46646abb2d62132003340b380ef344b4
57.046154
295
0.508084
false
false
false
false
QueryKit/QueryKit
refs/heads/master
Sources/QueryKit/Attribute.swift
bsd-2-clause
1
import Foundation /// An attribute, representing an attribute on a model public struct Attribute<AttributeType> : Equatable { public let key:String public init(_ key:String) { self.key = key } /// Builds a compound attribute with other key paths public init(attributes:[String]) { self.init(attributes.joined(separator: ".")) } /// Returns an expression for the attribute public var expression:NSExpression { return NSExpression(forKeyPath: key) } // MARK: Sorting /// Returns an ascending sort descriptor for the attribute public func ascending() -> NSSortDescriptor { return NSSortDescriptor(key: key, ascending: true) } /// Returns a descending sort descriptor for the attribute public func descending() -> NSSortDescriptor { return NSSortDescriptor(key: key, ascending: false) } func expressionForValue(_ value:AttributeType?) -> NSExpression { if let value = value { if let value = value as? NSObject { return NSExpression(forConstantValue: value as NSObject) } if MemoryLayout<AttributeType>.size == MemoryLayout<uintptr_t>.size { let value = unsafeBitCast(value, to: Optional<NSObject>.self) if let value = value { return NSExpression(forConstantValue: value) } } return NSExpression(forConstantValue: value) } return NSExpression(forConstantValue: NSNull()) } /// Builds a compound attribute by the current attribute with the given attribute public func attribute<T>(_ attribute:Attribute<T>) -> Attribute<T> { return Attribute<T>(attributes: [key, attribute.key]) } } /// Returns true if two attributes have the same name public func == <AttributeType>(lhs: Attribute<AttributeType>, rhs: Attribute<AttributeType>) -> Bool { return lhs.key == rhs.key } public func == <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression == left.expressionForValue(right) } public func != <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression != left.expressionForValue(right) } public func > <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression > left.expressionForValue(right) } public func >= <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression >= left.expressionForValue(right) } public func < <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression < left.expressionForValue(right) } public func <= <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression <= left.expressionForValue(right) } public func ~= <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression ~= left.expressionForValue(right) } public func << <AttributeType>(left: Attribute<AttributeType>, right: [AttributeType]) -> NSPredicate { let value = right.map { value in return value as! NSObject } return left.expression << NSExpression(forConstantValue: value) } public func << <AttributeType>(left: Attribute<AttributeType>, right: Range<AttributeType>) -> NSPredicate { let value = [right.lowerBound as! NSObject, right.upperBound as! NSObject] as NSArray let rightExpression = NSExpression(forConstantValue: value) return NSComparisonPredicate(leftExpression: left.expression, rightExpression: rightExpression, modifier: NSComparisonPredicate.Modifier.direct, type: NSComparisonPredicate.Operator.between, options: NSComparisonPredicate.Options(rawValue: 0)) } /// MARK: Bool Attributes prefix public func ! (left: Attribute<Bool>) -> NSPredicate { return left == false } public extension QuerySet { func filter(_ attribute:Attribute<Bool>) -> QuerySet<ModelType> { return filter((attribute == true) as NSPredicate) } func exclude(_ attribute:Attribute<Bool>) -> QuerySet<ModelType> { return filter((attribute == false) as NSPredicate) } } // MARK: Collections public func count(_ attribute:Attribute<NSSet>) -> Attribute<Int> { return Attribute<Int>(attributes: [attribute.key, "@count"]) } public func count(_ attribute:Attribute<NSOrderedSet>) -> Attribute<Int> { return Attribute<Int>(attributes: [attribute.key, "@count"]) }
e8af4ce9720c1821dfa33f48ddae3bb8
33.609375
245
0.72754
false
false
false
false
JGiola/swift
refs/heads/main
test/DebugInfo/inlined-generics-basic.swift
apache-2.0
10
// SIL. // RUN: %target-swift-frontend -parse-as-library -module-name A \ // RUN: -Xllvm -sil-print-debuginfo %s -g -O -o - -emit-sil \ // RUN: | %FileCheck %s --check-prefix=SIL // IR. // RUN: %target-swift-frontend -parse-as-library -module-name A \ // RUN: %s -g -O -o - -emit-ir \ // RUN: | %FileCheck %s --check-prefix=IR import StdlibUnittest @inline(never) func yes() -> Bool { return true } #sourceLocation(file: "use.swift", line: 1) @inline(never) func use<V>(_ v: V) { _blackHole(v) } #sourceLocation(file: "h.swift", line: 1) @inline(__always) func h<U>(_ u: U) { yes() use(u) } #sourceLocation(file: "g.swift", line: 1) @inline(__always) func g<T>(_ t: T) { if (yes()) { h(t) } } // SIL: sil_scope [[F:.*]] { {{.*}}parent @$s1A1CC1fyyqd__lF // SIL: sil_scope [[F1:.*]] { {{.*}}parent [[F]] } // SIL: sil_scope [[F1G:.*]] { loc "f.swift":2:5 parent [[F1]] } // SIL: sil_scope [[F1G1:.*]] { loc "g.swift":2:3 {{.*}}inlined_at [[F1G]] } // SIL: sil_scope [[F1G3:.*]] { loc "g.swift":3:5 {{.*}}inlined_at [[F1G]] } // SIL: sil_scope [[F1G3H:.*]] { loc "h.swift":1:24 // SIL-SAME: parent @{{.*}}1h{{.*}} inlined_at [[F1G3]] } // SIL: sil_scope [[F1G3H1:.*]] { {{.*}} parent [[F1G3H]] inlined_at [[F1G3]] } #sourceLocation(file: "C.swift", line: 1) public class C<R> { let r : R init(_ _r: R) { r = _r } // SIL-LABEL: // C.f<A>(_:) // IR-LABEL: define {{.*}} @"$s1A1CC1fyyqd__lF" #sourceLocation(file: "f.swift", line: 1) public func f<S>(_ s: S) { // SIL: debug_value %0 : $*S, let, name "s", argno 1, expr op_deref, {{.*}} scope [[F]] // SIL: function_ref {{.*}}yes{{.*}} scope [[F1G1]] // SIL: function_ref {{.*}}use{{.*}} scope [[F1G3H1]] // IR: dbg.value(metadata %swift.type* %S, metadata ![[MD_1_0:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[S:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[GS_T:[0-9]+]] // IR: dbg.value(metadata %swift.opaque* %0, metadata ![[GS_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 2) g(s) // Jump-threading removes the basic block containing debug_value // "t" before the second call to `g(r)`. When this happens, the // ref_element_addr in that removed block is left with a single // debug_value use, so they are both deleted. This means we have // no debug value for "t" in the call to `g(r)`. // dbg.value({{.*}}, metadata ![[GR_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GR_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 3) g(r) // IR: dbg.value({{.*}}, metadata ![[GRS_T:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GRS_U:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 4) g((r, s)) // Note to maintainers: the relative order of the constant dbg.values here // seem to flip back and forth. // IR: dbg.value({{.*}}, metadata ![[GI_U:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GI_T:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 5) g(Int(0)) // IR: dbg.value({{.*}}, metadata ![[GB_U:[0-9]+]] // IR: dbg.value({{.*}}, metadata ![[GB_T:[0-9]+]] // IR: call {{.*}}3use #sourceLocation(file: "f.swift", line: 6) g(false) } } // SIL-LABEL: } // end sil function '$s1A1CC1fyyqd__lF' // IR-LABEL: ret void // IR: ![[BOOL:[0-9]+]] = !DICompositeType({{.*}}name: "Bool" // IR: ![[LET_BOOL:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[BOOL]]) // IR: ![[INT:[0-9]+]] = !DICompositeType({{.*}}name: "Int" // IR: ![[LET_INT:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[INT]]) // IR: ![[TAU_0_0:[0-9]+]] = {{.*}}DW_TAG_structure_type, name: "$sxD", // IR: ![[LET_TAU_0_0:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[TAU_0_0]]) // IR: ![[TAU_1_0:[0-9]+]] = {{.*}}DW_TAG_structure_type, name: "$sqd__D", // IR: ![[MD_1_0]] = !DILocalVariable(name: "$\CF\84_1_0" // IR: ![[S]] = !DILocalVariable(name: "s", {{.*}} type: ![[LET_TAU_1_0:[0-9]+]] // IR: ![[LET_TAU_1_0]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[TAU_1_0]]) // IR: ![[GS_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GS_T:[0-9]+]], {{.*}} type: ![[LET_TAU_1_0]]) // IR: ![[SP_GS_T]] = {{.*}}linkageName: "$s1A1gyyxlFqd___Ti5" // IR: ![[GS_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GS_U:[0-9]+]], {{.*}} type: ![[LET_TAU_1_0]]) // IR: ![[SP_GS_U]] = {{.*}}linkageName: "$s1A1hyyxlFqd___Ti5" // Debug info for this variable is removed. See the note above the call to g(r). // ![[GR_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GR_T:[0-9]+]], {{.*}}type: ![[LET_TAU_0_0]]) // S has the same generic parameter numbering s T and U. // ![[SP_GR_T]] = {{.*}}linkageName: "$s1A1gyyxlF" // IR: ![[GR_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GR_U:[0-9]+]], {{.*}}type: ![[LET_TAU_0_0]]) // IR: ![[SP_GR_U]] = {{.*}}linkageName: "$s1A1hyyxlF" // IR: ![[GRS_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GRS_T:[0-9]+]], {{.*}}type: ![[LET_TUPLE:[0-9]+]] // IR: ![[SP_GRS_T]] = {{.*}}linkageName: "$s1A1gyyxlFx_qd__t_Ti5" // IR: ![[LET_TUPLE]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[TUPLE:[0-9]+]]) // IR: ![[TUPLE]] = {{.*}}DW_TAG_structure_type, name: "$sx_qd__tD" // IR: ![[GRS_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GRS_U:[0-9]+]], {{.*}}type: ![[LET_TUPLE]] // IR: ![[SP_GRS_U]] = {{.*}}linkageName: "$s1A1hyyxlFx_qd__t_Ti5" // IR-DAG: ![[GI_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GI_G:[0-9]+]], {{.*}}type: ![[LET_INT]]) // IR-DAG: ![[SP_GI_G]] = {{.*}}linkageName: "$s1A1gyyxlFSi_Tg5" // IR-DAG: ![[GI_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GI_U:[0-9]+]], {{.*}}type: ![[LET_INT]]) // IR-DAG: ![[SP_GI_U]] = {{.*}}linkageName: "$s1A1hyyxlFSi_TG5" // IR-DAG: ![[GB_T]] = !DILocalVariable(name: "t", {{.*}} scope: ![[SP_GB_G:[0-9]+]], {{.*}}type: ![[LET_BOOL]]) // IR-DAG: ![[SP_GB_G]] = {{.*}}linkageName: "$s1A1gyyxlFSb_Tg5" // IR-DAG: ![[GB_U]] = !DILocalVariable(name: "u", {{.*}} scope: ![[SP_GB_U:[0-9]+]], {{.*}}type: ![[LET_BOOL]]) // IR-DAG: ![[SP_GB_U]] = {{.*}}linkageName: "$s1A1hyyxlFSb_TG5"
a00a0ef76f673eb9c221d39c83397d9a
48.015748
117
0.526104
false
false
false
false
harlanhaskins/trill
refs/heads/master
Sources/AST/ASTDumper.swift
mit
2
/// /// ASTDumper.swift /// /// Copyright 2016-2017 the Trill project authors. /// Licensed under the MIT License. /// /// Full license text available at https://github.com/trill-lang/trill /// import Diagnostics import Foundation import Source public class ASTDumper<StreamType: ColoredStream>: ASTTransformer { typealias Result = Void var indentLevel = 0 let sourceFiles: Set<String> let showImports: Bool var stream: StreamType public init(stream: inout StreamType, context: ASTContext, files: [SourceFile], showImports: Bool = false) { self.stream = stream self.sourceFiles = Set(files.map { $0.path.basename }) self.showImports = showImports super.init(context: context) } required public init(context: ASTContext) { fatalError("Cannot instantiate with just context") } func printAttributes(_ attributes: [String: Any]) { var attrs = [(String, String)]() for key in attributes.keys.sorted() { guard let val = attributes[key] else { continue } let attr: (String, String) if let val = val as? String { attr = (key, "\"\(val.escaped())\"") } else { attr = (key, "\(val)") } attrs.append(attr) } for (index, (key, attr)) in attrs.enumerated() { stream.write(key, with: [.green]) stream.write("=") if attr.hasPrefix("\"") { stream.write(attr, with: [.red]) } else if attr == "true" || attr == "false" || Int(attr) != nil || Double(attr) != nil { stream.write(attr, with: [.cyan]) } else { stream.write(attr) } if index != attrs.endIndex - 1 { stream.write(" ") } } } func printNode(_ node: ASTNode, then: (() -> Void)? = nil) { guard let loc = node.startLoc else { return } let file = loc.file let component = file.path.basename if !showImports { guard sourceFiles.contains(component) else { return } if let decl = node as? Decl, decl.has(attribute: .implicit) { return } } if indentLevel != 0 { stream.write("\n") } stream.write(String(repeating: " ", count: indentLevel)) let nodeName = "\(type(of: node))".snakeCase() stream.write("(") stream.write("\(nodeName) ", with: [.bold, .magenta]) stream.write(component, with: [.cyan]) stream.write(":") stream.write("\(loc.line)", with: [.cyan]) stream.write(":") stream.write("\(loc.column)", with: [.cyan]) stream.write(" ") printAttributes(node.attributes()) if let then = then { indent() then() dedent() } stream.write(")") if indentLevel == 0 { stream.write("\n") } } func indent() { indentLevel += 2 } func dedent() { indentLevel -= 2 } public override func visitNumExpr(_ expr: NumExpr) { printNode(expr) } public override func visitCharExpr(_ expr: CharExpr) { printNode(expr) } public override func visitVarExpr(_ expr: VarExpr) { printNode(expr) } public override func visitVoidExpr(_ expr: VoidExpr) { printNode(expr) } public override func visitBoolExpr(_ expr: BoolExpr) { printNode(expr) } public override func visitVarAssignDecl(_ decl: VarAssignDecl) { printNode(decl) { super.visitVarAssignDecl(decl) } } public override func visitParamDecl(_ decl: ParamDecl) { printNode(decl) { super.visitParamDecl(decl) } } public override func visitTypeAliasDecl(_ decl: TypeAliasDecl) { printNode(decl) { super.visitTypeAliasDecl(decl) } } public override func visitFuncDecl(_ decl: FuncDecl) { printNode(decl) { for param in decl.genericParams { self.printNode(param) } super.visitFuncDecl(decl) } } public override func visitProtocolDecl(_ decl: ProtocolDecl) { printNode(decl) { super.visitProtocolDecl(decl) } } public override func visitClosureExpr(_ expr: ClosureExpr) { printNode(expr) { super.visitClosureExpr(expr) } } public override func visitReturnStmt(_ stmt: ReturnStmt) { printNode(stmt) { super.visitReturnStmt(stmt) } } public override func visitBreakStmt(_ stmt: BreakStmt) { printNode(stmt) } public override func visitContinueStmt(_ stmt: ContinueStmt) { printNode(stmt) } public override func visitStringExpr(_ expr: StringExpr) { printNode(expr) } public override func visitStringInterpolationExpr(_ expr: StringInterpolationExpr) { printNode(expr) { super.visitStringInterpolationExpr(expr) } } public override func visitSubscriptExpr(_ expr: SubscriptExpr) { printNode(expr) { super.visitSubscriptExpr(expr) } } public override func visitTypeRefExpr(_ expr: TypeRefExpr) { printNode(expr) { super.visitTypeRefExpr(expr) } } public override func visitFloatExpr(_ expr: FloatExpr) { printNode(expr) } public override func visitCompoundStmt(_ stmt: CompoundStmt) { printNode(stmt) { super.visitCompoundStmt(stmt) } } public override func visitFuncCallExpr(_ expr: FuncCallExpr) { printNode(expr) { for param in expr.genericParams { self.printNode(param) } super.visitFuncCallExpr(expr) } } public override func visitTypeDecl(_ decl: TypeDecl) { printNode(decl) { for param in decl.genericParams { self.printNode(param) } super.visitTypeDecl(decl) } } public override func visitPropertyDecl(_ decl: PropertyDecl) -> Void { printNode(decl) { super.visitPropertyDecl(decl) } } public override func visitExtensionDecl(_ decl: ExtensionDecl) { printNode(decl) { super.visitExtensionDecl(decl) } } public override func visitWhileStmt(_ stmt: WhileStmt) { printNode(stmt) { super.visitWhileStmt(stmt) } } public override func visitForStmt(_ stmt: ForStmt) { printNode(stmt) { super.visitForStmt(stmt) } } public override func visitIfStmt(_ stmt: IfStmt) { printNode(stmt) { super.visitIfStmt(stmt) } } public override func visitDeclStmt(_ stmt: DeclStmt) -> () { printNode(stmt) { super.visitDeclStmt(stmt) } } public override func visitExprStmt(_ stmt: ExprStmt) { printNode(stmt) { super.visitExprStmt(stmt) } } public override func visitTernaryExpr(_ expr: TernaryExpr) { printNode(expr) { super.visitTernaryExpr(expr) } } public override func visitSwitchStmt(_ stmt: SwitchStmt) { printNode(stmt) { super.visitSwitchStmt(stmt) } } public override func visitCaseStmt(_ stmt: CaseStmt) { printNode(stmt) { super.visitCaseStmt(stmt) } } public override func visitInfixOperatorExpr(_ expr: InfixOperatorExpr) { printNode(expr) { super.visitInfixOperatorExpr(expr) } } public override func visitPrefixOperatorExpr(_ expr: PrefixOperatorExpr) { printNode(expr) { super.visitPrefixOperatorExpr(expr) } } public override func visitPropertyRefExpr(_ expr: PropertyRefExpr) { printNode(expr) { super.visitPropertyRefExpr(expr) } } public override func visitNilExpr(_ expr: NilExpr) { printNode(expr) { super.visitNilExpr(expr) } } public override func visitPoundFunctionExpr(_ expr: PoundFunctionExpr) { printNode(expr) { super.visitPoundFunctionExpr(expr) } } public override func visitArrayExpr(_ expr: ArrayExpr) { printNode(expr) { super.visitArrayExpr(expr) } } public override func visitSizeofExpr(_ expr: SizeofExpr) { printNode(expr) { super.visitSizeofExpr(expr) } } public override func visitOperatorDecl(_ decl: OperatorDecl) { printNode(decl) { super.visitOperatorDecl(decl) } } public override func visitTupleExpr(_ expr: TupleExpr) { printNode(expr) { super.visitTupleExpr(expr) } } public override func visitTupleFieldLookupExpr(_ expr: TupleFieldLookupExpr) { printNode(expr) { super.visitTupleFieldLookupExpr(expr) } } public override func visitParenExpr(_ expr: ParenExpr) { printNode(expr) { super.visitParenExpr(expr) } } public override func visitPoundDiagnosticStmt(_ stmt: PoundDiagnosticStmt) { printNode(stmt) { super.visitPoundDiagnosticStmt(stmt) } } public override func visitIsExpr(_ expr: IsExpr) -> Void { printNode(expr) { super.visitIsExpr(expr) } } public override func visitCoercionExpr(_ expr: CoercionExpr) -> Void { printNode(expr) { super.visitCoercionExpr(expr) } } } extension String { func splitCapitals() -> [String] { var s = "" var words = [String]() for char in unicodeScalars { if isupper(Int32(char.value)) != 0 && !s.isEmpty { words.append(s) s = "" } s.append(String(char)) } if !s.isEmpty { words.append(s) } return words } func snakeCase() -> String { return splitCapitals().map { $0.lowercased() }.joined(separator: "_") } }
92f275f07f143932cafabd5878e1635d
24.759104
110
0.632558
false
false
false
false
dtartaglia/MVVM_Redux
refs/heads/master
MVVM Redux/PaybackCollection.swift
mit
1
// // PaybackCollection.swift // MVVM Redux // // Created by Daniel Tartaglia on 1/25/16. // Copyright © 2016 Daniel Tartaglia. All rights reserved. // struct PaybackCollection { fileprivate (set) var paybacks: [Payback] = [] mutating func addPaybackWithFirstName(_ firstName: String, lastName: String, amount: Double) { let id = uniqueId uniqueId += 1 let payback = Payback(id: id, firstName: firstName, lastName: lastName, amount: amount) paybacks.append(payback) } mutating func removeAtIndex(_ index: Int) { paybacks.remove(at: index) } fileprivate var uniqueId = 0 } extension PaybackCollection { init(dictionary: [String: Any]) { let paybackDicts = dictionary["paybacks"]! as! [[String: AnyObject]] paybacks = paybackDicts.map { Payback(dictionary: $0) } uniqueId = dictionary["uniqueId"]! as! Int } var dictionary: [String: Any] { return [ "paybacks": paybacks.map { $0.dictionary }, "uniqueId": uniqueId ] } }
c53666884785cd986bfeb7a7dcdb5f26
21.204545
95
0.685773
false
false
false
false
Tsiems/mobile-sensing-apps
refs/heads/master
HeartBeet/HeartBeet/GraphViewController.swift
mit
1
// // GraphViewController.swift // HeartBeet // // Created by Erik Gabrielsen on 10/12/16. // Copyright © 2016 Eric Larson. All rights reserved. // import UIKit import GLKit class GraphViewController: GLKViewController { lazy var graphHelper:SMUGraphHelper = SMUGraphHelper(controller: self, preferredFramesPerSecond: 10, numGraphs: 1, plotStyle: PlotStyleSeparated, maxPointsPerGraph: 200) var bridge = OpenCVBridgeSub() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.graphHelper.setScreenBoundsBottomHalf() NotificationCenter.default.addObserver(self, selector: #selector(self.updateBridge(notification:)), name: NSNotification.Name(rawValue: "bridge"), object: nil) // Do any additional setup after loading the view. } func update() { let data = self.bridge.getScaledRedArray() // self.graphHelper.setGraphData(data, withDataLength: 200, forGraphIndex: 0) self.graphHelper.setGraphData(data, withDataLength: 200, forGraphIndex: 0, withNormalization: 1.5, withZeroValue: 0) } override func glkView(_ view: GLKView, drawIn rect: CGRect) { self.graphHelper.draw() glClearColor(0, 0, 0, 0); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateBridge(notification: NSNotification) { let userInfo:Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String,AnyObject> let bridgeData = userInfo["bridge"]! as! OpenCVBridgeSub self.bridge = bridgeData update() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
f2439ce27c59b898f7e8e7e3ae616215
35.446154
167
0.617138
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Scenes/Get elevation at a point/GetElevationPointViewController.swift
apache-2.0
1
// Copyright 2019 Esri. // // 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 ArcGIS /// A view controller that manages the interface of the Get Elevation at a Point /// sample. class GetElevationPointViewController: UIViewController { /// The scene view managed by the view controller. @IBOutlet var sceneView: AGSSceneView! { didSet { // Initialize a scene. sceneView.scene = makeScene() sceneView.touchDelegate = self // Set scene's viewpoint. let camera = AGSCamera(latitude: 28.42, longitude: 83.9, altitude: 10000.0, heading: 10.0, pitch: 80.0, roll: 0.0) sceneView.setViewpointCamera(camera) sceneView.graphicsOverlays.add(graphicsOverlay) } } /// The graphics overlay used to show a graphic at the tapped point. private let graphicsOverlay: AGSGraphicsOverlay = { let graphicsOverlay = AGSGraphicsOverlay() graphicsOverlay.renderingMode = .dynamic graphicsOverlay.sceneProperties?.surfacePlacement = .relative return graphicsOverlay }() /// Creates a scene. /// /// - Returns: A new `AGSScene` object with a base surface configured with /// an elevation source. private func makeScene() -> AGSScene { let scene = AGSScene(basemapStyle: .arcGISImagery) let surface = AGSSurface() // Create an elevation source. let elevationURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer") let elevationSource = AGSArcGISTiledElevationSource(url: elevationURL!) // Add the elevation source to the surface. surface.elevationSources.append(elevationSource) scene.baseSurface = surface return scene } /// Dismisses the elevation popover and removes the associated graphic. func dismissElevationPopover() { guard presentedViewController != nil else { return } dismiss(animated: false) sceneView.viewpointChangedHandler = nil graphicsOverlay.graphics.removeAllObjects() } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["GetElevationPointViewController", "ElevationViewController"] } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) dismissElevationPopover() } } // MARK: - AGSGeoViewTouchDelegate extension GetElevationPointViewController: AGSGeoViewTouchDelegate { func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { if let relativeSurfacePoint = sceneView?.screen(toBaseSurface: screenPoint) { dismiss(animated: false) // Get the tapped point let point = AGSPoint(x: relativeSurfacePoint.x, y: relativeSurfacePoint.y, spatialReference: .wgs84()) if let graphic = graphicsOverlay.graphics.firstObject as? AGSGraphic { // Move the symbol to the tapped point. graphic.geometry = point } else { // Create the symbol at the tapped point. let marker = AGSSimpleMarkerSceneSymbol(style: .sphere, color: .red, height: 100, width: 100, depth: 100, anchorPosition: .center) let graphic = AGSGraphic(geometry: point, symbol: marker) graphicsOverlay.graphics.add(graphic) } // Get the surface elevation at the surface point. self.sceneView.scene?.baseSurface!.elevation(for: relativeSurfacePoint) { (results: Double, error: Error?) in if let error = error { self.presentAlert(error: error) } else { self.showPopover(elevation: results, popoverPoint: screenPoint) } } } // Dismiss the elevation popover and hide the graphic when the user // interacts with the scene. sceneView.viewpointChangedHandler = { [weak self] in DispatchQueue.main.async { self?.dismissElevationPopover() } } } private func showPopover(elevation: Double, popoverPoint: CGPoint) { guard let elevationViewController = storyboard?.instantiateViewController(withIdentifier: "ElevationViewController") as? ElevationViewController else { return } // Setup the controller to display as a popover. elevationViewController.modalPresentationStyle = .popover elevationViewController.elevation = Measurement(value: elevation, unit: UnitLength.meters) if let popoverPresentationController = elevationViewController.popoverPresentationController { popoverPresentationController.delegate = self popoverPresentationController.passthroughViews = [sceneView] popoverPresentationController.sourceRect = CGRect(origin: popoverPoint, size: .zero) popoverPresentationController.sourceView = sceneView } present(elevationViewController, animated: false) } } extension GetElevationPointViewController: UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { // Clear selection when popover is dismissed. graphicsOverlay.graphics.removeAllObjects() } }
e0fe52a06bb5c2e48b472f1c6dbf53f9
43.263514
159
0.675011
false
false
false
false
seandavidmcgee/HumanKontact
refs/heads/master
keyboardTest/PagingViewController2.swift
mit
1
// // PagingViewController2.swift // keyboardTest // // Created by Sean McGee on 4/6/15. // Copyright (c) 2015 3 Callistos Services. All rights reserved. // import UIKit class PagingViewController2: PagingViewController0, UITextFieldDelegate { override func viewDidLoad() { var arrayFirstRow = ["O", "J", "W"] var arrayOfTagsFirst = [79, 74, 87] var buttonXFirst: CGFloat = 0 var buttonTagFirst: Int = 0 for key in arrayFirstRow { let keyButton1 = UIButton(frame: CGRect(x: buttonXFirst, y: 10, width: 52, height: 52)) buttonXFirst = buttonXFirst + 62 keyButton1.layer.cornerRadius = 0 keyButton1.layer.borderWidth = 1 keyButton1.setTitleColor(UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ), forState: UIControlState.Normal) keyButton1.layer.borderColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ).CGColor; keyButton1.backgroundColor = UIColor(white: 248/255, alpha: 0.5) keyButton1.setTitle("\(key)", forState: UIControlState.Normal) keyButton1.setTitleColor(UIColor(white: 248/255, alpha: 0.5), forState: UIControlState.Highlighted) keyButton1.titleLabel!.text = "\(key)" keyButton1.tag = arrayOfTagsFirst[buttonTagFirst] buttonTagFirst = buttonTagFirst++ keyButton1.addTarget(self, action: "buttonHighlight:", forControlEvents: UIControlEvents.TouchDown); keyButton1.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchUpInside); keyButton1.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpOutside); self.view.addSubview(keyButton1) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func buttonHighlight(sender: UIButton!) { var btnsendtag:UIButton = sender sender.backgroundColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ) } override func buttonNormal(sender: UIButton!) { var btnsendtag:UIButton = sender sender.backgroundColor = UIColor(white: 248/255, alpha: 0.5) } }
429a32179617bc368c4a25a6730106d1
43.528302
132
0.647881
false
false
false
false
wireapp/wire-ios-data-model
refs/heads/develop
Source/Model/Message/ZMGenericMessageData.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireCryptobox @objc(ZMGenericMessageData) @objcMembers public class ZMGenericMessageData: ZMManagedObject { // MARK: - Static override open class func entityName() -> String { return "GenericMessageData" } public static let dataKey = "data" public static let nonceKey = "nonce" public static let messageKey = "message" public static let assetKey = "asset" // MARK: - Managed Properties /// The (possibly encrypted) serialized Profobuf data. @NSManaged private var data: Data /// The nonce used to encrypt `data`, if applicable. @NSManaged public private(set) var nonce: Data? /// The client message containing this generic message data. @NSManaged public var message: ZMClientMessage? /// The asset client message containing this generic message data. @NSManaged public var asset: ZMAssetClientMessage? // MARK: - Properties /// The deserialized Protobuf object, if available. public var underlyingMessage: GenericMessage? { do { return try GenericMessage(serializedData: getProtobufData()) } catch { Logging.messageProcessing.warn("Could not retrieve GenericMessage: \(error.localizedDescription)") return nil } } /// Whether the Protobuf data is encrypted in the database. public var isEncrypted: Bool { return nonce != nil } public override var modifiedKeys: Set<AnyHashable>? { get { return Set() } set { /* do nothing */ } } // MARK: - Methods private func getProtobufData() throws -> Data { guard let moc = managedObjectContext else { throw ProcessingError.missingManagedObjectContext } return try decryptDataIfNeeded(data: data, in: moc) } /// Set the generic message. /// /// This method will attempt to serialize the protobuf object and store its data in this /// instance. /// /// - Parameter message: The protobuf object whose serialized data will be stored. /// - Throws: `ProcessingError` if the data can't be stored. public func setGenericMessage(_ message: GenericMessage) throws { guard let protobufData = try? message.serializedData() else { throw ProcessingError.failedToSerializeMessage } guard let moc = managedObjectContext else { throw ProcessingError.missingManagedObjectContext } let (data, nonce) = try encryptDataIfNeeded(data: protobufData, in: moc) self.data = data self.nonce = nonce } private func encryptDataIfNeeded(data: Data, in moc: NSManagedObjectContext) throws -> (data: Data, nonce: Data?) { guard moc.encryptMessagesAtRest else { return (data, nonce: nil) } do { return try moc.encryptData(data: data) } catch let error as NSManagedObjectContext.EncryptionError { throw ProcessingError.failedToEncrypt(reason: error) } } private func decryptDataIfNeeded(data: Data, in moc: NSManagedObjectContext) throws -> Data { guard let nonce = nonce else { return data } do { return try moc.decryptData(data: data, nonce: nonce) } catch let error as NSManagedObjectContext.EncryptionError { throw ProcessingError.failedToDecrypt(reason: error) } } } // MARK: - Encryption Error extension ZMGenericMessageData { enum ProcessingError: LocalizedError { case missingManagedObjectContext case failedToSerializeMessage case failedToEncrypt(reason: NSManagedObjectContext.EncryptionError) case failedToDecrypt(reason: NSManagedObjectContext.EncryptionError) var errorDescription: String? { switch self { case .missingManagedObjectContext: return "A managed object context is required to process the message data." case .failedToSerializeMessage: return "The message data couldn't not be serialized." case .failedToEncrypt(reason: let encryptionError): return "The message data could not be encrypted. \(encryptionError.errorDescription ?? "")" case .failedToDecrypt(reason: let encryptionError): return "The message data could not be decrypted. \(encryptionError.errorDescription ?? "")" } } } } extension ZMGenericMessageData: EncryptionAtRestMigratable { static let predicateForObjectsNeedingMigration: NSPredicate? = nil func migrateTowardEncryptionAtRest(in moc: NSManagedObjectContext) throws { let (ciphertext, nonce) = try moc.encryptData(data: data) self.data = ciphertext self.nonce = nonce } func migrateAwayFromEncryptionAtRest(in moc: NSManagedObjectContext) throws { guard let nonce = nonce else { return } let plaintext = try moc.decryptData(data: data, nonce: nonce) self.data = plaintext self.nonce = nil } }
0ddbafe0623e882dea45bfa669b6fe96
31.75
119
0.672276
false
false
false
false
ChenYilong/iOS10AdaptationTips
refs/heads/master
LocalNotificationDemo-Swift/LocalNotificationDemo-Swift/ViewController.swift
mit
1
// // ViewController.m // LocalNotificationDemo-Swift // // Created by Elon Chan 陈宜龙 ( https://github.com/ChenYilong ) on 6/15/16. // Copyright © 2016 微博@iOS程序犭袁 ( http://weibo.com/luohanchenyilong ). All rights reserved. // import UIKit import UserNotifications class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let center = UNUserNotificationCenter.current() // create actions let accept = UNNotificationAction.init(identifier: "com.elonchan.yes", title: "Accept", options: UNNotificationActionOptions.foreground) let decline = UNNotificationAction.init(identifier: "com.elonchan.no", title: "Decline", options: UNNotificationActionOptions.destructive) let snooze = UNNotificationAction.init(identifier: "com.elonchan.snooze", title: "Snooze", options: UNNotificationActionOptions.destructive) let actions = [ accept, decline, snooze ] // create a category let inviteCategory = UNNotificationCategory(identifier: "com.elonchan.localNotification", actions: actions, intentIdentifiers: [], options: []) // registration center.setNotificationCategories([ inviteCategory ]) center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } // Do any additional setup after loading the view, typically from a nib. } @IBAction func triggerNotification(){ let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil) content.sound = UNNotificationSound.default() // NSNumber类型数据 content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1); content.categoryIdentifier = "com.elonchan.localNotification" // Deliver the notification in five seconds. /**** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'time interval must be at least 60 if repeating'*/ let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true) let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger) // Schedule the notification. let center = UNUserNotificationCenter.current() center.add(request) } @IBAction func stopNotification(_ sender: AnyObject) { let center = UNUserNotificationCenter.current() center.removeAllPendingNotificationRequests() // or you can remove specifical notification: // center.removePendingNotificationRequests(withIdentifiers: ["FiveSecond"]) } }
afd54a1bf345045e05c72deaf8ce8eec
47.78125
151
0.662076
false
false
false
false
n8armstrong/CalendarView
refs/heads/master
CalendarView/CalendarView/Classes/ContentView.swift
mit
1
// // CalendarContentView.swift // Calendar // // Created by Nate Armstrong on 3/29/15. // Copyright (c) 2015 Nate Armstrong. All rights reserved. // Updated to Swift 4 by A&D Progress aka verebes (c) 2018 // import UIKit import SwiftMoment class ContentView: UIScrollView { let numMonthsLoaded = 3 let currentPage = 1 var months: [MonthView] = [] var selectedDate: Moment? var paged = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { isPagingEnabled = true showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false for month in months { month.setdown() month.removeFromSuperview() } months = [] let date = selectedDate ?? moment() selectedDate = date var currentDate = date.subtract(1, .Months) for _ in 1...numMonthsLoaded { let month = MonthView(frame: CGRect.zero) month.date = currentDate addSubview(month) months.append(month) currentDate = currentDate.add(1, .Months) } } override func layoutSubviews() { super.layoutSubviews() var x: CGFloat = 0 for month in months { month.frame = CGRect(x: x, y: 0, width: bounds.size.width, height: bounds.size.height) x = month.frame.maxX } contentSize = CGSize(width: bounds.size.width * numMonthsLoaded, height: bounds.size.height) } func selectPage(page: Int) { var page1FrameMatched = false var page2FrameMatched = false var page3FrameMatched = false var frameCurrentMatched = false let pageWidth = frame.size.width let pageHeight = frame.size.height let frameCurrent = CGRect(x: page * pageWidth, y: 0, width: pageWidth, height: pageHeight) let frameLeft = CGRect(x: (page-1) * pageWidth, y: 0, width: pageWidth, height: pageHeight) let frameRight = CGRect(x: (page+1) * pageWidth, y: 0, width: pageWidth, height: pageHeight) let page1 = months.first! let page2 = months[1] let page3 = months.last! if frameCurrent.origin.x == page1.frame.origin.x { page1FrameMatched = true frameCurrentMatched = true } else if frameCurrent.origin.x == page2.frame.origin.x { page2FrameMatched = true frameCurrentMatched = true } else if frameCurrent.origin.x == page3.frame.origin.x { page3FrameMatched = true frameCurrentMatched = true } if frameCurrentMatched { if page2FrameMatched { print("something weird happened") } else if page1FrameMatched { page3.date = page1.date.subtract(1, .Months) page1.frame = frameCurrent page2.frame = frameRight page3.frame = frameLeft months = [page3, page1, page2] } else if page3FrameMatched { page1.date = page3.date.add(1, .Months) page1.frame = frameRight page2.frame = frameLeft page3.frame = frameCurrent months = [page2, page3, page1] } contentOffset.x = frame.width selectedDate = nil paged = true } } func selectDate(date: Moment) { selectedDate = date setup() selectVisibleDate(date: date.day) setNeedsLayout() } func selectVisibleDate(date: Int) -> DayView? { let month = currentMonth() for week in month.weeks { for day in week.days { if day.date != nil && day.date.month == month.date.month && day.date.day == date { day.selected = true return day } } } return nil } func removeObservers() { for month in months { for week in month.weeks { for day in week.days { NotificationCenter.default.removeObserver(day) } } } } func currentMonth() -> MonthView { return months[1] } }
a364b4d5ebbd1dd7931ee29449467300
24.598684
96
0.632999
false
false
false
false
slabgorb/Tiler
refs/heads/master
Tiler/MapListTableViewController.swift
mit
1
// // MapListTableViewController.swift // Tiler // // Created by Keith Avery on 3/26/16. // Copyright © 2016 Keith Avery. All rights reserved. // import UIKit class MapListTableViewController: UITableViewController, MapPersistence { var mapList:MapList? { didSet { tableView.reloadData() } } var selectedMap: Map? @IBOutlet weak var editMapBarButton: UIBarButtonItem! @IBOutlet weak var addMapBarButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() if let savedMaps = loadMaps() { if savedMaps.count > 0 { mapList = savedMaps } else { mapList = loadSampleMaps() } } else { mapList = loadSampleMaps() saveMaps() } clearsSelectionOnViewWillAppear = false tableView.tableFooterView = UIView(frame: CGRectZero ) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) mapList = loadMaps() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let count = mapList?.count { return count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> MapTableViewCell { let cell:MapTableViewCell = tableView.dequeueReusableCellWithIdentifier("mapTableCell", forIndexPath: indexPath) as! MapTableViewCell if let ml = self.mapList { let map = ml.get(indexPath.row) cell.loadItem(map) } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectedMap = mapList!.get(indexPath.row) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { mapList!.remove(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) if mapList!.count == 0 { mapList = loadSampleMaps() finishEditing() } } else if editingStyle == .Insert { let newMap = Map(title: "Untitled") mapList!.append(newMap) } saveMaps() } override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { mapList!.swapItems(fromIndexPath.row, toIndexPath.row) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "MapDetailSegue") { if let navigationController = segue.destinationViewController as? UINavigationController { if let mapViewController = navigationController.topViewController as? MapViewController { if let row = tableView.indexPathForSelectedRow?.row { mapViewController.mapIndex = row } } } } } // MARK: - Editing func finishEditing() { self.tableView.setEditing(false, animated: true) saveMaps() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(MapListTableViewController.editMapList(_:))) tableView.reloadData() } func startEditing() { self.tableView.setEditing(true, animated: true) self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(MapListTableViewController.editMapList(_:))) } @IBAction func editMapList(sender: UIBarButtonItem) { if self.tableView.editing { finishEditing() } else { startEditing() } } @IBAction func addMap(sender: UIBarButtonItem) { let newMap = Map(title: "Untitled") mapList!.append(newMap) saveMaps() self.tableView.reloadData() } func loadSampleMaps() -> MapList { let openings = [ Opening(.Small, .West), Opening(.Small, .North) ] let tile1 = Tile(openings: openings, imageName: "bend", backgroundImageName: "texture1", row: 0, column: 0) let tile2 = Tile(openings: openings, imageName: "bend", backgroundImageName: "texture1", row: 0, column: 1) let tile3 = Tile(openings: openings, imageName: "bend", backgroundImageName: "texture1", row: 1, column: 0) let tile4 = Tile(openings: openings, imageName: "bend", backgroundImageName: "texture1", row: 1, column: 1) tile1.rotate(.Clockwise) tile3.rotate(.Counterclockwise) tile4.rotate(.Clockwise) tile4.rotate(.Clockwise) let map1 = Map(title: "Sample Map 1", tiles:[tile1, tile2, tile3, tile4]) let map2 = Map(title: "Sample Map 2", tiles:[tile1, tile2, tile3, tile4]) return MapList(maps:[ map1, map2 ]) } @IBAction func unwindToList(unwindSegue: UIStoryboardSegue) { } }
4a04a0665739606312a454d66e01bd56
32.616766
168
0.620057
false
false
false
false
nhatlee/MyWebsite-SwiftVapor
refs/heads/master
Sources/Helps/Constants/Constaints.swift
mit
1
// // Constaints.swift // MyWebsite // // Created by nhatlee on 9/25/17. // //public enum UserKeys: String, CodingKey { // case name = "username" // case email = "email" // case password = "password" // case confirm = "ConfirmPassword" // case address = "address" //}
df0854914331d023984b968246963f9c
19.466667
43
0.566775
false
false
false
false
ramki1979/OAuthSDK
refs/heads/master
Example/Services/TwitterService.swift
mit
1
// // TwitterService.swift // OAuthSDK // // Created by RamaKrishna Mallireddy on 20/04/15. // Copyright (c) 2015 VUContacts. All rights reserved. // import Foundation import OAuthSDK class TwitterService: OAuth1 { // Add json config to make this easier... init(service: String) { // client_secret -> should be get from the server // server supports only https... // once received, it has to be stored into the keychain // client secret shouldn't be stored in plaintext, its has to be encrypted let config = [ "service":service, "base_url":"https://api.twitter.com/1.1", "consumer_key":"2cyqKxhrMcV8YJSH8Ed6A", "consumer_secret":"BcP8Fdcn6FWpWCPwC3Lk4frZ58OE6Lh0CE60cjRoEMw"] super.init(config: config) delegate = self // Add Default API Endpoints here... let requestToken = ["method":"POST", "url":"https://api.twitter.com/oauth/request_token", "format":"&=", "oauth_callback":"https://127.0.0.1:9000/oauth1/twitter/"] let authenticateUser = ["url":"https://api.twitter.com/oauth/authorize", "oauth_token":""] let authenticateRequestTokenForAccessToken = ["method":"POST","url":"https://api.twitter.com/oauth/access_token", "format":"&="] // let refreshToken = ["method":"POST","url":"https://www.googleapis.com/oauth2/v3/token","client_id":"","client_secret":"","refresh_token":"","grant_type":"refresh_token"] // let validateToken = ["method":"GET","url":"https://www.googleapis.com/oauth2/v1/tokeninfo","access_token":""] let profile = ["method":"GET", "path":"/users/show.json", "screen_name":"", "format":"json"] addEndPoint(OAuthEndPointKeys.RequestTokenURL.rawValue, value: requestToken) addEndPoint(OAuthEndPointKeys.AuthenticateUserURL.rawValue, value: authenticateUser) addEndPoint(OAuthEndPointKeys.AuthenticateUserCodeForAccessTokenURL.rawValue, value: authenticateRequestTokenForAccessToken) // addEndPoint(OAuthEndPointKeys.RefreshAccessTokenURL.rawValue, value: refreshToken) // addEndPoint(OAuthEndPointKeys.ValidateAccessTokenURL.rawValue, value: validateToken) addEndPoint(OAuthEndPointKeys.UserProfileURL.rawValue, value: profile) } } extension TwitterService: OAuthRequestResponse { func requestComplete(serviceName: String, path: String, response: AnyObject) { if state() == OAuthClientState.AccessToken { // Access user profile createDataTask(OAuthEndPointKeys.UserProfileURL.rawValue) } } func requestCompleteWithError(serviceName: String, path: String, response: String) { } func requestFailedWithError(serviceName: String, path: String, error: String) { } }
130bd16fd8fbbb75cfea9cd866e9de77
44.396825
179
0.662819
false
true
false
false
P0ed/Magikombat
refs/heads/master
Carthage/Checkouts/BrightFutures/BrightFuturesTests/PromiseTests.swift
mit
8
// // PromiseTests.swift // BrightFutures // // Created by Thomas Visser on 16/10/15. // Copyright © 2015 Thomas Visser. All rights reserved. // import XCTest import BrightFutures import Result class PromiseTests: XCTestCase { func testSuccessPromise() { let p = Promise<Int, NoError>() Queue.global.async { p.success(fibonacci(10)) } let e = self.expectationWithDescription("complete expectation") p.future.onComplete { result in switch result { case .Success(let val): XCTAssert(Int(55) == val) case .Failure(_): XCTAssert(false) } e.fulfill() } self.waitForExpectationsWithTimeout(2, handler: nil) } func testFailurePromise() { let p = Promise<Int, TestError>() Queue.global.async { p.tryFailure(TestError.JustAnError) } let e = self.expectationWithDescription("complete expectation") p.future.onComplete { result in switch result { case .Success(_): XCTFail("should not be success") case .Failure(let err): XCTAssertEqual(err, TestError.JustAnError) } e.fulfill() } self.waitForExpectationsWithTimeout(2, handler: nil) } func testCompletePromise() { let p = Promise<Int, TestError>() p.complete(Result(value: 2)) XCTAssertEqual(p.future.value, 2) } func testPromiseCompleteWithSuccess() { let p = Promise<Int, TestError>() p.tryComplete(Result(value: 2)) XCTAssert(p.future.isSuccess) XCTAssert(p.future.forced() == Result<Int, TestError>(value:2)) } func testPromiseCompleteWithFailure() { let p = Promise<Int, TestError>() p.tryComplete(Result(error: TestError.JustAnError)) XCTAssert(p.future.isFailure) XCTAssert(p.future.forced() == Result<Int, TestError>(error:TestError.JustAnError)) } func testPromiseTrySuccessTwice() { let p = Promise<Int, NoError>() XCTAssert(p.trySuccess(1)) XCTAssertFalse(p.trySuccess(2)) XCTAssertEqual(p.future.forced().value!, 1) } func testPromiseTryFailureTwice() { let p = Promise<Int, TestError>() XCTAssert(p.tryFailure(TestError.JustAnError)) XCTAssertFalse(p.tryFailure(TestError.JustAnotherError)) XCTAssertEqual(p.future.forced().error!, TestError.JustAnError) } func testPromiseCompleteWithSucceedingFuture() { let p = Promise<Int, NoError>() let q = Promise<Int, NoError>() p.completeWith(q.future) XCTAssert(!p.future.isCompleted) q.success(1) XCTAssertEqual(p.future.value, 1) } func testPromiseCompleteWithFailingFuture() { let p = Promise<Int, TestError>() let q = Promise<Int, TestError>() p.completeWith(q.future) XCTAssert(!p.future.isCompleted) q.failure(.JustAnError) XCTAssertEqual(p.future.error, .JustAnError) } }
20c2dd87bfb1441dea786e6352080c04
26.92437
91
0.570268
false
true
false
false
codestergit/swift
refs/heads/master
test/SILGen/materializeForSet.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Base { var stored: Int = 0 // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T2:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none // CHECK: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Base, [[SELFTYPE:%.*]] : $@thick Base.Type): // CHECK: [[T0:%.*]] = load_borrow [[SELF]] // CHECK: [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T2:%.*]] = load [trivial] [[T1]] : $*Int // CHECK: [[SETTER:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifs // CHECK: apply [[SETTER]]([[T2]], [[T0]]) // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC8computedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[ADDR]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[ADDR]] // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () // CHECK: [[T2:%.*]] = thin_function_to_pointer [[T0]] // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T2]] : $Builtin.RawPointer // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } var computed: Int { get { return 0 } set(value) {} } var storedFunction: () -> Int = { 0 } final var finalStoredFunction: () -> Int = { 0 } var computedFunction: () -> Int { get { return {0} } set {} } static var staticFunction: () -> Int { get { return {0} } set {} } } class Derived : Base {} protocol Abstractable { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } // Validate that we thunk materializeForSet correctly when there's // an abstraction pattern present. extension Derived : Abstractable {} // CHECK: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Derived, @thick Derived.Type) -> () // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!setter.1 : (Base) -> (@escaping () -> Int) -> () // CHECK-NEXT: apply [[FN]]([[NEWVALUE]], [[SELF]]) // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction{{[_0-9a-zA-Z]*}}fmTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!getter.1 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[SELF]]) // CHECK-NEXT: store [[RESULT]] to [init] [[TEMP]] // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T2:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycfmytfU_TW // CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]] // CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: return [[T4]] // CHECK: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycfmytfU_TW : // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: // function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: assign [[NEWVALUE]] to [[ADDR]] // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction{{[_0-9a-zA-Z]*}}fmTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[ADDR]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T2:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycfmytfU_TW // CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]] // CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: return [[T4]] // CHECK-LABEL: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZytfU_TW // CHECK: bb0([[ARG1:%.*]] : $Builtin.RawPointer, [[ARG2:%.*]] : $*Builtin.UnsafeValueBuffer, [[ARG3:%.*]] : $*@thick Derived.Type, [[ARG4:%.*]] : $@thick Derived.Type.Type): // CHECK-NEXT: [[SELF:%.*]] = load [trivial] [[ARG3]] : $*@thick Derived.Type // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[SELF]] : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[BUFFER:%.*]] = pointer_to_address [[ARG1]] : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[BUFFER]] : $*@callee_owned () -> @out Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_T017materializeForSet4BaseC14staticFunctionSiycfsZ : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: apply [[SETTER_FN]]([[NEWVALUE]], [[BASE_SELF]]) : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $@thick Derived.Type): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[SELF:%.*]] = upcast %2 : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[OUT:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK: [[GETTER:%.*]] = function_ref @_T017materializeForSet4BaseC14staticFunctionSiycfgZ : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]]) : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: store [[VALUE]] to [init] [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = load [copy] [[OUT]] : $*@callee_owned () -> Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: destroy_addr [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: store [[NEWVALUE]] to [init] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: [[ADDR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () // CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] : $Builtin.RawPointer // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: dealloc_stack [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) protocol ClassAbstractable : class { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } extension Derived : ClassAbstractable {} protocol Signatures { associatedtype Result var computedFunction: () -> Result { get set } } protocol Implementations {} extension Implementations { var computedFunction: () -> Int { get { return {0} } set {} } } class ImplementingClass : Implementations, Signatures {} struct ImplementingStruct : Implementations, Signatures { var ref: ImplementingClass? } class HasDidSet : Base { override var stored: Int { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet06HasDidC0C6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet06HasDidC0C6storedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet06HasDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } override var computed: Int { get { return 0 } set(value) {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet06HasDidC0C8computedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet06HasDidC0C8computedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet06HasDidC0C8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } class HasStoredDidSet { var stored: Int = 0 { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet012HasStoredDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*HasStoredDidSet, [[METATYPE:%.*]] : $@thick HasStoredDidSet.Type): // CHECK: [[SELF_VALUE:%.*]] = load_borrow [[SELF]] : $*HasStoredDidSet // CHECK: [[BUFFER_ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[BUFFER_ADDR]] : $*Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifs : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: apply [[SETTER_FN]]([[VALUE]], [[SELF_VALUE]]) : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: return // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet012HasStoredDidC0C6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasStoredDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasStoredDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } class HasWeak { weak var weakvar: HasWeak? } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet7HasWeakC7weakvarACSgXwfm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasWeak): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Optional<HasWeak> // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar // CHECK: [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak> // CHECK: store [[T1]] to [init] [[T2]] : $*Optional<HasWeak> // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet7HasWeakC7weakvarACSgXwfmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> () // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // rdar://22109071 // Test that we don't use materializeForSet from a protocol extension. protocol Magic {} extension Magic { var hocus: Int { get { return 0 } set {} } } struct Wizard : Magic {} func improve(_ x: inout Int) {} func improveWizard(_ wizard: inout Wizard) { improve(&wizard.hocus) } // CHECK-LABEL: sil hidden @_T017materializeForSet13improveWizardyAA0E0VzF // CHECK: [[IMPROVE:%.*]] = function_ref @_T017materializeForSet7improveySizF : // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int // Call the getter and materialize the result in the temporary. // CHECK-NEXT: [[T0:%.*]] = load [trivial] [[WIZARD:.*]] : $*Wizard // CHECK-NEXT: function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_T017materializeForSet5MagicPAAE5hocusSifg // CHECK-NEXT: [[WTEMP:%.*]] = alloc_stack $Wizard // CHECK-NEXT: store [[T0]] to [trivial] [[WTEMP]] // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]<Wizard>([[WTEMP]]) // CHECK-NEXT: dealloc_stack [[WTEMP]] // CHECK-NEXT: store [[T0]] to [trivial] [[TEMP]] // Call improve. // CHECK-NEXT: apply [[IMPROVE]]([[TEMP]]) // CHECK-NEXT: [[T0:%.*]] = load [trivial] [[TEMP]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T017materializeForSet5MagicPAAE5hocusSifs // CHECK-NEXT: apply [[SETTER]]<Wizard>([[T0]], [[WIZARD]]) // CHECK-NEXT: dealloc_stack [[TEMP]] protocol Totalled { var total: Int { get set } } struct Bill : Totalled { var total: Int } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BillV5totalSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*Bill, #Bill.total // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt // CHECK: [[T4:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BillV5totalSifm // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BUFFER]], [[STORAGE]], [[SELF]]) // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[T1]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[T1]] // CHECK-NEXT: [[T1:%.*]] = tuple ([[LEFT]] : $Builtin.RawPointer, [[RIGHT]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: return [[T1]] : protocol AddressOnlySubscript { associatedtype Index subscript(i: Index) -> Index { get set } } struct Foo<T>: AddressOnlySubscript { subscript(i: T) -> T { get { return i } set { print("\(i) = \(newValue)") } } } func increment(_ x: inout Int) { x += 1 } // Generic subscripts. protocol GenericSubscriptProtocol { subscript<T>(_: T) -> T { get set } } struct GenericSubscriptWitness : GenericSubscriptProtocol { subscript<T>(_: T) -> T { get { } set { } } } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufmytfU_ : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () { // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*GenericSubscriptWitness, %3 : $@thick GenericSubscriptWitness.Type): // CHECK: [[BUFFER:%.*]] = project_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: [[INDICES:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T // CHECK: [[SETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufs : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> () // CHECK-NEXT: apply [[SETTER]]<T>([[INDICES]], [[BUFFER]], %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> () // CHECK-NEXT: dealloc_value_buffer $*T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL sil hidden [transparent] [thunk] @_T017materializeForSet23GenericSubscriptWitnessVAA0dE8ProtocolA2aDP9subscriptqd__qd__clufmTW : $@convention(witness_method) <τ_0_0> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in τ_0_0, @inout GenericSubscriptWitness) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*T, %3 : $*GenericSubscriptWitness): // CHECK-NEXT: [[BUFFER:%.*]] = alloc_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: copy_addr %2 to [initialization] [[BUFFER]] : $*T // CHECK-NEXT: [[VALUE:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T // CHECK-NEXT: [[SELF:%.*]] = load [trivial] %3 : $*GenericSubscriptWitness // CHECK: [[GETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufg : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0 // CHECK-NEXT: apply [[GETTER]]<T>([[VALUE]], %2, [[SELF]]) : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0 // CHECK-NEXT: [[VALUE_PTR:%.*]] = address_to_pointer [[VALUE]] : $*T to $Builtin.RawPointer // CHECK: [[CALLBACK:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufmytfU_ // CHECK-NEXT: [[CALLBACK_PTR:%.*]] = thin_function_to_pointer [[CALLBACK]] : $@convention(method) <τ_0_0> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () to $Builtin.RawPointer // CHECK-NEXT: [[CALLBACK_OPTIONAL:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_PTR]] : $Builtin.RawPointer // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[VALUE_PTR]] : $Builtin.RawPointer, [[CALLBACK_OPTIONAL]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) extension GenericSubscriptProtocol { subscript<T>(t: T) -> T { get { } set { } } } struct GenericSubscriptDefaultWitness : GenericSubscriptProtocol { } // Test for materializeForSet vs static properties of structs. protocol Beverage { static var abv: Int { get set } } struct Beer : Beverage { static var abv: Int { get { return 7 } set { } } } struct Wine<Color> : Beverage { static var abv: Int { get { return 14 } set { } } } // Make sure we can perform an inout access of such a property too. func inoutAccessOfStaticProperty<T : Beverage>(_ t: T.Type) { increment(&t.abv) } // Test for materializeForSet vs overridden computed property of classes. class BaseForOverride { var valueStored: Int var valueComputed: Int { get { } set { } } init(valueStored: Int) { self.valueStored = valueStored } } class DerivedForOverride : BaseForOverride { override var valueStored: Int { get { } set { } } override var valueComputed: Int { get { } set { } } } // Test for materializeForSet vs static properties of classes. class ReferenceBeer { class var abv: Int { get { return 7 } set { } } } func inoutAccessOfClassProperty() { increment(&ReferenceBeer.abv) } // Test for materializeForSet when Self is re-abstracted. // // We have to open-code the materializeForSelf witness, and not screw up // the re-abstraction. protocol Panda { var x: (Self) -> Self { get set } } func id<T>(_ t: T) -> T { return t } extension Panda { var x: (Self) -> Self { get { return id } set { } } } struct TuxedoPanda : Panda { } // CHECK-LABEL: sil private [transparent] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // FIXME: Useless re-abstractions // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxir_A2CIxyd_TR : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcfs : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_owned (@in τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> () // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxyd_A2CIxir_TR : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // CHECK: } // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmTW // Call the getter: // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcfg : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_owned (@in τ_0_0) -> @out τ_0_0 // Result of calling the getter is re-abstracted to the maximally substituted type // by SILGenFunction::emitApply(): // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxir_A2CIxyd_TR : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // ... then we re-abstract to the requirement signature: // FIXME: Peephole this away with the previous one since there's actually no // abstraction change in this case. // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxyd_A2CIxir_TR : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // The callback: // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // CHECK: } // Test for materializeForSet vs lazy properties of structs. struct LazyStructProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet31inoutAccessOfLazyStructPropertyyAA0ghI0Vz1l_tF // CHECK: function_ref @_T017materializeForSet18LazyStructPropertyV3catSifg // CHECK: function_ref @_T017materializeForSet18LazyStructPropertyV3catSifs func inoutAccessOfLazyStructProperty(l: inout LazyStructProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of classes. // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet17LazyClassPropertyC3catSifm class LazyClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet30inoutAccessOfLazyClassPropertyyAA0ghI0Cz1l_tF // CHECK: class_method {{.*}} : $LazyClassProperty, #LazyClassProperty.cat!materializeForSet.1 func inoutAccessOfLazyClassProperty(l: inout LazyClassProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of final classes. final class LazyFinalClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet35inoutAccessOfLazyFinalClassPropertyyAA0ghiJ0Cz1l_tF // CHECK: function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSifg // CHECK: function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSifs func inoutAccessOfLazyFinalClassProperty(l: inout LazyFinalClassProperty) { increment(&l.cat) } // Make sure the below doesn't crash SILGen struct FooClosure { var computed: (((Int) -> Int) -> Int)? { get { return stored } set {} } var stored: (((Int) -> Int) -> Int)? = nil } // CHECK-LABEL: _T017materializeForSet22testMaterializedSetteryyF func testMaterializedSetter() { // CHECK: function_ref @_T017materializeForSet10FooClosureVACycfC var f = FooClosure() // CHECK: function_ref @_T017materializeForSet10FooClosureV8computedS3iccSgfg // CHECK: function_ref @_T017materializeForSet10FooClosureV8computedS3iccSgfs f.computed = f.computed } // CHECK-LABEL: sil_vtable DerivedForOverride { // CHECK: #BaseForOverride.valueStored!getter.1: (BaseForOverride) -> () -> Int : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifg // CHECK: #BaseForOverride.valueStored!setter.1: (BaseForOverride) -> (Int) -> () : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifs // CHECK: #BaseForOverride.valueStored!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifm // CHECK: #BaseForOverride.valueComputed!getter.1: (BaseForOverride) -> () -> Int : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifg // CHECK: #BaseForOverride.valueComputed!setter.1: (BaseForOverride) -> (Int) -> () : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifs // CHECK: #BaseForOverride.valueComputed!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifm // CHECK: } // CHECK-LABEL: sil_witness_table hidden Bill: Totalled module materializeForSet { // CHECK: method #Totalled.total!getter.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifgTW // CHECK: method #Totalled.total!setter.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifsTW // CHECK: method #Totalled.total!materializeForSet.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifmTW // CHECK: }
15ada15b2a9c2bee6ecf75a833fab1c7
56.732657
334
0.673417
false
false
false
false
tkremenek/swift
refs/heads/master
test/Parse/async-syntax.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency -disable-availability-checking -verify-syntax-tree // REQUIRES: concurrency func asyncGlobal1() async { } func asyncGlobal2() async throws { } typealias AsyncFunc1 = () async -> () typealias AsyncFunc2 = () async throws -> () typealias AsyncFunc3 = (_ a: Bool, _ b: Bool) async throws -> () func testTypeExprs() { let _ = [() async -> ()]() let _ = [() async throws -> ()]() } func testAwaitOperator() async { let _ = await asyncGlobal1() } func testAsyncClosure() { let _ = { () async in 5 } let _ = { () throws in 5 } let _ = { () async throws in 5 } } func testAwait() async { let _ = await asyncGlobal1() }
2d2676eccc3dfbb48f993d1f3342a908
23.275862
122
0.632102
false
true
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Objects/Entities/MapImpl.swift
mit
1
import Foundation struct MapImpl: Map { private let imageRepository: ImageRepository private let dataStore: DataStore private let characteristics: MapCharacteristics private let dealers: ConcreteDealersService var identifier: MapIdentifier var location: String init( imageRepository: ImageRepository, dataStore: DataStore, characteristics: MapCharacteristics, dealers: ConcreteDealersService ) { self.imageRepository = imageRepository self.dataStore = dataStore self.characteristics = characteristics self.dealers = dealers self.identifier = MapIdentifier(characteristics.identifier) self.location = characteristics.mapDescription } func fetchImagePNGData(completionHandler: @escaping (Data) -> Void) { if let image = imageRepository.loadImage(identifier: characteristics.imageIdentifier) { completionHandler(image.pngImageData) } } private struct MapEntryDisplacementResult: Comparable { static func < (lhs: MapImpl.MapEntryDisplacementResult, rhs: MapImpl.MapEntryDisplacementResult) -> Bool { lhs.displacement < rhs.displacement } var entry: MapCharacteristics.Entry var displacement: Double } func fetchContentAt(x: Int, y: Int, completionHandler: @escaping (MapContent) -> Void) { var content: MapContent = .none defer { completionHandler(content) } let tappedWithinEntry: (MapCharacteristics.Entry) -> MapEntryDisplacementResult? = { (entry) in let tapRadius = entry.tapRadius let horizontalDelta = abs(entry.x - x) let verticalDelta = abs(entry.y - y) let delta = hypot(Double(horizontalDelta), Double(verticalDelta)) guard delta < Double(tapRadius) else { return nil } return MapEntryDisplacementResult(entry: entry, displacement: delta) } guard let entry = characteristics.entries.compactMap(tappedWithinEntry).min()?.entry else { return } let contentFromLink: (MapCharacteristics.Entry.Link) -> MapContent? = { (link) in if let room = self.dataStore.fetchRooms()?.first(where: { $0.identifier == link.target }) { return .room(Room(name: room.name)) } if let dealer = self.dealers.fetchDealer(for: DealerIdentifier(link.target)) { return .dealer(dealer) } if link.type == .mapEntry, let linkedEntry = self.characteristics.entries.first(where: { $0.identifier == link.target }), let name = link.name { return .location(x: Float(linkedEntry.x), y: Float(linkedEntry.y), name: name) } return nil } let links = entry.links let contents: [MapContent] = links.compactMap(contentFromLink) content = contents.reduce(into: MapContent.none, +) } }
0d0d833b4d701e46e7fa256f2579be2c
35.870588
114
0.616465
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/EquipmentOverviewView.swift
gpl-3.0
1
// // EquipmentOverviewView.swift // Habitica // // Created by Phillip Thelen on 17.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import PinLayout class EquipmentOverviewView: UIView { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var switchLabelView: UILabel! @IBOutlet weak var switchView: UISwitch! @IBOutlet weak var containerView: UIView! @IBOutlet weak var weaponItemView: EquipmentOverviewItemView! @IBOutlet weak var offHandItemView: EquipmentOverviewItemView! @IBOutlet weak var headItemView: EquipmentOverviewItemView! @IBOutlet weak var armorItemView: EquipmentOverviewItemView! @IBOutlet weak var headAccessoryItemView: EquipmentOverviewItemView! @IBOutlet weak var bodyAccessoryItemView: EquipmentOverviewItemView! @IBOutlet weak var backItemView: EquipmentOverviewItemView! @IBOutlet weak var eyewearItemView: EquipmentOverviewItemView! var title: String? { get { return titleLabel.text } set { titleLabel.text = newValue } } var switchLabel: String? { get { return switchLabelView.text } set { switchLabelView.text = newValue switchView.accessibilityLabel = newValue } } var switchValue: Bool { get { return switchView.isOn } set { switchView.isOn = newValue } } var itemTapped: ((String) -> Void)? var switchToggled: ((Bool) -> Void)? override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 375, height: 250)) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } override func layoutSubviews() { super.layoutSubviews() layout() } func getTotalHeight(for width: CGFloat) -> CGFloat { let itemWidth = (width - (7*8)) / 4 let itemHeights = (itemWidth+36)*2+(3*8) return itemHeights+79 } override func sizeThatFits(_ size: CGSize) -> CGSize { layout() return CGSize(width: size.width, height: containerView.frame.origin.y+containerView.frame.size.height+25) } override var intrinsicContentSize: CGSize { layout() return CGSize(width: bounds.size.width, height: containerView.frame.origin.y+containerView.frame.size.height+25) } private func layout() { let itemWidth = (bounds.size.width - (7*8)) / 4 let itemHeight = itemWidth+36 containerView.pin.top(54).left(8).right(8).height(itemHeight*2+(3*8)) titleLabel.pin.top(0).left(8).above(of: containerView).sizeToFit(.height) switchView.pin.right(8).top(11) switchLabelView.pin.top(0).above(of: containerView).left(of: switchView).marginRight(8).sizeToFit(.height) weaponItemView.pin.top(8).left(8).width(itemWidth).height(itemHeight) offHandItemView.pin.top(8).right(of: weaponItemView).marginLeft(8).width(itemWidth).height(itemHeight) headItemView.pin.top(8).right(of: offHandItemView).marginLeft(8).width(itemWidth).height(itemHeight) armorItemView.pin.top(8).right(of: headItemView).marginLeft(8).width(itemWidth).height(itemHeight) headAccessoryItemView.pin.bottom(8).left(8).width(itemWidth).width(itemWidth).height(itemHeight) bodyAccessoryItemView.pin.bottom(8).right(of: headAccessoryItemView).marginLeft(8).width(itemWidth).height(itemHeight) backItemView.pin.bottom(8).right(of: bodyAccessoryItemView).marginLeft(8).width(itemWidth).height(itemHeight) eyewearItemView.pin.bottom(8).right(of: backItemView).marginLeft(8).width(itemWidth).height(itemHeight) } // MARK: - Private Helper Methods private func setupView() { if let view = viewFromNibForClass() { view.frame = bounds addSubview(view) setupLabels() setNeedsUpdateConstraints() updateConstraints() setNeedsLayout() layoutIfNeeded() } } func applyTheme(theme: Theme) { titleLabel.textColor = theme.primaryTextColor switchLabelView.textColor = theme.secondaryTextColor backgroundColor = theme.contentBackgroundColor weaponItemView.applyTheme(theme: theme) offHandItemView.applyTheme(theme: theme) headItemView.applyTheme(theme: theme) armorItemView.applyTheme(theme: theme) headAccessoryItemView.applyTheme(theme: theme) bodyAccessoryItemView.applyTheme(theme: theme) backItemView.applyTheme(theme: theme) eyewearItemView.applyTheme(theme: theme) } private func setupLabels() { weaponItemView.setup(title: L10n.Equipment.weapon) {[weak self] in self?.onItemTapped("weapon") } offHandItemView.setup(title: L10n.Equipment.offHand) {[weak self] in self?.onItemTapped("shield") } headItemView.setup(title: L10n.Equipment.head) {[weak self] in self?.onItemTapped("head") } armorItemView.setup(title: L10n.Equipment.armor) {[weak self] in self?.onItemTapped("armor") } headAccessoryItemView.setup(title: L10n.Equipment.headAccessory) {[weak self] in self?.onItemTapped("headAccessory") } bodyAccessoryItemView.setup(title: L10n.Equipment.body) {[weak self] in self?.onItemTapped("body") } backItemView.setup(title: L10n.Equipment.back) {[weak self] in self?.onItemTapped("back") } eyewearItemView.setup(title: L10n.Equipment.eyewear) {[weak self] in self?.onItemTapped("eyewear") } } func configure(outfit: OutfitProtocol) { weaponItemView.configure(outfit.weapon) offHandItemView.configure(outfit.shield) headItemView.configure(outfit.head) armorItemView.configure(outfit.armor) headAccessoryItemView.configure(outfit.headAccessory) bodyAccessoryItemView.configure(outfit.body) backItemView.configure(outfit.back) eyewearItemView.configure(outfit.eyewear) } private func onItemTapped(_ typeKey: String) { if let action = itemTapped { action(typeKey) } } @IBAction func switchValueChanged(_ sender: Any) { if let action = switchToggled { action(switchView.isOn) } } }
28e460b78ae28931e592bd9de36164ac
34.531915
126
0.643263
false
false
false
false
WickedColdfront/Slide-iOS
refs/heads/master
Slide for Reddit/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // Slide for Reddit // // Created by Carlos Crane on 12/22/16. // Copyright © 2016 Haptic Apps. All rights reserved. // import UIKit import reddift import UserNotifications import RealmSwift import SDWebImage /// Posted when the OAuth2TokenRepository object succeed in saving a token successfully into Keychain. public let OAuth2TokenRepositoryDidSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidSaveToken") /// Posted when the OAuth2TokenRepository object failed to save a token successfully into Keychain. public let OAuth2TokenRepositoryDidFailToSaveTokenName = Notification.Name(rawValue: "OAuth2TokenRepositoryDidFailToSaveToken") @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let name = "reddittoken" var session: Session? = nil var fetcher: BackgroundFetch? = nil var subreddits: [Subreddit] = [] var paginator = Paginator() var login: SubredditsViewController? var seenFile: String? var commentsFile: String? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray let documentDirectory = paths[0] as! String seenFile = documentDirectory.appending("/seen.plist") commentsFile = documentDirectory.appending("/comments.plist") let config = Realm.Configuration( schemaVersion: 4, migrationBlock: { migration, oldSchemaVersion in if (oldSchemaVersion < 4) { } }) Realm.Configuration.defaultConfiguration = config application.setMinimumBackgroundFetchInterval(TimeInterval.init(900)) let fileManager = FileManager.default if(!fileManager.fileExists(atPath: seenFile!)){ if let bundlePath = Bundle.main.path(forResource: "seen", ofType: "plist"){ _ = NSMutableDictionary(contentsOfFile: bundlePath) do{ try fileManager.copyItem(atPath: bundlePath, toPath: seenFile!) }catch{ print("copy failure.") } }else{ print("file myData.plist not found.") } }else{ print("file myData.plist already exits at path.") } if(!fileManager.fileExists(atPath: commentsFile!)){ if let bundlePath = Bundle.main.path(forResource: "comments", ofType: "plist"){ _ = NSMutableDictionary(contentsOfFile: bundlePath) do{ try fileManager.copyItem(atPath: bundlePath, toPath: commentsFile!) }catch{ print("copy failure.") } }else{ print("file myData.plist not found.") } }else{ print("file myData.plist already exits at path.") } session = Session() History.seenTimes = NSMutableDictionary.init(contentsOfFile: seenFile!)! History.commentCounts = NSMutableDictionary.init(contentsOfFile: commentsFile!)! UIApplication.shared.statusBarStyle = .lightContent SettingValues.initialize() FontGenerator.initialize() AccountController.initialize() PostFilter.initialize() Drafts.initialize() Subscriptions.sync(name: AccountController.currentName, completion: nil) if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in if((error) != nil){ print(error!.localizedDescription) } } UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in if((error) != nil){ print(error!.localizedDescription) } } UIApplication.shared.registerForRemoteNotifications() } else { // Fallback on earlier versions } if !UserDefaults.standard.bool(forKey: "sc" + name){ syncColors(subredditController: nil) } ColorUtil.doInit() let textAttributes = [NSForegroundColorAttributeName:UIColor.white] UINavigationBar.appearance().titleTextAttributes = textAttributes statusBar.frame = CGRect(x: 0, y: 0, width: (self.window?.frame.size.width)!, height: 20) statusBar.backgroundColor = UIColor.black.withAlphaComponent(0.15) self.window?.rootViewController?.view.addSubview(statusBar) return true } var statusBar = UIView() func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if let session = session { do { let request = try session.requestForGettingProfile() let fetcher = BackgroundFetch(current: session, request: request, taskHandler: { (response, dataURL, error) -> Void in print("Doing") if let response = response, let dataURL = dataURL { if response.statusCode == HttpStatus.ok.rawValue { do { let data = try Data(contentsOf: dataURL) let result = accountInResult(from: data, response: response) switch result { case .success(let account): print(account) UIApplication.shared.applicationIconBadgeNumber = account.inboxCount self.postLocalNotification("You have \(account.inboxCount) new messages.") completionHandler(.newData) return case .failure(let error): print(error) self.postLocalNotification("\(error)") completionHandler(.failed) } } catch { } } else { self.postLocalNotification("response code \(response.statusCode)") completionHandler(.failed) } } else { self.postLocalNotification("Error can not parse response and data.") completionHandler(.failed) } }) fetcher.resume() self.fetcher = fetcher } catch { print(error.localizedDescription) postLocalNotification("\(error)") completionHandler(.failed) } } else { print("Fail") postLocalNotification("session is not available.") completionHandler(.failed) } } func postLocalNotification(_ message: String) { if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = "New messages!" content.body = message content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false) let identifier = "SlideMSGNotif" let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) center.add(request, withCompletionHandler: { (error) in if error != nil { print(error!.localizedDescription) // Something went wrong } }) } else { // Fallback on earlier versions } } func syncColors(subredditController: SubredditsViewController?) { let defaults = UserDefaults.standard var toReturn: [String] = [] defaults.set(true, forKey: "sc" + name) defaults.synchronize() do { if(!AccountController.isLoggedIn){ try session?.getSubreddit(.default, paginator:paginator, completion: { (result) -> Void in switch result { case .failure: print(result.error!) case .success(let listing): self.subreddits += listing.children.flatMap({$0 as? Subreddit}) self.paginator = listing.paginator for sub in self.subreddits{ toReturn.append(sub.displayName) if(!sub.keyColor.isEmpty){ let color = (UIColor.init(hexString: sub.keyColor)) if(defaults.object(forKey: "color" + sub.displayName) == nil){ defaults.setColor(color: color , forKey: "color+" + sub.displayName) } } } } if(subredditController != nil){ DispatchQueue.main.async (execute: { () -> Void in subredditController?.complete(subs: toReturn) }) } }) } else { Subscriptions.getSubscriptionsFully(session: session!, completion: { (subs, multis) in for sub in subs { toReturn.append(sub.displayName) if(!sub.keyColor.isEmpty){ let color = (UIColor.init(hexString: sub.keyColor)) if(defaults.object(forKey: "color" + sub.displayName) == nil){ defaults.setColor(color: color , forKey: "color+" + sub.displayName) } } } for m in multis { toReturn.append("/m/" + m.displayName) if(!m.keyColor.isEmpty){ let color = (UIColor.init(hexString: m.keyColor)) if(defaults.object(forKey: "color" + m.displayName) == nil){ defaults.setColor(color: color , forKey: "color+" + m.displayName) } } } toReturn = toReturn.sorted{ $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending } toReturn.insert("all", at: 0) toReturn.insert("slide_ios", at: 0) toReturn.insert("frontpage", at: 0) if(subredditController != nil){ DispatchQueue.main.async (execute: { () -> Void in subredditController?.complete(subs: toReturn) }) } }) } } catch { print(error) if(subredditController != nil){ DispatchQueue.main.async (execute: { () -> Void in subredditController?.complete(subs: toReturn) }) } } } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { print("Returning \(url.absoluteString)") var parameters: [String:String] = url.getKeyVals()! if let code = parameters["code"], let state = parameters["state"] { print(state) if code.characters.count > 0 { print(code) } } return OAuth2Authorizer.sharedInstance.receiveRedirect(url, completion: {(result) -> Void in print(result) switch result { case .failure(let error): print(error) case .success(let token): DispatchQueue.main.async(execute: { () -> Void in do { try OAuth2TokenRepository.save(token: token, of: token.name) self.login?.setToken(token: token) NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil) } catch { NotificationCenter.default.post(name: OAuth2TokenRepositoryDidFailToSaveTokenName, object: nil, userInfo: nil) print(error) } }) } }) } func killAndReturn(){ if let rootViewController = UIApplication.topViewController() { var navigationArray = rootViewController.viewControllers navigationArray.removeAll() rootViewController.viewControllers = navigationArray rootViewController.pushViewController(SubredditsViewController(coder: NSCoder.init())!, animated: false) } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { print("background") History.seenTimes.write(toFile: seenFile!, atomically: true) History.commentCounts.write(toFile: commentsFile!, atomically: true) // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { self.refreshSession() } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { History.seenTimes.write(toFile: seenFile!, atomically: true) History.commentCounts.write(toFile: commentsFile!, atomically: true) // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func refreshSession() { // refresh current session token do { try self.session?.refreshToken({ (result) -> Void in switch result { case .failure(let error): print(error) case .success(let token): DispatchQueue.main.async(execute: { () -> Void in print(token) NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil) }) } }) } catch { print(error) } } func reloadSession() { // reddit username is save NSUserDefaults using "currentName" key. // create an authenticated or anonymous session object if let currentName = UserDefaults.standard.object(forKey: "name") as? String { do { let token = try OAuth2TokenRepository.token(of: currentName) self.session = Session(token: token) self.refreshSession() } catch { print(error) } } else { self.session = Session() } NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil) } } extension UIApplication { class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UINavigationController? { if let nav = base as? UINavigationController { return nav } if let tab = base as? UITabBarController { let moreNavigationController = tab.moreNavigationController return moreNavigationController } if let presented = base?.presentedViewController { return topViewController(base: presented) } return base?.navigationController } } extension URL { func getKeyVals() -> Dictionary<String, String>? { var results = [String:String]() let keyValues = self.query?.components(separatedBy: "&") if (keyValues?.count)! > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results.updateValue(kv[1], forKey: kv[0]) } } } return results } }
b7f03833ae0393d340be85f4faa0e7da
44.49642
285
0.524681
false
false
false
false
mpullman/ios-charts
refs/heads/master
Charts/Classes/Renderers/D3BarChartRenderer.swift
apache-2.0
1
// // BarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit @objc public protocol D3BarChartRendererDelegate { func barChartRendererData(renderer: D3BarChartRenderer) -> BarChartData! func barChartRenderer(renderer: D3BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func barChartRendererMaxVisibleValueCount(renderer: D3BarChartRenderer) -> Int func barChartDefaultRendererValueFormatter(renderer: D3BarChartRenderer) -> NSNumberFormatter! func barChartRendererChartYMax(renderer: D3BarChartRenderer) -> Double func barChartRendererChartYMin(renderer: D3BarChartRenderer) -> Double func barChartRendererChartXMax(renderer: D3BarChartRenderer) -> Double func barChartRendererChartXMin(renderer: D3BarChartRenderer) -> Double func barChartIsDrawHighlightArrowEnabled(renderer: D3BarChartRenderer) -> Bool func barChartIsDrawValueAboveBarEnabled(renderer: D3BarChartRenderer) -> Bool func barChartIsDrawBarShadowEnabled(renderer: D3BarChartRenderer) -> Bool func barChartIsInverted(renderer: D3BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool } public class D3BarChartRenderer: ChartDataRendererBase { public weak var delegate: D3BarChartRendererDelegate? public init(delegate: D3BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(#context: CGContext) { var barData = delegate!.barChartRendererData(self) if (barData === nil) { return } for (var i = 0; i < barData.dataSetCount; i++) { var set = barData.getDataSetByIndex(i) if set !== nil && set!.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set as! BarChartDataSet, index: i) } } } internal func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int) { CGContextSaveGState(context) var barData = delegate!.barChartRendererData(self) var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self) var dataSetOffset = (barData.dataSetCount - 1) var groupSpace = barData.groupSpace var groupSpaceHalf = groupSpace / 2.0 var barSpace = dataSet.barSpace var barSpaceHalf = barSpace / 2.0 var containsStacks = dataSet.isStacked var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var barWidth: CGFloat = 0.5 var phaseY = _animator.phaseY var barRect = CGRect() var barShadow = CGRect() var y: Double // do the drawing for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(j) + groupSpaceHalf var vals = e.values if (!containsStacks || vals == nil) { y = e.value var left = x - barWidth + barSpaceHalf var right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextFillRect(context, barRect) } else { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value var left = x - barWidth + barSpaceHalf var right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) barShadow.origin.x = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // fill the stack for (var k = 0; k < vals!.count; k++) { let value = vals![k] if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } var left = x - barWidth + barSpaceHalf var right = x + barWidth - barSpaceHalf var top: CGFloat, bottom: CGFloat if isInverted { bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart) top = y <= yStart ? CGFloat(y) : CGFloat(yStart) } else { top = y >= yStart ? CGFloat(y) : CGFloat(yStart) bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart) } // multiply the height of the rect with the phase top *= phaseY bottom *= phaseY barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextFillRect(context, barRect) } } } CGContextRestoreGState(context) } /// Prepares a bar for being highlighted. internal func prepareBarHighlight(#x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5 var left = x - barWidth + barspacehalf var right = x + barWidth - barspacehalf var top = CGFloat(y1) var bottom = CGFloat(y2) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixel(&rect, phaseY: _animator.phaseY) } public override func drawValues(#context: CGContext) { // if values are drawn if (passesCheck()) { var barData = delegate!.barChartRendererData(self) var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self) var dataSets = barData.dataSets var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self) var posOffset: CGFloat var negOffset: CGFloat for (var i = 0, count = barData.dataSetCount; i < count; i++) { var dataSet = dataSets[i] as! BarChartDataSet if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) // calculate the correct offset depending on the draw position of the value let valueOffsetPlus: CGFloat = 4.5 var valueFont = dataSet.valueFont var valueTextHeight = valueFont.lineHeight posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus) negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)) if (isInverted) { posOffset = -posOffset - valueTextHeight negOffset = -negOffset - valueTextHeight } var valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i) // if only single values are drawn (sum) if (!dataSet.isStacked) { for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsRight(valuePoints[j].x)) { break } if (!viewPortHandler.isInBoundsY(valuePoints[j].y) || !viewPortHandler.isInBoundsLeft(valuePoints[j].x)) { continue } var val = entries[j].value drawValue(context: context, value: formatter!.stringFromNumber(val)!, xPos: valuePoints[j].x, yPos: valuePoints[j].y + (val >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor) } } else { // if we have stacks for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { var e = entries[j] let values = e.values // we still draw stacked bars, but there is one non-stacked in between if (values == nil) { if (!viewPortHandler.isInBoundsRight(valuePoints[j].x)) { break } if (!viewPortHandler.isInBoundsY(valuePoints[j].y) || !viewPortHandler.isInBoundsLeft(valuePoints[j].x)) { continue } drawValue(context: context, value: formatter!.stringFromNumber(e.value)!, xPos: valuePoints[j].x, yPos: valuePoints[j].y + (e.value >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor) } else { // draw stack values let vals = values! var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for (var k = 0; k < vals.count; k++) { let value = vals[k] var y: Double if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: 0.0, y: CGFloat(y) * _animator.phaseY)) } trans.pointValuesToPixel(&transformed) for (var k = 0; k < transformed.count; k++) { var x = valuePoints[j].x var y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset) if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)) { continue } drawValue(context: context, value: formatter!.stringFromNumber(vals[k])!, xPos: x, yPos: y, font: valueFont, align: .Center, color: valueTextColor) } } } } } } } /// Draws a value at the specified x and y position. internal func drawValue(#context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor) { ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color]) } public override func drawExtras(#context: CGContext) { } private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint()) public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { var barData = delegate!.barChartRendererData(self) if (barData === nil) { return } CGContextSaveGState(context) var setCount = barData.dataSetCount var drawHighlightArrowEnabled = delegate!.barChartIsDrawHighlightArrowEnabled(self) var barRect = CGRect() for (var i = 0; i < indices.count; i++) { var h = indices[i] var index = h.xIndex var dataSetIndex = h.dataSetIndex var set = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } var barspaceHalf = set.barSpace / 2.0 var trans = delegate!.barChartRenderer(self, transformerForAxis: set.axisDependency) CGContextSetFillColorWithColor(context, set.colorAt(index).CGColor) CGContextSetAlpha(context, set.highLightAlpha) // check outofbounds if (CGFloat(index) < (CGFloat(delegate!.barChartRendererChartXMax(self)) * _animator.phaseX) / CGFloat(setCount)) { var e = set.entryForXIndex(index) as! BarChartDataEntry! if (e === nil || e.xIndex != index) { continue } var groupspace = barData.groupSpace var isStack = h.stackIndex < 0 ? false : true // calculate the correct x-position var x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index) let y1: Double let y2: Double if (isStack) { y1 = h.range?.from ?? 0.0 y2 = (h.range?.to ?? 0.0) * Double(_animator.phaseY) } else { y1 = e.value y2 = 0.0 } prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect) CGContextFillRect(context, barRect) if (drawHighlightArrowEnabled) { CGContextSetAlpha(context, 1.0) // distance between highlight arrow and bar var offsetY = _animator.phaseY * 0.07 CGContextSaveGState(context) var pixelToValueMatrix = trans.pixelToValueMatrix var xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c)) var arrowWidth = set.barSpace / 2.0 var arrowHeight = arrowWidth * xToYRel let yArrow = y1 > -y2 ? y1 : y1; _highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4 _highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY _highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight _highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight trans.pointValuesToPixel(&_highlightArrowPtsBuffer) CGContextBeginPath(context) CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y) CGContextClosePath(context) CGContextFillPath(context) CGContextRestoreGState(context) } } } CGContextRestoreGState(context) } public func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint] { return trans.generateTransformedValuesBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY) } internal func passesCheck() -> Bool { var barData = delegate!.barChartRendererData(self) if (barData === nil) { return false } return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX } }
20af6b013d49f9a788c2177cc824b734
40.281834
232
0.459571
false
false
false
false
creatubbles/ctb-api-swift
refs/heads/develop
CreatubblesAPIClientIntegrationTests/Spec/User Followings/DeleteAUserFollowingResponseHandlerSpec.swift
mit
1
// // DeleteAUserFollowingResponseHandler.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 Quick import Nimble @testable import CreatubblesAPIClient class DeleteAUserFollowingResponseHandlerSpec: QuickSpec { fileprivate let userId = TestConfiguration.testUserIdentifier override func spec() { describe("Delete A User following Response Handler") { let deleteAUserFollowing = DeleteAUserFollowingRequest(userId: self.userId!) it("Should return correct value after login") { let sender = TestComponentsFactory.requestSender waitUntil(timeout: TestConfiguration.timeoutMedium) { done in _ = sender.login(TestConfiguration.username, password: TestConfiguration.password) { (error: Error?) -> Void in expect(error).to(beNil()) _ = sender.send(deleteAUserFollowing, withResponseHandler:DeleteAUserFollowingResponseHandler { (error: Error?) -> Void in expect(error).to(beNil()) done() }) } } } it("Should return error when not logged in") { let sender = TestComponentsFactory.requestSender sender.logout() waitUntil(timeout: TestConfiguration.timeoutShort) { done in _ = sender.send(deleteAUserFollowing, withResponseHandler:DeleteAUserFollowingResponseHandler { (error: Error?) -> Void in expect(error).notTo(beNil()) done() }) } } } } }
3e076f66fc1a3d30553f723297d71f67
42.880597
119
0.621769
false
true
false
false
64characters/Telephone
refs/heads/master
UseCasesTestDoubles/CallHistoriesSpy.swift
gpl-3.0
1
// // CallHistoriesSpy.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UseCases public final class CallHistoriesSpy { public private(set) var didCallRemove = false public private(set) var invokedUUID = "" private let histories: [String: CallHistory] public init(histories: [String: CallHistory]) { self.histories = histories } } extension CallHistoriesSpy: CallHistories { public func history(withUUID uuid: String) -> CallHistory { return histories[uuid]! } public func remove(withUUID uuid: String) { didCallRemove = true invokedUUID = uuid } }
43fcbd4275dd95d2ddbbd69eaf88232e
28.195122
72
0.706767
false
false
false
false
GENG-GitHub/weibo-gd
refs/heads/master
GDWeibo/Class/Module/Discover/Controller/GDDiscoverViewController.swift
apache-2.0
1
// // GDDiscoverViewController.swift // GDWeibo // // Created by geng on 15/10/27. // Copyright © 2015年 geng. All rights reserved. // import UIKit class GDDiscoverViewController: GDBasicViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
ff51734eca124ddbf5dbad207a4c279f
32.989474
157
0.6869
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Tests/DoggieTests/XMLTest.swift
mit
1
// // XMLTest.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Doggie import XCTest class XMLTest: XCTestCase { func testXMLA() { let xmlString = """ <?xml version="1.0" encoding="utf-8" standalone="yes"?> <D:propfind xmlns:D="DAV:"> <D:prop> <D:getlastmodified></D:getlastmodified> <D:getcontentlength></D:getcontentlength> <D:creationdate></D:creationdate> <D:resourcetype></D:resourcetype> </D:prop> </D:propfind> """ do { let doc = try SDXMLDocument(xml: xmlString) XCTAssertEqual(doc.count, 1) XCTAssertEqual(doc[0].name, "propfind") XCTAssertEqual(doc[0].namespace, "DAV:") XCTAssertEqual(doc[0].count, 1) XCTAssertEqual(doc[0][0].name, "prop") XCTAssertEqual(doc[0][0].namespace, "DAV:") XCTAssertEqual(doc[0][0].count, 4) XCTAssertEqual(doc[0][0][0].name, "getlastmodified") XCTAssertEqual(doc[0][0][0].namespace, "DAV:") XCTAssertEqual(doc[0][0][0].count, 0) XCTAssertEqual(doc[0][0][1].name, "getcontentlength") XCTAssertEqual(doc[0][0][1].namespace, "DAV:") XCTAssertEqual(doc[0][0][1].count, 0) XCTAssertEqual(doc[0][0][2].name, "creationdate") XCTAssertEqual(doc[0][0][2].namespace, "DAV:") XCTAssertEqual(doc[0][0][2].count, 0) XCTAssertEqual(doc[0][0][3].name, "resourcetype") XCTAssertEqual(doc[0][0][3].namespace, "DAV:") XCTAssertEqual(doc[0][0][3].count, 0) } catch { XCTFail("XML parser error: \(error)") } } }
333bf0e85b11c0ff60278a53f5add6e4
36.9375
81
0.592422
false
true
false
false
wikimedia/apps-ios-wikipedia
refs/heads/twn
Wikipedia/Code/Advanced Settings/InsertMediaLabelTableFooterView.swift
mit
1
final class InsertMediaLabelTableFooterView: SetupView, Themeable { private let label = UILabel() private let separator = UIView() init(text: String) { label.text = text super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func setup() { super.setup() separator.translatesAutoresizingMaskIntoConstraints = false addSubview(separator) let separatorLeadingConstraint = separator.leadingAnchor.constraint(equalTo: leadingAnchor) let separatorTrailingConstraint = separator.trailingAnchor.constraint(equalTo: trailingAnchor) let separatorTopConstraint = separator.topAnchor.constraint(equalTo: topAnchor) let separatorHeightConstraint = separator.heightAnchor.constraint(equalToConstant: 0.5) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) let labelLeadingConstraint = label.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 15) let labelTrailingConstraint = label.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -15) let labelBottomConstraint = label.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: 15) let labelTopConstraint = label.topAnchor.constraint(equalTo: topAnchor, constant: 5) NSLayoutConstraint.activate([separatorLeadingConstraint, separatorTrailingConstraint, separatorTopConstraint, separatorHeightConstraint, labelLeadingConstraint, labelTrailingConstraint, labelBottomConstraint, labelTopConstraint]) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) label.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection) } func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground label.backgroundColor = backgroundColor label.textColor = theme.colors.secondaryText separator.backgroundColor = theme.colors.border } override func layoutSubviews() { super.layoutSubviews() label.preferredMaxLayoutWidth = label.bounds.width } }
1abc72892466238aa91769f5c5787e86
47.729167
237
0.749038
false
false
false
false
Witcast/witcast-ios
refs/heads/develop
WiTcast/Model/ItemLocal.swift
apache-2.0
1
// // ItemLocal.swift // WiTcast // // Created by Tanakorn Phoochaliaw on 8/6/2560 BE. // Copyright © 2560 Tanakorn Phoochaliaw. All rights reserved. // import UIKit import RealmSwift class ItemLocal: Object { dynamic var episodeId = 0; dynamic var downloadStatus = "None"; dynamic var isFavourite = false; dynamic var downloadPath = ""; dynamic var downloadPercent = 0; dynamic var lastDulation = 0.0; override class func primaryKey() -> String { return "episodeId" } }
9c6414dfc19061b4db496874ec6f723f
20.958333
63
0.662239
false
false
false
false
Ehrippura/firefox-ios
refs/heads/master
Account/FxADeviceRegistration.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Deferred import Shared import SwiftyJSON private let log = Logger.syncLogger /// The current version of the device registration. We use this to re-register /// devices after we update what we send on device registration. private let DeviceRegistrationVersion = 2 public enum FxADeviceRegistrationResult { case registered case updated case alreadyRegistered } public enum FxADeviceRegistratorError: MaybeErrorType { case accountDeleted case currentDeviceNotFound case invalidSession case unknownDevice public var description: String { switch self { case .accountDeleted: return "Account no longer exists." case .currentDeviceNotFound: return "Current device not found." case .invalidSession: return "Session token was invalid." case .unknownDevice: return "Unknown device." } } } open class FxADeviceRegistration: NSObject, NSCoding { /// The device identifier identifying this device. A device is uniquely identified /// across the lifetime of a Firefox Account. public let id: String /// The version of the device registration. We use this to re-register /// devices after we update what we send on device registration. let version: Int /// The last time we successfully (re-)registered with the server. let lastRegistered: Timestamp init(id: String, version: Int, lastRegistered: Timestamp) { self.id = id self.version = version self.lastRegistered = lastRegistered } public convenience required init(coder: NSCoder) { let id = coder.decodeObject(forKey: "id") as! String let version = coder.decodeAsInt(forKey: "version") let lastRegistered = coder.decodeAsUInt64(forKey: "lastRegistered") self.init(id: id, version: version, lastRegistered: lastRegistered) } open func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(version, forKey: "version") aCoder.encode(NSNumber(value: lastRegistered), forKey: "lastRegistered") } open func toJSON() -> JSON { return JSON(object: [ "id": id, "version": version, "lastRegistered": lastRegistered, ]) } } open class FxADeviceRegistrator { open static func registerOrUpdateDevice(_ account: FirefoxAccount, sessionToken: NSData, client: FxAClient10? = nil) -> Deferred<Maybe<FxADeviceRegistrationResult>> { // If we've already registered, the registration version is up-to-date, *and* we've (re-)registered // within the last week, do nothing. We re-register weekly as a sanity check. if let registration = account.deviceRegistration, registration.version == DeviceRegistrationVersion && Date.now() < registration.lastRegistered + OneWeekInMilliseconds { return deferMaybe(FxADeviceRegistrationResult.alreadyRegistered) } let pushParams: FxADevicePushParams? if AppConstants.MOZ_FXA_PUSH, let pushRegistration = account.pushRegistration { let subscription = pushRegistration.defaultSubscription pushParams = FxADevicePushParams(callback: subscription.endpoint.absoluteString, publicKey: subscription.p256dhPublicKey, authKey: subscription.authKey) } else { pushParams = nil } let client = client ?? FxAClient10(authEndpoint: account.configuration.authEndpointURL, oauthEndpoint: account.configuration.oauthEndpointURL, profileEndpoint: account.configuration.profileEndpointURL) let name = DeviceInfo.defaultClientName() let device: FxADevice let registrationResult: FxADeviceRegistrationResult if let registration = account.deviceRegistration { device = FxADevice.forUpdate(name, id: registration.id, push: pushParams) registrationResult = FxADeviceRegistrationResult.updated } else { device = FxADevice.forRegister(name, type: "mobile", push: pushParams) registrationResult = FxADeviceRegistrationResult.registered } let registeredDevice = client.registerOrUpdate(device: device, withSessionToken: sessionToken) let registration: Deferred<Maybe<FxADeviceRegistration>> = registeredDevice.bind { result in if let device = result.successValue { return deferMaybe(FxADeviceRegistration(id: device.id!, version: DeviceRegistrationVersion, lastRegistered: Date.now())) } // Recover from the error -- if we can. if let error = result.failureValue as? FxAClientError, case .remote(let remoteError) = error { switch remoteError.code { case FxAccountRemoteError.DeviceSessionConflict: return recoverFromDeviceSessionConflict(account, client: client, sessionToken: sessionToken) case FxAccountRemoteError.InvalidAuthenticationToken: return recoverFromTokenError(account, client: client) case FxAccountRemoteError.UnknownDevice: return recoverFromUnknownDevice(account) default: break } } // Not an error we can recover from. Rethrow it and fall back to the failure handler. return deferMaybe(result.failureValue!) } // Post-recovery. We either registered or we didn't, but update the account either way. return registration.bind { result in switch result { case .success(let registration): account.deviceRegistration = registration.value return deferMaybe(registrationResult) case .failure(let error): log.error("Device registration failed: \(error.description)") if let registration = account.deviceRegistration { account.deviceRegistration = FxADeviceRegistration(id: registration.id, version: 0, lastRegistered: registration.lastRegistered) } return deferMaybe(error) } } } fileprivate static func recoverFromDeviceSessionConflict(_ account: FirefoxAccount, client: FxAClient10, sessionToken: NSData) -> Deferred<Maybe<FxADeviceRegistration>> { // FxA has already associated this session with a different device id. // Perhaps we were beaten in a race to register. Handle the conflict: // 1. Fetch the list of devices for the current user from FxA. // 2. Look for ourselves in the list. // 3. If we find a match, set the correct device id and device registration // version on the account data and return the correct device id. At next // sync or next sign-in, registration is retried and should succeed. log.warning("Device session conflict. Attempting to find the current device ID…") return client.devices(withSessionToken: sessionToken) >>== { response in guard let currentDevice = response.devices.find({ $0.isCurrentDevice }) else { return deferMaybe(FxADeviceRegistratorError.currentDeviceNotFound) } return deferMaybe(FxADeviceRegistration(id: currentDevice.id!, version: 0, lastRegistered: Date.now())) } } fileprivate static func recoverFromTokenError(_ account: FirefoxAccount, client: FxAClient10) -> Deferred<Maybe<FxADeviceRegistration>> { return client.status(forUID: account.uid) >>== { status in _ = account.makeDoghouse() if !status.exists { // TODO: Should be in an "I have an iOS account, but the FxA is gone." state. // This will do for now... return deferMaybe(FxADeviceRegistratorError.accountDeleted) } return deferMaybe(FxADeviceRegistratorError.invalidSession) } } fileprivate static func recoverFromUnknownDevice(_ account: FirefoxAccount) -> Deferred<Maybe<FxADeviceRegistration>> { // FxA did not recognize the device ID. Handle it by clearing the registration on the account data. // At next sync or next sign-in, registration is retried and should succeed. log.warning("Unknown device ID. Clearing the local device data.") account.deviceRegistration = nil return deferMaybe(FxADeviceRegistratorError.unknownDevice) } }
64267da4df60ce8faa80ca72a9e86910
46.255435
209
0.675101
false
false
false
false
antlr/antlr4
refs/heads/dev
runtime/Swift/Sources/Antlr4/tree/pattern/Chunk.swift
bsd-3-clause
6
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// /// A chunk is either a token tag, a rule tag, or a span of literal text within a /// tree pattern. /// /// The method _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#split(String)_ returns a list of /// chunks in preparation for creating a token stream by /// _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#tokenize(String)_. From there, we get a parse /// tree from with _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#compile(String, int)_. These /// chunks are converted to _org.antlr.v4.runtime.tree.pattern.RuleTagToken_, _org.antlr.v4.runtime.tree.pattern.TokenTagToken_, or the /// regular tokens of the text surrounding the tags. /// public class Chunk: Equatable { public static func ==(lhs: Chunk, rhs: Chunk) -> Bool { return lhs.isEqual(rhs) } public func isEqual(_ other: Chunk) -> Bool { return self === other } }
d27b7e8d317b5f9b583c93e1be94ab1b
38.428571
135
0.709239
false
false
false
false
nmdias/FeedParser
refs/heads/master
Sources/Model/RSS/Mappers/RSSFeed + Attributes Mapper.swift
mit
2
// // RSSFeed + Attributes Mapper.swift // // Copyright (c) 2016 Nuno Manuel Dias // // 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 extension RSSFeed { /** Maps the attributes of the specified dictionary for a given `RSSPath` to the `RSSFeed` model - parameter attributeDict: The attribute dictionary to map to the model - parameter path: The path of feed's element */ func map(attributes attributeDict: [String : String], forPath path: RSSPath) { switch path { case .RSSChannelItem: if self.items == nil { self.items = [] } self.items?.append(RSSFeedItem()) case .RSSChannelImage: if self.image == nil { self.image = RSSFeedImage() } case .RSSChannelSkipDays: if self.skipDays == nil { self.skipDays = [] } case .RSSChannelSkipHours: if self.skipHours == nil { self.skipHours = [] } case .RSSChannelTextInput: if self.textInput == nil { self.textInput = RSSFeedTextInput() } case .RSSChannelCategory: if self.categories == nil { self.categories = [] } self.categories?.append(RSSFeedCategory(attributes: attributeDict)) case .RSSChannelCloud: if self.cloud == nil { self.cloud = RSSFeedCloud(attributes: attributeDict) } case .RSSChannelItemCategory: if self.items?.last?.categories == nil { self.items?.last?.categories = [] } self.items?.last?.categories?.append(RSSFeedItemCategory(attributes: attributeDict)) case .RSSChannelItemEnclosure: if self.items?.last?.enclosure == nil { self.items?.last?.enclosure = RSSFeedItemEnclosure(attributes: attributeDict) } case .RSSChannelItemGUID: if self.items?.last?.guid == nil { self.items?.last?.guid = RSSFeedItemGUID(attributes: attributeDict) } case .RSSChannelItemSource: if self.items?.last?.source == nil { self.items?.last?.source = RSSFeedItemSource(attributes: attributeDict) } case .RSSChannelItemContentEncoded: if self.items?.last?.content == nil { self.items?.last?.content = ContentNamespace() } case .RSSChannelSyndicationUpdateBase, .RSSChannelSyndicationUpdatePeriod, .RSSChannelSyndicationUpdateFrequency: /// If the syndication variable has not been initialized yet, do it before assiging any values if self.syndication == nil { self.syndication = SyndicationNamespace() } case .RSSChannelDublinCoreTitle, .RSSChannelDublinCoreCreator, .RSSChannelDublinCoreSubject, .RSSChannelDublinCoreDescription, .RSSChannelDublinCorePublisher, .RSSChannelDublinCoreContributor, .RSSChannelDublinCoreDate, .RSSChannelDublinCoreType, .RSSChannelDublinCoreFormat, .RSSChannelDublinCoreIdentifier, .RSSChannelDublinCoreSource, .RSSChannelDublinCoreLanguage, .RSSChannelDublinCoreRelation, .RSSChannelDublinCoreCoverage, .RSSChannelDublinCoreRights: if self.dublinCore == nil { self.dublinCore = DublinCoreNamespace() } case .RSSChannelItemDublinCoreTitle, .RSSChannelItemDublinCoreCreator, .RSSChannelItemDublinCoreSubject, .RSSChannelItemDublinCoreDescription, .RSSChannelItemDublinCorePublisher, .RSSChannelItemDublinCoreContributor, .RSSChannelItemDublinCoreDate, .RSSChannelItemDublinCoreType, .RSSChannelItemDublinCoreFormat, .RSSChannelItemDublinCoreIdentifier, .RSSChannelItemDublinCoreSource, .RSSChannelItemDublinCoreLanguage, .RSSChannelItemDublinCoreRelation, .RSSChannelItemDublinCoreCoverage, .RSSChannelItemDublinCoreRights: /// If the dublin core variable has not been initialized yet, do it before assiging any values if self.items?.last?.dublinCore == nil { self.items?.last?.dublinCore = DublinCoreNamespace() } default: break } } }
421a44def6911aa7c903f8b49e08b3e3
32.736264
106
0.575501
false
false
false
false
jisudong/study
refs/heads/master
MyPlayground.playground/Pages/可选型.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation // 可选类型 // 当一个值可能存在,可能不存在的时候用可选类型 // 格式:类型名? class Person6 { var phone: String? } // 问号?表明phone的值是可选的,可能是一个String,也可能不存在(nil) // phone 默认值就是 nil,因此上面的语句相当于 var phone: String? = nil // 强制解包 // 使用感叹号!将可选类型的(包装)的值取出来 // 在可选类型的后面加一个感叹号!,就可以把可选类型(包装)的值取出来,赋值给具体类型 // 如果可选类型(包装)的值不存在,仍然强制解包,运行时会报错 var number: Int? = 10 var number1: Int = number! print(number ?? 0) print(number1) // 判断 if (number != nil) { } else { } if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber { print("\(firstNumber) < \(secondNumber)") } // 隐式解包 // 格式:将问号?换成感叹号! // 能够自动解包:自动把可选类型(包装)的值取出来赋给具体类型 var number3: Int! = 20 var number4: Int = number3 //自动解包,不用再使用! // map 和 flatMap class Student { var name: String? var age: Int? } let xm = Student() //xm.age = 3 xm.name = "小明" func isAdult(stu: Student) -> Bool? { return stu.age.map { // 当可选项不为空时,闭包被执行 print("map 被执行") // map 方法中的参数默认已经解包了,所以 $0 是 Int 类型 return $0 >= 18 ? true : false } } isAdult(stu: xm) func example(code: String) -> Student? { if code == "xm" { let xiaoming = Student() xiaoming.name = "小明" xiaoming.age = 12 return xiaoming } else if code == "xg" { let xiaogang = Student() xiaogang.name = "小刚" xiaogang.age = 15 return xiaogang } return nil } // result 是双重可选型 Bool?? let result = example(code: "xm").map { isAdult(stu: $0) } let resultA = result! // result1 是单重可选型 Bool? let result1 = example(code: "xm").flatMap { // print("flatMap 被执行") isAdult(stu: $0) }
8c2e6c442ac8fb57ca6cf812cb7ac3b5
16.763441
87
0.605932
false
false
false
false
justindarc/firefox-ios
refs/heads/master
ClientTests/TabManagerStoreTests.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @testable import Client import Shared import Storage import UIKit import WebKit import XCTest class TabManagerStoreTests: XCTestCase { let profile = TabManagerMockProfile() var manager: TabManager! let configuration = WKWebViewConfiguration() override func setUp() { super.setUp() manager = TabManager(profile: profile, imageStore: nil) configuration.processPool = WKProcessPool() if UIDevice.current.userInterfaceIdiom == .pad { // BVC.viewWillAppear() calls restoreTabs() which interferes with these tests. (On iPhone, ClientTests never dismiss the intro screen, on iPad the intro is a popover on the BVC). // Wait for this to happen (UIView.window only gets assigned after viewWillAppear()), then begin testing. let bvc = (UIApplication.shared.delegate as! AppDelegate).browserViewController let predicate = XCTNSPredicateExpectation(predicate: NSPredicate(format: "view.window != nil"), object: bvc) wait(for: [predicate], timeout: 20) } manager.testClearArchive() } override func tearDown() { super.tearDown() } // Without session data, a Tab can't become a SavedTab and get archived func addTabWithSessionData(isPrivate: Bool = false) { let tab = Tab(configuration: configuration, isPrivate: isPrivate) tab.url = URL(string: "http://yahoo.com")! manager.configureTab(tab, request: URLRequest(url: tab.url!), flushToDisk: false, zombie: false) tab.sessionData = SessionData(currentPage: 0, urls: [tab.url!], lastUsedTime: Date.now()) } func testNoData() { XCTAssertEqual(manager.testTabCountOnDisk(), 0, "Expected 0 tabs on disk") XCTAssertEqual(manager.testCountRestoredTabs(), 0) } func testPrivateTabsAreArchived() { for _ in 0..<2 { addTabWithSessionData(isPrivate: true) } let e = expectation(description: "saved") manager.storeChanges().uponQueue(.main) {_ in XCTAssertEqual(self.manager.testTabCountOnDisk(), 2) e.fulfill() } waitForExpectations(timeout: 2, handler: nil) } func testAddedTabsAreStored() { // Add 2 tabs for _ in 0..<2 { addTabWithSessionData() } var e = expectation(description: "saved") manager.storeChanges().uponQueue(.main) { _ in XCTAssertEqual(self.manager.testTabCountOnDisk(), 2) e.fulfill() } waitForExpectations(timeout: 2, handler: nil) // Add 2 more for _ in 0..<2 { addTabWithSessionData() } e = expectation(description: "saved") manager.storeChanges().uponQueue(.main) { _ in XCTAssertEqual(self.manager.testTabCountOnDisk(), 4) e.fulfill() } waitForExpectations(timeout: 2, handler: nil) // Remove all tabs, and add just 1 tab manager.removeAll() addTabWithSessionData() e = expectation(description: "saved") manager.storeChanges().uponQueue(.main) {_ in XCTAssertEqual(self.manager.testTabCountOnDisk(), 1) e.fulfill() } waitForExpectations(timeout: 2, handler: nil) } }
1bc0008729e7b6ff99d6619127df5a3a
33.80198
190
0.63357
false
true
false
false
VladiMihaylenko/omim
refs/heads/master
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RoutePreviewStatus/TransportTransitSteps/TransportTransitStepsCollectionView.swift
apache-2.0
14
final class TransportTransitStepsCollectionView: UICollectionView { var steps: [MWMRouterTransitStepInfo] = [] { didSet { reloadData() } } override var frame: CGRect { didSet { collectionViewLayout.invalidateLayout() } } override var bounds: CGRect { didSet { collectionViewLayout.invalidateLayout() } } override func awakeFromNib() { super.awakeFromNib() dataSource = self [TransportTransitIntermediatePoint.self, TransportTransitPedestrian.self, TransportTransitTrain.self].forEach { register(cellClass: $0) } } private func cellClass(item: Int) -> TransportTransitCell.Type { let step = steps[item] switch step.type { case .intermediatePoint: return TransportTransitIntermediatePoint.self case .pedestrian: return TransportTransitPedestrian.self case .train: fallthrough case .subway: fallthrough case .lightRail: fallthrough case .monorail: return TransportTransitTrain.self } } func estimatedCellSize(item: Int) -> CGSize { return cellClass(item: item).estimatedCellSize(step: steps[item]) } } extension TransportTransitStepsCollectionView: UICollectionViewDataSource { func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return steps.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = indexPath.item let cellClass = self.cellClass(item: item) let cell = collectionView.dequeueReusableCell(withCellClass: cellClass, indexPath: indexPath) as! TransportTransitCell cell.config(step: steps[item]) return cell } }
f300635f47eb8b5274367ca783b75624
28.77193
122
0.727755
false
false
false
false
katfang/swift-overview
refs/heads/master
11-protocols-extensions.playground/section-1.swift
mit
1
import UIKit // for pow // --- Protocols and Extensions // struct definitions from 06-structs-classes struct Point { var x = 0.0 var y = 0.0 } struct Size { var width = 0.0, height = 0.0 } let s = Size(width: 2, height: 2) struct Rect { var origin = Point() var size = Size() // -- computed properties var upperLeft: Point { get { let x = origin.x - (size.width/2) let y = origin.y + (size.height/2) return Point(x: x, y: y) } set (newLeft) { origin.x = newLeft.x + size.width/2 origin.y = newLeft.y - size.height/2 } } // -- struct func func description() -> String { return "Rectangle with origin \(origin) and size \(size)" } // -- mutating func mutating func moveRight() { origin.x += 1 } // -- static func static func unitSquareAtOrigin(origin:Point) -> Rect { return Rect(origin: origin, size:Size(width:1, height:1)) } } // -- Protocol // * protocols can be added to structs and classes // * can define property (must say get and/or set) // * can define function protocol HasColor { var color: (Float, Float, Float, Float) { get set } } protocol RoundChecker { func isRound() -> Bool } protocol HasArea { var area: Double { get } } // Classes can adopt protocols class Circle: HasColor, RoundChecker { var radius: Double = 1 var color: (Float, Float, Float, Float) init(color: (Float, Float, Float, Float)) { self.color = color } func isRound() -> Bool { return true } } // Storing something that adopts a protocol var circle1: HasColor = Circle(color: (1, 1, 1, 1)) circle1.color // circle1() // Errors, isRound() isn't part of HasColor protocol (circle1 as Circle).isRound() // Storing object that adopts multiple protocols var circle2: protocol<HasColor, RoundChecker> = Circle(color: (1, 1, 1, 1)) circle2.color circle2.isRound() // -- Extensions // * Allow you to add methods and computed properties to classes, structs // * Cannot add new stored properties // add new protocol to class extension Circle: HasArea { var area: Double { return 3.14159 * pow(radius, 2) } } // add new protocol extension Rect : HasArea { var area: Double { return size.width * size.height } } // add new function extension Rect { mutating func moveLeft() { origin.x -= 1 } } var r = Rect.unitSquareAtOrigin(Point(x: 0,y: 0)) r.area // add initializer extension Point { init(_ x: Double, _ y: Double) { self.x = x self.y = y } } var q = Point(0,0)
3a2933ca9903e40dd1a563cd230dc880
20.878049
75
0.597398
false
false
false
false
haitran2011/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat.Shared/Emojione.swift
mit
2
// // Emojione.swift // // Created by Rafael Kellermann Streit (@rafaelks) on 10/10/16. // Copyright (c) 2016. // import Foundation // swiftlint:disable type_body_length // swiftlint:disable file_length struct Emojione { static let values = [ "100": "\u{0001f4af}", "1234": "\u{0001f522}", "grinning": "\u{0001f600}", "grimacing": "\u{0001f62c}", "grin": "\u{0001f601}", "joy": "\u{0001f602}", "smiley": "\u{0001f603}", "smile": "\u{0001f604}", "sweat_smile": "\u{0001f605}", "laughing": "\u{0001f606}", "innocent": "\u{0001f607}", "wink": "\u{0001f609}", "blush": "\u{0001f60a}", "slight_smile": "\u{0001f642}", "upside_down": "\u{0001f643}", "relaxed": "\u{0000263a}", "yum": "\u{0001f60b}", "relieved": "\u{0001f60c}", "heart_eyes": "\u{0001f60d}", "kissing_heart": "\u{0001f618}", "kissing": "\u{0001f617}", "kissing_smiling_eyes": "\u{0001f619}", "kissing_closed_eyes": "\u{0001f61a}", "stuck_out_tongue_winking_eye": "\u{0001f61c}", "stuck_out_tongue_closed_eyes": "\u{0001f61d}", "stuck_out_tongue": "\u{0001f61b}", "money_mouth": "\u{0001f911}", "nerd": "\u{0001f913}", "sunglasses": "\u{0001f60e}", "hugging": "\u{0001f917}", "smirk": "\u{0001f60f}", "no_mouth": "\u{0001f636}", "neutral_face": "\u{0001f610}", "expressionless": "\u{0001f611}", "unamused": "\u{0001f612}", "rolling_eyes": "\u{0001f644}", "thinking": "\u{0001f914}", "flushed": "\u{0001f633}", "disappointed": "\u{0001f61e}", "worried": "\u{0001f61f}", "angry": "\u{0001f620}", "rage": "\u{0001f621}", "pensive": "\u{0001f614}", "confused": "\u{0001f615}", "slight_frown": "\u{0001f641}", "frowning2": "\u{00002639}", "persevere": "\u{0001f623}", "confounded": "\u{0001f616}", "tired_face": "\u{0001f62b}", "weary": "\u{0001f629}", "triumph": "\u{0001f624}", "open_mouth": "\u{0001f62e}", "scream": "\u{0001f631}", "fearful": "\u{0001f628}", "cold_sweat": "\u{0001f630}", "hushed": "\u{0001f62f}", "frowning": "\u{0001f626}", "anguished": "\u{0001f627}", "cry": "\u{0001f622}", "disappointed_relieved": "\u{0001f625}", "sleepy": "\u{0001f62a}", "sweat": "\u{0001f613}", "sob": "\u{0001f62d}", "dizzy_face": "\u{0001f635}", "astonished": "\u{0001f632}", "zipper_mouth": "\u{0001f910}", "mask": "\u{0001f637}", "thermometer_face": "\u{0001f912}", "head_bandage": "\u{0001f915}", "sleeping": "\u{0001f634}", "zzz": "\u{0001f4a4}", "poop": "\u{0001f4a9}", "smiling_imp": "\u{0001f608}", "imp": "\u{0001f47f}", "japanese_ogre": "\u{0001f479}", "japanese_goblin": "\u{0001f47a}", "skull": "\u{0001f480}", "ghost": "\u{0001f47b}", "alien": "\u{0001f47d}", "robot": "\u{0001f916}", "smiley_cat": "\u{0001f63a}", "smile_cat": "\u{0001f638}", "joy_cat": "\u{0001f639}", "heart_eyes_cat": "\u{0001f63b}", "smirk_cat": "\u{0001f63c}", "kissing_cat": "\u{0001f63d}", "scream_cat": "\u{0001f640}", "crying_cat_face": "\u{0001f63f}", "pouting_cat": "\u{0001f63e}", "raised_hands": "\u{0001f64c}", "clap": "\u{0001f44f}", "wave": "\u{0001f44b}", "thumbsup": "\u{0001f44d}", "thumbsdown": "\u{0001f44e}", "punch": "\u{0001f44a}", "fist": "\u{0000270a}", "v": "\u{0000270c}", "ok_hand": "\u{0001f44c}", "raised_hand": "\u{0000270b}", "open_hands": "\u{0001f450}", "muscle": "\u{0001f4aa}", "pray": "\u{0001f64f}", "point_up": "\u{0000261d}", "point_up_2": "\u{0001f446}", "point_down": "\u{0001f447}", "point_left": "\u{0001f448}", "point_right": "\u{0001f449}", "middle_finger": "\u{0001f595}", "hand_splayed": "\u{0001f590}", "metal": "\u{0001f918}", "vulcan": "\u{0001f596}", "writing_hand": "\u{0000270d}", "nail_care": "\u{0001f485}", "lips": "\u{0001f444}", "tongue": "\u{0001f445}", "ear": "\u{0001f442}", "nose": "\u{0001f443}", "eye": "\u{0001f441}", "eyes": "\u{0001f440}", "bust_in_silhouette": "\u{0001f464}", "busts_in_silhouette": "\u{0001f465}", "speaking_head": "\u{0001f5e3}", "baby": "\u{0001f476}", "boy": "\u{0001f466}", "girl": "\u{0001f467}", "man": "\u{0001f468}", "woman": "\u{0001f469}", "person_with_blond_hair": "\u{0001f471}", "older_man": "\u{0001f474}", "older_woman": "\u{0001f475}", "man_with_gua_pi_mao": "\u{0001f472}", "man_with_turban": "\u{0001f473}", "cop": "\u{0001f46e}", "construction_worker": "\u{0001f477}", "guardsman": "\u{0001f482}", "spy": "\u{0001f575}", "santa": "\u{0001f385}", "angel": "\u{0001f47c}", "princess": "\u{0001f478}", "bride_with_veil": "\u{0001f470}", "walking": "\u{0001f6b6}", "runner": "\u{0001f3c3}", "dancer": "\u{0001f483}", "dancers": "\u{0001f46f}", "couple": "\u{0001f46b}", "two_men_holding_hands": "\u{0001f46c}", "two_women_holding_hands": "\u{0001f46d}", "bow": "\u{0001f647}", "information_desk_person": "\u{0001f481}", "no_good": "\u{0001f645}", "ok_woman": "\u{0001f646}", "raising_hand": "\u{0001f64b}", "person_with_pouting_face": "\u{0001f64e}", "person_frowning": "\u{0001f64d}", "haircut": "\u{0001f487}", "massage": "\u{0001f486}", "couple_with_heart": "\u{0001f491}", "couple_ww": "\u{0001f469}\u{00002764}\u{0001f469}", "couple_mm": "\u{0001f468}\u{00002764}\u{0001f468}", "couplekiss": "\u{0001f48f}", "kiss_ww": "\u{0001f469}\u{00002764}\u{0001f48b}\u{0001f469}", "kiss_mm": "\u{0001f468}\u{00002764}\u{0001f48b}\u{0001f468}", "family": "\u{0001f46a}", "family_mwg": "\u{0001f468}\u{0001f469}\u{0001f467}", "family_mwgb": "\u{0001f468}\u{0001f469}\u{0001f467}\u{0001f466}", "family_mwbb": "\u{0001f468}\u{0001f469}\u{0001f466}\u{0001f466}", "family_mwgg": "\u{0001f468}\u{0001f469}\u{0001f467}\u{0001f467}", "family_wwb": "\u{0001f469}\u{0001f469}\u{0001f466}", "family_wwg": "\u{0001f469}\u{0001f469}\u{0001f467}", "family_wwgb": "\u{0001f469}\u{0001f469}\u{0001f467}\u{0001f466}", "family_wwbb": "\u{0001f469}\u{0001f469}\u{0001f466}\u{0001f466}", "family_wwgg": "\u{0001f469}\u{0001f469}\u{0001f467}\u{0001f467}", "family_mmb": "\u{0001f468}\u{0001f468}\u{0001f466}", "family_mmg": "\u{0001f468}\u{0001f468}\u{0001f467}", "family_mmgb": "\u{0001f468}\u{0001f468}\u{0001f467}\u{0001f466}", "family_mmbb": "\u{0001f468}\u{0001f468}\u{0001f466}\u{0001f466}", "family_mmgg": "\u{0001f468}\u{0001f468}\u{0001f467}\u{0001f467}", "womans_clothes": "\u{0001f45a}", "shirt": "\u{0001f455}", "jeans": "\u{0001f456}", "necktie": "\u{0001f454}", "dress": "\u{0001f457}", "bikini": "\u{0001f459}", "kimono": "\u{0001f458}", "lipstick": "\u{0001f484}", "kiss": "\u{0001f48b}", "footprints": "\u{0001f463}", "high_heel": "\u{0001f460}", "sandal": "\u{0001f461}", "boot": "\u{0001f462}", "mans_shoe": "\u{0001f45e}", "athletic_shoe": "\u{0001f45f}", "womans_hat": "\u{0001f452}", "tophat": "\u{0001f3a9}", "helmet_with_cross": "\u{000026d1}", "mortar_board": "\u{0001f393}", "crown": "\u{0001f451}", "school_satchel": "\u{0001f392}", "pouch": "\u{0001f45d}", "purse": "\u{0001f45b}", "handbag": "\u{0001f45c}", "briefcase": "\u{0001f4bc}", "eyeglasses": "\u{0001f453}", "dark_sunglasses": "\u{0001f576}", "ring": "\u{0001f48d}", "closed_umbrella": "\u{0001f302}", "dog": "\u{0001f436}", "cat": "\u{0001f431}", "mouse": "\u{0001f42d}", "hamster": "\u{0001f439}", "rabbit": "\u{0001f430}", "bear": "\u{0001f43b}", "panda_face": "\u{0001f43c}", "koala": "\u{0001f428}", "tiger": "\u{0001f42f}", "lion_face": "\u{0001f981}", "cow": "\u{0001f42e}", "pig": "\u{0001f437}", "pig_nose": "\u{0001f43d}", "frog": "\u{0001f438}", "octopus": "\u{0001f419}", "monkey_face": "\u{0001f435}", "see_no_evil": "\u{0001f648}", "hear_no_evil": "\u{0001f649}", "speak_no_evil": "\u{0001f64a}", "monkey": "\u{0001f412}", "chicken": "\u{0001f414}", "penguin": "\u{0001f427}", "bird": "\u{0001f426}", "baby_chick": "\u{0001f424}", "hatching_chick": "\u{0001f423}", "hatched_chick": "\u{0001f425}", "wolf": "\u{0001f43a}", "boar": "\u{0001f417}", "horse": "\u{0001f434}", "unicorn": "\u{0001f984}", "bee": "\u{0001f41d}", "bug": "\u{0001f41b}", "snail": "\u{0001f40c}", "beetle": "\u{0001f41e}", "ant": "\u{0001f41c}", "spider": "\u{0001f577}", "scorpion": "\u{0001f982}", "crab": "\u{0001f980}", "snake": "\u{0001f40d}", "turtle": "\u{0001f422}", "tropical_fish": "\u{0001f420}", "fish": "\u{0001f41f}", "blowfish": "\u{0001f421}", "dolphin": "\u{0001f42c}", "whale": "\u{0001f433}", "whale2": "\u{0001f40b}", "crocodile": "\u{0001f40a}", "leopard": "\u{0001f406}", "tiger2": "\u{0001f405}", "water_buffalo": "\u{0001f403}", "ox": "\u{0001f402}", "cow2": "\u{0001f404}", "dromedary_camel": "\u{0001f42a}", "camel": "\u{0001f42b}", "elephant": "\u{0001f418}", "goat": "\u{0001f410}", "ram": "\u{0001f40f}", "sheep": "\u{0001f411}", "racehorse": "\u{0001f40e}", "pig2": "\u{0001f416}", "rat": "\u{0001f400}", "mouse2": "\u{0001f401}", "rooster": "\u{0001f413}", "turkey": "\u{0001f983}", "dove": "\u{0001f54a}", "dog2": "\u{0001f415}", "poodle": "\u{0001f429}", "cat2": "\u{0001f408}", "rabbit2": "\u{0001f407}", "chipmunk": "\u{0001f43f}", "feet": "\u{0001f43e}", "dragon": "\u{0001f409}", "dragon_face": "\u{0001f432}", "cactus": "\u{0001f335}", "christmas_tree": "\u{0001f384}", "evergreen_tree": "\u{0001f332}", "deciduous_tree": "\u{0001f333}", "palm_tree": "\u{0001f334}", "seedling": "\u{0001f331}", "herb": "\u{0001f33f}", "shamrock": "\u{00002618}", "four_leaf_clover": "\u{0001f340}", "bamboo": "\u{0001f38d}", "tanabata_tree": "\u{0001f38b}", "leaves": "\u{0001f343}", "fallen_leaf": "\u{0001f342}", "maple_leaf": "\u{0001f341}", "ear_of_rice": "\u{0001f33e}", "hibiscus": "\u{0001f33a}", "sunflower": "\u{0001f33b}", "rose": "\u{0001f339}", "tulip": "\u{0001f337}", "blossom": "\u{0001f33c}", "cherry_blossom": "\u{0001f338}", "bouquet": "\u{0001f490}", "mushroom": "\u{0001f344}", "chestnut": "\u{0001f330}", "jack_o_lantern": "\u{0001f383}", "shell": "\u{0001f41a}", "spider_web": "\u{0001f578}", "earth_americas": "\u{0001f30e}", "earth_africa": "\u{0001f30d}", "earth_asia": "\u{0001f30f}", "full_moon": "\u{0001f315}", "waning_gibbous_moon": "\u{0001f316}", "last_quarter_moon": "\u{0001f317}", "waning_crescent_moon": "\u{0001f318}", "new_moon": "\u{0001f311}", "waxing_crescent_moon": "\u{0001f312}", "first_quarter_moon": "\u{0001f313}", "waxing_gibbous_moon": "\u{0001f314}", "new_moon_with_face": "\u{0001f31a}", "full_moon_with_face": "\u{0001f31d}", "first_quarter_moon_with_face": "\u{0001f31b}", "last_quarter_moon_with_face": "\u{0001f31c}", "sun_with_face": "\u{0001f31e}", "crescent_moon": "\u{0001f319}", "star": "\u{00002b50}", "star2": "\u{0001f31f}", "dizzy": "\u{0001f4ab}", "sparkles": "\u{00002728}", "comet": "\u{00002604}", "sunny": "\u{00002600}", "white_sun_small_cloud": "\u{0001f324}", "partly_sunny": "\u{000026c5}", "white_sun_cloud": "\u{0001f325}", "white_sun_rain_cloud": "\u{0001f326}", "cloud": "\u{00002601}", "cloud_rain": "\u{0001f327}", "thunder_cloud_rain": "\u{000026c8}", "cloud_lightning": "\u{0001f329}", "zap": "\u{000026a1}", "fire": "\u{0001f525}", "boom": "\u{0001f4a5}", "snowflake": "\u{00002744}", "cloud_snow": "\u{0001f328}", "snowman2": "\u{00002603}", "snowman": "\u{000026c4}", "wind_blowing_face": "\u{0001f32c}", "dash": "\u{0001f4a8}", "cloud_tornado": "\u{0001f32a}", "fog": "\u{0001f32b}", "umbrella2": "\u{00002602}", "umbrella": "\u{00002614}", "droplet": "\u{0001f4a7}", "sweat_drops": "\u{0001f4a6}", "ocean": "\u{0001f30a}", "green_apple": "\u{0001f34f}", "apple": "\u{0001f34e}", "pear": "\u{0001f350}", "tangerine": "\u{0001f34a}", "lemon": "\u{0001f34b}", "banana": "\u{0001f34c}", "watermelon": "\u{0001f349}", "grapes": "\u{0001f347}", "strawberry": "\u{0001f353}", "melon": "\u{0001f348}", "cherries": "\u{0001f352}", "peach": "\u{0001f351}", "pineapple": "\u{0001f34d}", "tomato": "\u{0001f345}", "eggplant": "\u{0001f346}", "hot_pepper": "\u{0001f336}", "corn": "\u{0001f33d}", "sweet_potato": "\u{0001f360}", "honey_pot": "\u{0001f36f}", "bread": "\u{0001f35e}", "cheese": "\u{0001f9c0}", "poultry_leg": "\u{0001f357}", "meat_on_bone": "\u{0001f356}", "fried_shrimp": "\u{0001f364}", "cooking": "\u{0001f373}", "hamburger": "\u{0001f354}", "fries": "\u{0001f35f}", "hotdog": "\u{0001f32d}", "pizza": "\u{0001f355}", "spaghetti": "\u{0001f35d}", "taco": "\u{0001f32e}", "burrito": "\u{0001f32f}", "ramen": "\u{0001f35c}", "stew": "\u{0001f372}", "fish_cake": "\u{0001f365}", "sushi": "\u{0001f363}", "bento": "\u{0001f371}", "curry": "\u{0001f35b}", "rice_ball": "\u{0001f359}", "rice": "\u{0001f35a}", "rice_cracker": "\u{0001f358}", "oden": "\u{0001f362}", "dango": "\u{0001f361}", "shaved_ice": "\u{0001f367}", "ice_cream": "\u{0001f368}", "icecream": "\u{0001f366}", "cake": "\u{0001f370}", "birthday": "\u{0001f382}", "custard": "\u{0001f36e}", "candy": "\u{0001f36c}", "lollipop": "\u{0001f36d}", "chocolate_bar": "\u{0001f36b}", "popcorn": "\u{0001f37f}", "doughnut": "\u{0001f369}", "cookie": "\u{0001f36a}", "beer": "\u{0001f37a}", "beers": "\u{0001f37b}", "wine_glass": "\u{0001f377}", "cocktail": "\u{0001f378}", "tropical_drink": "\u{0001f379}", "champagne": "\u{0001f37e}", "sake": "\u{0001f376}", "tea": "\u{0001f375}", "coffee": "\u{00002615}", "baby_bottle": "\u{0001f37c}", "fork_and_knife": "\u{0001f374}", "fork_knife_plate": "\u{0001f37d}", "soccer": "\u{000026bd}", "basketball": "\u{0001f3c0}", "football": "\u{0001f3c8}", "baseball": "\u{000026be}", "tennis": "\u{0001f3be}", "volleyball": "\u{0001f3d0}", "rugby_football": "\u{0001f3c9}", "8ball": "\u{0001f3b1}", "golf": "\u{000026f3}", "golfer": "\u{0001f3cc}", "ping_pong": "\u{0001f3d3}", "badminton": "\u{0001f3f8}", "hockey": "\u{0001f3d2}", "field_hockey": "\u{0001f3d1}", "cricket": "\u{0001f3cf}", "ski": "\u{0001f3bf}", "skier": "\u{000026f7}", "snowboarder": "\u{0001f3c2}", "ice_skate": "\u{000026f8}", "bow_and_arrow": "\u{0001f3f9}", "fishing_pole_and_fish": "\u{0001f3a3}", "rowboat": "\u{0001f6a3}", "swimmer": "\u{0001f3ca}", "surfer": "\u{0001f3c4}", "bath": "\u{0001f6c0}", "basketball_player": "\u{000026f9}", "lifter": "\u{0001f3cb}", "bicyclist": "\u{0001f6b4}", "mountain_bicyclist": "\u{0001f6b5}", "horse_racing": "\u{0001f3c7}", "levitate": "\u{0001f574}", "trophy": "\u{0001f3c6}", "running_shirt_with_sash": "\u{0001f3bd}", "medal": "\u{0001f3c5}", "military_medal": "\u{0001f396}", "reminder_ribbon": "\u{0001f397}", "rosette": "\u{0001f3f5}", "ticket": "\u{0001f3ab}", "tickets": "\u{0001f39f}", "performing_arts": "\u{0001f3ad}", "art": "\u{0001f3a8}", "circus_tent": "\u{0001f3aa}", "microphone": "\u{0001f3a4}", "headphones": "\u{0001f3a7}", "musical_score": "\u{0001f3bc}", "musical_keyboard": "\u{0001f3b9}", "saxophone": "\u{0001f3b7}", "trumpet": "\u{0001f3ba}", "guitar": "\u{0001f3b8}", "violin": "\u{0001f3bb}", "clapper": "\u{0001f3ac}", "video_game": "\u{0001f3ae}", "space_invader": "\u{0001f47e}", "dart": "\u{0001f3af}", "game_die": "\u{0001f3b2}", "slot_machine": "\u{0001f3b0}", "bowling": "\u{0001f3b3}", "red_car": "\u{0001f697}", "taxi": "\u{0001f695}", "blue_car": "\u{0001f699}", "bus": "\u{0001f68c}", "trolleybus": "\u{0001f68e}", "race_car": "\u{0001f3ce}", "police_car": "\u{0001f693}", "ambulance": "\u{0001f691}", "fire_engine": "\u{0001f692}", "minibus": "\u{0001f690}", "truck": "\u{0001f69a}", "articulated_lorry": "\u{0001f69b}", "tractor": "\u{0001f69c}", "motorcycle": "\u{0001f3cd}", "bike": "\u{0001f6b2}", "rotating_light": "\u{0001f6a8}", "oncoming_police_car": "\u{0001f694}", "oncoming_bus": "\u{0001f68d}", "oncoming_automobile": "\u{0001f698}", "oncoming_taxi": "\u{0001f696}", "aerial_tramway": "\u{0001f6a1}", "mountain_cableway": "\u{0001f6a0}", "suspension_railway": "\u{0001f69f}", "railway_car": "\u{0001f683}", "train": "\u{0001f68b}", "monorail": "\u{0001f69d}", "bullettrain_side": "\u{0001f684}", "bullettrain_front": "\u{0001f685}", "light_rail": "\u{0001f688}", "mountain_railway": "\u{0001f69e}", "steam_locomotive": "\u{0001f682}", "train2": "\u{0001f686}", "metro": "\u{0001f687}", "tram": "\u{0001f68a}", "station": "\u{0001f689}", "helicopter": "\u{0001f681}", "airplane_small": "\u{0001f6e9}", "airplane": "\u{00002708}", "airplane_departure": "\u{0001f6eb}", "airplane_arriving": "\u{0001f6ec}", "sailboat": "\u{000026f5}", "motorboat": "\u{0001f6e5}", "speedboat": "\u{0001f6a4}", "ferry": "\u{000026f4}", "cruise_ship": "\u{0001f6f3}", "rocket": "\u{0001f680}", "satellite_orbital": "\u{0001f6f0}", "seat": "\u{0001f4ba}", "anchor": "\u{00002693}", "construction": "\u{0001f6a7}", "fuelpump": "\u{000026fd}", "busstop": "\u{0001f68f}", "vertical_traffic_light": "\u{0001f6a6}", "traffic_light": "\u{0001f6a5}", "checkered_flag": "\u{0001f3c1}", "ship": "\u{0001f6a2}", "ferris_wheel": "\u{0001f3a1}", "roller_coaster": "\u{0001f3a2}", "carousel_horse": "\u{0001f3a0}", "construction_site": "\u{0001f3d7}", "foggy": "\u{0001f301}", "tokyo_tower": "\u{0001f5fc}", "factory": "\u{0001f3ed}", "fountain": "\u{000026f2}", "rice_scene": "\u{0001f391}", "mountain": "\u{000026f0}", "mountain_snow": "\u{0001f3d4}", "mount_fuji": "\u{0001f5fb}", "volcano": "\u{0001f30b}", "japan": "\u{0001f5fe}", "camping": "\u{0001f3d5}", "tent": "\u{000026fa}", "park": "\u{0001f3de}", "motorway": "\u{0001f6e3}", "railway_track": "\u{0001f6e4}", "sunrise": "\u{0001f305}", "sunrise_over_mountains": "\u{0001f304}", "desert": "\u{0001f3dc}", "beach": "\u{0001f3d6}", "island": "\u{0001f3dd}", "city_sunset": "\u{0001f307}", "city_dusk": "\u{0001f306}", "cityscape": "\u{0001f3d9}", "night_with_stars": "\u{0001f303}", "bridge_at_night": "\u{0001f309}", "milky_way": "\u{0001f30c}", "stars": "\u{0001f320}", "sparkler": "\u{0001f387}", "fireworks": "\u{0001f386}", "rainbow": "\u{0001f308}", "homes": "\u{0001f3d8}", "european_castle": "\u{0001f3f0}", "japanese_castle": "\u{0001f3ef}", "stadium": "\u{0001f3df}", "statue_of_liberty": "\u{0001f5fd}", "house": "\u{0001f3e0}", "house_with_garden": "\u{0001f3e1}", "house_abandoned": "\u{0001f3da}", "office": "\u{0001f3e2}", "department_store": "\u{0001f3ec}", "post_office": "\u{0001f3e3}", "european_post_office": "\u{0001f3e4}", "hospital": "\u{0001f3e5}", "bank": "\u{0001f3e6}", "hotel": "\u{0001f3e8}", "convenience_store": "\u{0001f3ea}", "school": "\u{0001f3eb}", "love_hotel": "\u{0001f3e9}", "wedding": "\u{0001f492}", "classical_building": "\u{0001f3db}", "church": "\u{000026ea}", "mosque": "\u{0001f54c}", "synagogue": "\u{0001f54d}", "kaaba": "\u{0001f54b}", "shinto_shrine": "\u{000026e9}", "watch": "\u{0000231a}", "iphone": "\u{0001f4f1}", "calling": "\u{0001f4f2}", "computer": "\u{0001f4bb}", "keyboard": "\u{00002328}", "desktop": "\u{0001f5a5}", "printer": "\u{0001f5a8}", "mouse_three_button": "\u{0001f5b1}", "trackball": "\u{0001f5b2}", "joystick": "\u{0001f579}", "compression": "\u{0001f5dc}", "minidisc": "\u{0001f4bd}", "floppy_disk": "\u{0001f4be}", "cd": "\u{0001f4bf}", "dvd": "\u{0001f4c0}", "vhs": "\u{0001f4fc}", "camera": "\u{0001f4f7}", "camera_with_flash": "\u{0001f4f8}", "video_camera": "\u{0001f4f9}", "movie_camera": "\u{0001f3a5}", "projector": "\u{0001f4fd}", "film_frames": "\u{0001f39e}", "telephone_receiver": "\u{0001f4de}", "telephone": "\u{0000260e}", "pager": "\u{0001f4df}", "fax": "\u{0001f4e0}", "tv": "\u{0001f4fa}", "radio": "\u{0001f4fb}", "microphone2": "\u{0001f399}", "level_slider": "\u{0001f39a}", "control_knobs": "\u{0001f39b}", "stopwatch": "\u{000023f1}", "timer": "\u{000023f2}", "alarm_clock": "\u{000023f0}", "clock": "\u{0001f570}", "hourglass_flowing_sand": "\u{000023f3}", "hourglass": "\u{0000231b}", "satellite": "\u{0001f4e1}", "battery": "\u{0001f50b}", "electric_plug": "\u{0001f50c}", "bulb": "\u{0001f4a1}", "flashlight": "\u{0001f526}", "candle": "\u{0001f56f}", "wastebasket": "\u{0001f5d1}", "oil": "\u{0001f6e2}", "money_with_wings": "\u{0001f4b8}", "dollar": "\u{0001f4b5}", "yen": "\u{0001f4b4}", "euro": "\u{0001f4b6}", "pound": "\u{0001f4b7}", "moneybag": "\u{0001f4b0}", "credit_card": "\u{0001f4b3}", "gem": "\u{0001f48e}", "scales": "\u{00002696}", "wrench": "\u{0001f527}", "hammer": "\u{0001f528}", "hammer_pick": "\u{00002692}", "tools": "\u{0001f6e0}", "pick": "\u{000026cf}", "nut_and_bolt": "\u{0001f529}", "gear": "\u{00002699}", "chains": "\u{000026d3}", "gun": "\u{0001f52b}", "bomb": "\u{0001f4a3}", "knife": "\u{0001f52a}", "dagger": "\u{0001f5e1}", "crossed_swords": "\u{00002694}", "shield": "\u{0001f6e1}", "smoking": "\u{0001f6ac}", "skull_crossbones": "\u{00002620}", "coffin": "\u{000026b0}", "urn": "\u{000026b1}", "amphora": "\u{0001f3fa}", "crystal_ball": "\u{0001f52e}", "prayer_beads": "\u{0001f4ff}", "barber": "\u{0001f488}", "alembic": "\u{00002697}", "telescope": "\u{0001f52d}", "microscope": "\u{0001f52c}", "hole": "\u{0001f573}", "pill": "\u{0001f48a}", "syringe": "\u{0001f489}", "thermometer": "\u{0001f321}", "label": "\u{0001f3f7}", "bookmark": "\u{0001f516}", "toilet": "\u{0001f6bd}", "shower": "\u{0001f6bf}", "bathtub": "\u{0001f6c1}", "key": "\u{0001f511}", "key2": "\u{0001f5dd}", "couch": "\u{0001f6cb}", "sleeping_accommodation": "\u{0001f6cc}", "bed": "\u{0001f6cf}", "door": "\u{0001f6aa}", "bellhop": "\u{0001f6ce}", "frame_photo": "\u{0001f5bc}", "map": "\u{0001f5fa}", "beach_umbrella": "\u{000026f1}", "moyai": "\u{0001f5ff}", "shopping_bags": "\u{0001f6cd}", "balloon": "\u{0001f388}", "flags": "\u{0001f38f}", "ribbon": "\u{0001f380}", "gift": "\u{0001f381}", "confetti_ball": "\u{0001f38a}", "tada": "\u{0001f389}", "dolls": "\u{0001f38e}", "wind_chime": "\u{0001f390}", "crossed_flags": "\u{0001f38c}", "izakaya_lantern": "\u{0001f3ee}", "envelope": "\u{00002709}", "envelope_with_arrow": "\u{0001f4e9}", "incoming_envelope": "\u{0001f4e8}", "e-mail": "\u{0001f4e7}", "love_letter": "\u{0001f48c}", "postbox": "\u{0001f4ee}", "mailbox_closed": "\u{0001f4ea}", "mailbox": "\u{0001f4eb}", "mailbox_with_mail": "\u{0001f4ec}", "mailbox_with_no_mail": "\u{0001f4ed}", "package": "\u{0001f4e6}", "postal_horn": "\u{0001f4ef}", "inbox_tray": "\u{0001f4e5}", "outbox_tray": "\u{0001f4e4}", "scroll": "\u{0001f4dc}", "page_with_curl": "\u{0001f4c3}", "bookmark_tabs": "\u{0001f4d1}", "bar_chart": "\u{0001f4ca}", "chart_with_upwards_trend": "\u{0001f4c8}", "chart_with_downwards_trend": "\u{0001f4c9}", "page_facing_up": "\u{0001f4c4}", "date": "\u{0001f4c5}", "calendar": "\u{0001f4c6}", "calendar_spiral": "\u{0001f5d3}", "card_index": "\u{0001f4c7}", "card_box": "\u{0001f5c3}", "ballot_box": "\u{0001f5f3}", "file_cabinet": "\u{0001f5c4}", "clipboard": "\u{0001f4cb}", "notepad_spiral": "\u{0001f5d2}", "file_folder": "\u{0001f4c1}", "open_file_folder": "\u{0001f4c2}", "dividers": "\u{0001f5c2}", "newspaper2": "\u{0001f5de}", "newspaper": "\u{0001f4f0}", "notebook": "\u{0001f4d3}", "closed_book": "\u{0001f4d5}", "green_book": "\u{0001f4d7}", "blue_book": "\u{0001f4d8}", "orange_book": "\u{0001f4d9}", "notebook_with_decorative_cover": "\u{0001f4d4}", "ledger": "\u{0001f4d2}", "books": "\u{0001f4da}", "book": "\u{0001f4d6}", "link": "\u{0001f517}", "paperclip": "\u{0001f4ce}", "paperclips": "\u{0001f587}", "scissors": "\u{00002702}", "triangular_ruler": "\u{0001f4d0}", "straight_ruler": "\u{0001f4cf}", "pushpin": "\u{0001f4cc}", "round_pushpin": "\u{0001f4cd}", "triangular_flag_on_post": "\u{0001f6a9}", "flag_white": "\u{0001f3f3}", "flag_black": "\u{0001f3f4}", "closed_lock_with_key": "\u{0001f510}", "lock": "\u{0001f512}", "unlock": "\u{0001f513}", "lock_with_ink_pen": "\u{0001f50f}", "pen_ballpoint": "\u{0001f58a}", "pen_fountain": "\u{0001f58b}", "black_nib": "\u{00002712}", "pencil": "\u{0001f4dd}", "pencil2": "\u{0000270f}", "crayon": "\u{0001f58d}", "paintbrush": "\u{0001f58c}", "mag": "\u{0001f50d}", "mag_right": "\u{0001f50e}", "heart": "\u{00002764}", "yellow_heart": "\u{0001f49b}", "green_heart": "\u{0001f49a}", "blue_heart": "\u{0001f499}", "purple_heart": "\u{0001f49c}", "broken_heart": "\u{0001f494}", "heart_exclamation": "\u{00002763}", "two_hearts": "\u{0001f495}", "revolving_hearts": "\u{0001f49e}", "heartbeat": "\u{0001f493}", "heartpulse": "\u{0001f497}", "sparkling_heart": "\u{0001f496}", "cupid": "\u{0001f498}", "gift_heart": "\u{0001f49d}", "heart_decoration": "\u{0001f49f}", "peace": "\u{0000262e}", "cross": "\u{0000271d}", "star_and_crescent": "\u{0000262a}", "om_symbol": "\u{0001f549}", "wheel_of_dharma": "\u{00002638}", "star_of_david": "\u{00002721}", "six_pointed_star": "\u{0001f52f}", "menorah": "\u{0001f54e}", "yin_yang": "\u{0000262f}", "orthodox_cross": "\u{00002626}", "place_of_worship": "\u{0001f6d0}", "ophiuchus": "\u{000026ce}", "aries": "\u{00002648}", "taurus": "\u{00002649}", "gemini": "\u{0000264a}", "cancer": "\u{0000264b}", "leo": "\u{0000264c}", "virgo": "\u{0000264d}", "libra": "\u{0000264e}", "scorpius": "\u{0000264f}", "sagittarius": "\u{00002650}", "capricorn": "\u{00002651}", "aquarius": "\u{00002652}", "pisces": "\u{00002653}", "id": "\u{0001f194}", "atom": "\u{0000269b}", "u7a7a": "\u{0001f233}", "u5272": "\u{0001f239}", "radioactive": "\u{00002622}", "biohazard": "\u{00002623}", "mobile_phone_off": "\u{0001f4f4}", "vibration_mode": "\u{0001f4f3}", "u6709": "\u{0001f236}", "u7121": "\u{0001f21a}", "u7533": "\u{0001f238}", "u55b6": "\u{0001f23a}", "u6708": "\u{0001f237}", "eight_pointed_black_star": "\u{00002734}", "vs": "\u{0001f19a}", "accept": "\u{0001f251}", "white_flower": "\u{0001f4ae}", "ideograph_advantage": "\u{0001f250}", "secret": "\u{00003299}", "congratulations": "\u{00003297}", "u5408": "\u{0001f234}", "u6e80": "\u{0001f235}", "u7981": "\u{0001f232}", "a": "\u{0001f170}", "b": "\u{0001f171}", "ab": "\u{0001f18e}", "cl": "\u{0001f191}", "o2": "\u{0001f17e}", "sos": "\u{0001f198}", "no_entry": "\u{000026d4}", "name_badge": "\u{0001f4db}", "no_entry_sign": "\u{0001f6ab}", "x": "\u{0000274c}", "o": "\u{00002b55}", "anger": "\u{0001f4a2}", "hotsprings": "\u{00002668}", "no_pedestrians": "\u{0001f6b7}", "do_not_litter": "\u{0001f6af}", "no_bicycles": "\u{0001f6b3}", "non-potable_water": "\u{0001f6b1}", "underage": "\u{0001f51e}", "no_mobile_phones": "\u{0001f4f5}", "exclamation": "\u{00002757}", "grey_exclamation": "\u{00002755}", "question": "\u{00002753}", "grey_question": "\u{00002754}", "bangbang": "\u{0000203c}", "interrobang": "\u{00002049}", "low_brightness": "\u{0001f505}", "high_brightness": "\u{0001f506}", "trident": "\u{0001f531}", "fleur-de-lis": "\u{0000269c}", "part_alternation_mark": "\u{0000303d}", "warning": "\u{000026a0}", "children_crossing": "\u{0001f6b8}", "beginner": "\u{0001f530}", "recycle": "\u{0000267b}", "u6307": "\u{0001f22f}", "chart": "\u{0001f4b9}", "sparkle": "\u{00002747}", "eight_spoked_asterisk": "\u{00002733}", "negative_squared_cross_mark": "\u{0000274e}", "white_check_mark": "\u{00002705}", "diamond_shape_with_a_dot_inside": "\u{0001f4a0}", "cyclone": "\u{0001f300}", "loop": "\u{000027bf}", "globe_with_meridians": "\u{0001f310}", "m": "\u{000024c2}", "atm": "\u{0001f3e7}", "sa": "\u{0001f202}", "passport_control": "\u{0001f6c2}", "customs": "\u{0001f6c3}", "baggage_claim": "\u{0001f6c4}", "left_luggage": "\u{0001f6c5}", "wheelchair": "\u{0000267f}", "no_smoking": "\u{0001f6ad}", "wc": "\u{0001f6be}", "parking": "\u{0001f17f}", "potable_water": "\u{0001f6b0}", "mens": "\u{0001f6b9}", "womens": "\u{0001f6ba}", "baby_symbol": "\u{0001f6bc}", "restroom": "\u{0001f6bb}", "put_litter_in_its_place": "\u{0001f6ae}", "cinema": "\u{0001f3a6}", "signal_strength": "\u{0001f4f6}", "koko": "\u{0001f201}", "ng": "\u{0001f196}", "ok": "\u{0001f197}", "up": "\u{0001f199}", "cool": "\u{0001f192}", "new": "\u{0001f195}", "free": "\u{0001f193}", "zero": "0\u{000020e3}", "one": "1\u{000020e3}", "two": "2\u{000020e3}", "three": "3\u{000020e3}", "four": "4\u{000020e3}", "five": "5\u{000020e3}", "six": "6\u{000020e3}", "seven": "7\u{000020e3}", "eight": "8\u{000020e3}", "nine": "9\u{000020e3}", "keycap_ten": "\u{0001f51f}", "arrow_forward": "\u{000025b6}", "pause_button": "\u{000023f8}", "play_pause": "\u{000023ef}", "stop_button": "\u{000023f9}", "record_button": "\u{000023fa}", "track_next": "\u{000023ed}", "track_previous": "\u{000023ee}", "fast_forward": "\u{000023e9}", "rewind": "\u{000023ea}", "twisted_rightwards_arrows": "\u{0001f500}", "repeat": "\u{0001f501}", "repeat_one": "\u{0001f502}", "arrow_backward": "\u{000025c0}", "arrow_up_small": "\u{0001f53c}", "arrow_down_small": "\u{0001f53d}", "arrow_double_up": "\u{000023eb}", "arrow_double_down": "\u{000023ec}", "arrow_right": "\u{000027a1}", "arrow_left": "\u{00002b05}", "arrow_up": "\u{00002b06}", "arrow_down": "\u{00002b07}", "arrow_upper_right": "\u{00002197}", "arrow_lower_right": "\u{00002198}", "arrow_lower_left": "\u{00002199}", "arrow_upper_left": "\u{00002196}", "arrow_up_down": "\u{00002195}", "left_right_arrow": "\u{00002194}", "arrows_counterclockwise": "\u{0001f504}", "arrow_right_hook": "\u{000021aa}", "leftwards_arrow_with_hook": "\u{000021a9}", "arrow_heading_up": "\u{00002934}", "arrow_heading_down": "\u{00002935}", "hash": "#\u{000020e3}", "asterisk": "\u{0000002a}\u{000020e3}", "information_source": "\u{00002139}", "abc": "\u{0001f524}", "abcd": "\u{0001f521}", "capital_abcd": "\u{0001f520}", "symbols": "\u{0001f523}", "musical_note": "\u{0001f3b5}", "notes": "\u{0001f3b6}", "wavy_dash": "\u{00003030}", "curly_loop": "\u{000027b0}", "heavy_check_mark": "\u{00002714}", "arrows_clockwise": "\u{0001f503}", "heavy_plus_sign": "\u{00002795}", "heavy_minus_sign": "\u{00002796}", "heavy_division_sign": "\u{00002797}", "heavy_multiplication_x": "\u{00002716}", "heavy_dollar_sign": "\u{0001f4b2}", "currency_exchange": "\u{0001f4b1}", "copyright": "\u{000000a9}", "registered": "\u{000000ae}", "tm": "\u{00002122}", "end": "\u{0001f51a}", "back": "\u{0001f519}", "on": "\u{0001f51b}", "top": "\u{0001f51d}", "soon": "\u{0001f51c}", "ballot_box_with_check": "\u{00002611}", "radio_button": "\u{0001f518}", "white_circle": "\u{000026aa}", "black_circle": "\u{000026ab}", "red_circle": "\u{0001f534}", "large_blue_circle": "\u{0001f535}", "small_orange_diamond": "\u{0001f538}", "small_blue_diamond": "\u{0001f539}", "large_orange_diamond": "\u{0001f536}", "large_blue_diamond": "\u{0001f537}", "small_red_triangle": "\u{0001f53a}", "black_small_square": "\u{000025aa}", "white_small_square": "\u{000025ab}", "black_large_square": "\u{00002b1b}", "white_large_square": "\u{00002b1c}", "small_red_triangle_down": "\u{0001f53b}", "black_medium_square": "\u{000025fc}", "white_medium_square": "\u{000025fb}", "black_medium_small_square": "\u{000025fe}", "white_medium_small_square": "\u{000025fd}", "black_square_button": "\u{0001f532}", "white_square_button": "\u{0001f533}", "speaker": "\u{0001f508}", "sound": "\u{0001f509}", "loud_sound": "\u{0001f50a}", "mute": "\u{0001f507}", "mega": "\u{0001f4e3}", "loudspeaker": "\u{0001f4e2}", "bell": "\u{0001f514}", "no_bell": "\u{0001f515}", "black_joker": "\u{0001f0cf}", "mahjong": "\u{0001f004}", "spades": "\u{00002660}", "clubs": "\u{00002663}", "hearts": "\u{00002665}", "diamonds": "\u{00002666}", "flower_playing_cards": "\u{0001f3b4}", "thought_balloon": "\u{0001f4ad}", "anger_right": "\u{0001f5ef}", "speech_balloon": "\u{0001f4ac}", "clock1": "\u{0001f550}", "clock2": "\u{0001f551}", "clock3": "\u{0001f552}", "clock4": "\u{0001f553}", "clock5": "\u{0001f554}", "clock6": "\u{0001f555}", "clock7": "\u{0001f556}", "clock8": "\u{0001f557}", "clock9": "\u{0001f558}", "clock10": "\u{0001f559}", "clock11": "\u{0001f55a}", "clock12": "\u{0001f55b}", "clock130": "\u{0001f55c}", "clock230": "\u{0001f55d}", "clock330": "\u{0001f55e}", "clock430": "\u{0001f55f}", "clock530": "\u{0001f560}", "clock630": "\u{0001f561}", "clock730": "\u{0001f562}", "clock830": "\u{0001f563}", "clock930": "\u{0001f564}", "clock1030": "\u{0001f565}", "clock1130": "\u{0001f566}", "clock1230": "\u{0001f567}", "eye_in_speech_bubble": "\u{0001f441}\u{0001f5e8}", "flag_ac": "\u{0001f1e6}\u{0001f1e8}", "flag_af": "\u{0001f1e6}\u{0001f1eb}", "flag_al": "\u{0001f1e6}\u{0001f1f1}", "flag_dz": "\u{0001f1e9}\u{0001f1ff}", "flag_ad": "\u{0001f1e6}\u{0001f1e9}", "flag_ao": "\u{0001f1e6}\u{0001f1f4}", "flag_ai": "\u{0001f1e6}\u{0001f1ee}", "flag_ag": "\u{0001f1e6}\u{0001f1ec}", "flag_ar": "\u{0001f1e6}\u{0001f1f7}", "flag_am": "\u{0001f1e6}\u{0001f1f2}", "flag_aw": "\u{0001f1e6}\u{0001f1fc}", "flag_au": "\u{0001f1e6}\u{0001f1fa}", "flag_at": "\u{0001f1e6}\u{0001f1f9}", "flag_az": "\u{0001f1e6}\u{0001f1ff}", "flag_bs": "\u{0001f1e7}\u{0001f1f8}", "flag_bh": "\u{0001f1e7}\u{0001f1ed}", "flag_bd": "\u{0001f1e7}\u{0001f1e9}", "flag_bb": "\u{0001f1e7}\u{0001f1e7}", "flag_by": "\u{0001f1e7}\u{0001f1fe}", "flag_be": "\u{0001f1e7}\u{0001f1ea}", "flag_bz": "\u{0001f1e7}\u{0001f1ff}", "flag_bj": "\u{0001f1e7}\u{0001f1ef}", "flag_bm": "\u{0001f1e7}\u{0001f1f2}", "flag_bt": "\u{0001f1e7}\u{0001f1f9}", "flag_bo": "\u{0001f1e7}\u{0001f1f4}", "flag_ba": "\u{0001f1e7}\u{0001f1e6}", "flag_bw": "\u{0001f1e7}\u{0001f1fc}", "flag_br": "\u{0001f1e7}\u{0001f1f7}", "flag_bn": "\u{0001f1e7}\u{0001f1f3}", "flag_bg": "\u{0001f1e7}\u{0001f1ec}", "flag_bf": "\u{0001f1e7}\u{0001f1eb}", "flag_bi": "\u{0001f1e7}\u{0001f1ee}", "flag_cv": "\u{0001f1e8}\u{0001f1fb}", "flag_kh": "\u{0001f1f0}\u{0001f1ed}", "flag_cm": "\u{0001f1e8}\u{0001f1f2}", "flag_ca": "\u{0001f1e8}\u{0001f1e6}", "flag_ky": "\u{0001f1f0}\u{0001f1fe}", "flag_cf": "\u{0001f1e8}\u{0001f1eb}", "flag_td": "\u{0001f1f9}\u{0001f1e9}", "flag_cl": "\u{0001f1e8}\u{0001f1f1}", "flag_cn": "\u{0001f1e8}\u{0001f1f3}", "flag_co": "\u{0001f1e8}\u{0001f1f4}", "flag_km": "\u{0001f1f0}\u{0001f1f2}", "flag_cg": "\u{0001f1e8}\u{0001f1ec}", "flag_cd": "\u{0001f1e8}\u{0001f1e9}", "flag_cr": "\u{0001f1e8}\u{0001f1f7}", "flag_hr": "\u{0001f1ed}\u{0001f1f7}", "flag_cu": "\u{0001f1e8}\u{0001f1fa}", "flag_cy": "\u{0001f1e8}\u{0001f1fe}", "flag_cz": "\u{0001f1e8}\u{0001f1ff}", "flag_dk": "\u{0001f1e9}\u{0001f1f0}", "flag_dj": "\u{0001f1e9}\u{0001f1ef}", "flag_dm": "\u{0001f1e9}\u{0001f1f2}", "flag_do": "\u{0001f1e9}\u{0001f1f4}", "flag_ec": "\u{0001f1ea}\u{0001f1e8}", "flag_eg": "\u{0001f1ea}\u{0001f1ec}", "flag_sv": "\u{0001f1f8}\u{0001f1fb}", "flag_gq": "\u{0001f1ec}\u{0001f1f6}", "flag_er": "\u{0001f1ea}\u{0001f1f7}", "flag_ee": "\u{0001f1ea}\u{0001f1ea}", "flag_et": "\u{0001f1ea}\u{0001f1f9}", "flag_fk": "\u{0001f1eb}\u{0001f1f0}", "flag_fo": "\u{0001f1eb}\u{0001f1f4}", "flag_fj": "\u{0001f1eb}\u{0001f1ef}", "flag_fi": "\u{0001f1eb}\u{0001f1ee}", "flag_fr": "\u{0001f1eb}\u{0001f1f7}", "flag_pf": "\u{0001f1f5}\u{0001f1eb}", "flag_ga": "\u{0001f1ec}\u{0001f1e6}", "flag_gm": "\u{0001f1ec}\u{0001f1f2}", "flag_ge": "\u{0001f1ec}\u{0001f1ea}", "flag_de": "\u{0001f1e9}\u{0001f1ea}", "flag_gh": "\u{0001f1ec}\u{0001f1ed}", "flag_gi": "\u{0001f1ec}\u{0001f1ee}", "flag_gr": "\u{0001f1ec}\u{0001f1f7}", "flag_gl": "\u{0001f1ec}\u{0001f1f1}", "flag_gd": "\u{0001f1ec}\u{0001f1e9}", "flag_gu": "\u{0001f1ec}\u{0001f1fa}", "flag_gt": "\u{0001f1ec}\u{0001f1f9}", "flag_gn": "\u{0001f1ec}\u{0001f1f3}", "flag_gw": "\u{0001f1ec}\u{0001f1fc}", "flag_gy": "\u{0001f1ec}\u{0001f1fe}", "flag_ht": "\u{0001f1ed}\u{0001f1f9}", "flag_hn": "\u{0001f1ed}\u{0001f1f3}", "flag_hk": "\u{0001f1ed}\u{0001f1f0}", "flag_hu": "\u{0001f1ed}\u{0001f1fa}", "flag_is": "\u{0001f1ee}\u{0001f1f8}", "flag_in": "\u{0001f1ee}\u{0001f1f3}", "flag_id": "\u{0001f1ee}\u{0001f1e9}", "flag_ir": "\u{0001f1ee}\u{0001f1f7}", "flag_iq": "\u{0001f1ee}\u{0001f1f6}", "flag_ie": "\u{0001f1ee}\u{0001f1ea}", "flag_il": "\u{0001f1ee}\u{0001f1f1}", "flag_it": "\u{0001f1ee}\u{0001f1f9}", "flag_ci": "\u{0001f1e8}\u{0001f1ee}", "flag_jm": "\u{0001f1ef}\u{0001f1f2}", "flag_jp": "\u{0001f1ef}\u{0001f1f5}", "flag_je": "\u{0001f1ef}\u{0001f1ea}", "flag_jo": "\u{0001f1ef}\u{0001f1f4}", "flag_kz": "\u{0001f1f0}\u{0001f1ff}", "flag_ke": "\u{0001f1f0}\u{0001f1ea}", "flag_ki": "\u{0001f1f0}\u{0001f1ee}", "flag_xk": "\u{0001f1fd}\u{0001f1f0}", "flag_kw": "\u{0001f1f0}\u{0001f1fc}", "flag_kg": "\u{0001f1f0}\u{0001f1ec}", "flag_la": "\u{0001f1f1}\u{0001f1e6}", "flag_lv": "\u{0001f1f1}\u{0001f1fb}", "flag_lb": "\u{0001f1f1}\u{0001f1e7}", "flag_ls": "\u{0001f1f1}\u{0001f1f8}", "flag_lr": "\u{0001f1f1}\u{0001f1f7}", "flag_ly": "\u{0001f1f1}\u{0001f1fe}", "flag_li": "\u{0001f1f1}\u{0001f1ee}", "flag_lt": "\u{0001f1f1}\u{0001f1f9}", "flag_lu": "\u{0001f1f1}\u{0001f1fa}", "flag_mo": "\u{0001f1f2}\u{0001f1f4}", "flag_mk": "\u{0001f1f2}\u{0001f1f0}", "flag_mg": "\u{0001f1f2}\u{0001f1ec}", "flag_mw": "\u{0001f1f2}\u{0001f1fc}", "flag_my": "\u{0001f1f2}\u{0001f1fe}", "flag_mv": "\u{0001f1f2}\u{0001f1fb}", "flag_ml": "\u{0001f1f2}\u{0001f1f1}", "flag_mt": "\u{0001f1f2}\u{0001f1f9}", "flag_mh": "\u{0001f1f2}\u{0001f1ed}", "flag_mr": "\u{0001f1f2}\u{0001f1f7}", "flag_mu": "\u{0001f1f2}\u{0001f1fa}", "flag_mx": "\u{0001f1f2}\u{0001f1fd}", "flag_fm": "\u{0001f1eb}\u{0001f1f2}", "flag_md": "\u{0001f1f2}\u{0001f1e9}", "flag_mc": "\u{0001f1f2}\u{0001f1e8}", "flag_mn": "\u{0001f1f2}\u{0001f1f3}", "flag_me": "\u{0001f1f2}\u{0001f1ea}", "flag_ms": "\u{0001f1f2}\u{0001f1f8}", "flag_ma": "\u{0001f1f2}\u{0001f1e6}", "flag_mz": "\u{0001f1f2}\u{0001f1ff}", "flag_mm": "\u{0001f1f2}\u{0001f1f2}", "flag_na": "\u{0001f1f3}\u{0001f1e6}", "flag_nr": "\u{0001f1f3}\u{0001f1f7}", "flag_np": "\u{0001f1f3}\u{0001f1f5}", "flag_nl": "\u{0001f1f3}\u{0001f1f1}", "flag_nc": "\u{0001f1f3}\u{0001f1e8}", "flag_nz": "\u{0001f1f3}\u{0001f1ff}", "flag_ni": "\u{0001f1f3}\u{0001f1ee}", "flag_ne": "\u{0001f1f3}\u{0001f1ea}", "flag_ng": "\u{0001f1f3}\u{0001f1ec}", "flag_nu": "\u{0001f1f3}\u{0001f1fa}", "flag_kp": "\u{0001f1f0}\u{0001f1f5}", "flag_no": "\u{0001f1f3}\u{0001f1f4}", "flag_om": "\u{0001f1f4}\u{0001f1f2}", "flag_pk": "\u{0001f1f5}\u{0001f1f0}", "flag_pw": "\u{0001f1f5}\u{0001f1fc}", "flag_ps": "\u{0001f1f5}\u{0001f1f8}", "flag_pa": "\u{0001f1f5}\u{0001f1e6}", "flag_pg": "\u{0001f1f5}\u{0001f1ec}", "flag_py": "\u{0001f1f5}\u{0001f1fe}", "flag_pe": "\u{0001f1f5}\u{0001f1ea}", "flag_ph": "\u{0001f1f5}\u{0001f1ed}", "flag_pl": "\u{0001f1f5}\u{0001f1f1}", "flag_pt": "\u{0001f1f5}\u{0001f1f9}", "flag_pr": "\u{0001f1f5}\u{0001f1f7}", "flag_qa": "\u{0001f1f6}\u{0001f1e6}", "flag_ro": "\u{0001f1f7}\u{0001f1f4}", "flag_ru": "\u{0001f1f7}\u{0001f1fa}", "flag_rw": "\u{0001f1f7}\u{0001f1fc}", "flag_sh": "\u{0001f1f8}\u{0001f1ed}", "flag_kn": "\u{0001f1f0}\u{0001f1f3}", "flag_lc": "\u{0001f1f1}\u{0001f1e8}", "flag_vc": "\u{0001f1fb}\u{0001f1e8}", "flag_ws": "\u{0001f1fc}\u{0001f1f8}", "flag_sm": "\u{0001f1f8}\u{0001f1f2}", "flag_st": "\u{0001f1f8}\u{0001f1f9}", "flag_sa": "\u{0001f1f8}\u{0001f1e6}", "flag_sn": "\u{0001f1f8}\u{0001f1f3}", "flag_rs": "\u{0001f1f7}\u{0001f1f8}", "flag_sc": "\u{0001f1f8}\u{0001f1e8}", "flag_sl": "\u{0001f1f8}\u{0001f1f1}", "flag_sg": "\u{0001f1f8}\u{0001f1ec}", "flag_sk": "\u{0001f1f8}\u{0001f1f0}", "flag_si": "\u{0001f1f8}\u{0001f1ee}", "flag_sb": "\u{0001f1f8}\u{0001f1e7}", "flag_so": "\u{0001f1f8}\u{0001f1f4}", "flag_za": "\u{0001f1ff}\u{0001f1e6}", "flag_kr": "\u{0001f1f0}\u{0001f1f7}", "flag_es": "\u{0001f1ea}\u{0001f1f8}", "flag_lk": "\u{0001f1f1}\u{0001f1f0}", "flag_sd": "\u{0001f1f8}\u{0001f1e9}", "flag_sr": "\u{0001f1f8}\u{0001f1f7}", "flag_sz": "\u{0001f1f8}\u{0001f1ff}", "flag_se": "\u{0001f1f8}\u{0001f1ea}", "flag_ch": "\u{0001f1e8}\u{0001f1ed}", "flag_sy": "\u{0001f1f8}\u{0001f1fe}", "flag_tw": "\u{0001f1f9}\u{0001f1fc}", "flag_tj": "\u{0001f1f9}\u{0001f1ef}", "flag_tz": "\u{0001f1f9}\u{0001f1ff}", "flag_th": "\u{0001f1f9}\u{0001f1ed}", "flag_tl": "\u{0001f1f9}\u{0001f1f1}", "flag_tg": "\u{0001f1f9}\u{0001f1ec}", "flag_to": "\u{0001f1f9}\u{0001f1f4}", "flag_tt": "\u{0001f1f9}\u{0001f1f9}", "flag_tn": "\u{0001f1f9}\u{0001f1f3}", "flag_tr": "\u{0001f1f9}\u{0001f1f7}", "flag_tm": "\u{0001f1f9}\u{0001f1f2}", "flag_tv": "\u{0001f1f9}\u{0001f1fb}", "flag_ug": "\u{0001f1fa}\u{0001f1ec}", "flag_ua": "\u{0001f1fa}\u{0001f1e6}", "flag_ae": "\u{0001f1e6}\u{0001f1ea}", "flag_gb": "\u{0001f1ec}\u{0001f1e7}", "flag_us": "\u{0001f1fa}\u{0001f1f8}", "flag_vi": "\u{0001f1fb}\u{0001f1ee}", "flag_uy": "\u{0001f1fa}\u{0001f1fe}", "flag_uz": "\u{0001f1fa}\u{0001f1ff}", "flag_vu": "\u{0001f1fb}\u{0001f1fa}", "flag_va": "\u{0001f1fb}\u{0001f1e6}", "flag_ve": "\u{0001f1fb}\u{0001f1ea}", "flag_vn": "\u{0001f1fb}\u{0001f1f3}", "flag_wf": "\u{0001f1fc}\u{0001f1eb}", "flag_eh": "\u{0001f1ea}\u{0001f1ed}", "flag_ye": "\u{0001f1fe}\u{0001f1ea}", "flag_zm": "\u{0001f1ff}\u{0001f1f2}", "flag_zw": "\u{0001f1ff}\u{0001f1fc}", "flag_re": "\u{0001f1f7}\u{0001f1ea}", "flag_ax": "\u{0001f1e6}\u{0001f1fd}", "flag_ta": "\u{0001f1f9}\u{0001f1e6}", "flag_io": "\u{0001f1ee}\u{0001f1f4}", "flag_bq": "\u{0001f1e7}\u{0001f1f6}", "flag_cx": "\u{0001f1e8}\u{0001f1fd}", "flag_cc": "\u{0001f1e8}\u{0001f1e8}", "flag_gg": "\u{0001f1ec}\u{0001f1ec}", "flag_im": "\u{0001f1ee}\u{0001f1f2}", "flag_yt": "\u{0001f1fe}\u{0001f1f9}", "flag_nf": "\u{0001f1f3}\u{0001f1eb}", "flag_pn": "\u{0001f1f5}\u{0001f1f3}", "flag_bl": "\u{0001f1e7}\u{0001f1f1}", "flag_pm": "\u{0001f1f5}\u{0001f1f2}", "flag_gs": "\u{0001f1ec}\u{0001f1f8}", "flag_tk": "\u{0001f1f9}\u{0001f1f0}", "flag_bv": "\u{0001f1e7}\u{0001f1fb}", "flag_hm": "\u{0001f1ed}\u{0001f1f2}", "flag_sj": "\u{0001f1f8}\u{0001f1ef}", "flag_um": "\u{0001f1fa}\u{0001f1f2}", "flag_ic": "\u{0001f1ee}\u{0001f1e8}", "flag_ea": "\u{0001f1ea}\u{0001f1e6}", "flag_cp": "\u{0001f1e8}\u{0001f1f5}", "flag_dg": "\u{0001f1e9}\u{0001f1ec}", "flag_as": "\u{0001f1e6}\u{0001f1f8}", "flag_aq": "\u{0001f1e6}\u{0001f1f6}", "flag_vg": "\u{0001f1fb}\u{0001f1ec}", "flag_ck": "\u{0001f1e8}\u{0001f1f0}", "flag_cw": "\u{0001f1e8}\u{0001f1fc}", "flag_eu": "\u{0001f1ea}\u{0001f1fa}", "flag_gf": "\u{0001f1ec}\u{0001f1eb}", "flag_tf": "\u{0001f1f9}\u{0001f1eb}", "flag_gp": "\u{0001f1ec}\u{0001f1f5}", "flag_mq": "\u{0001f1f2}\u{0001f1f6}", "flag_mp": "\u{0001f1f2}\u{0001f1f5}", "flag_sx": "\u{0001f1f8}\u{0001f1fd}", "flag_ss": "\u{0001f1f8}\u{0001f1f8}", "flag_tc": "\u{0001f1f9}\u{0001f1e8}", "flag_mf": "\u{0001f1f2}\u{0001f1eb}", "raised_hands_tone1": "\u{0001f64c}\u{0001f3fb}", "raised_hands_tone2": "\u{0001f64c}\u{0001f3fc}", "raised_hands_tone3": "\u{0001f64c}\u{0001f3fd}", "raised_hands_tone4": "\u{0001f64c}\u{0001f3fe}", "raised_hands_tone5": "\u{0001f64c}\u{0001f3ff}", "clap_tone1": "\u{0001f44f}\u{0001f3fb}", "clap_tone2": "\u{0001f44f}\u{0001f3fc}", "clap_tone3": "\u{0001f44f}\u{0001f3fd}", "clap_tone4": "\u{0001f44f}\u{0001f3fe}", "clap_tone5": "\u{0001f44f}\u{0001f3ff}", "wave_tone1": "\u{0001f44b}\u{0001f3fb}", "wave_tone2": "\u{0001f44b}\u{0001f3fc}", "wave_tone3": "\u{0001f44b}\u{0001f3fd}", "wave_tone4": "\u{0001f44b}\u{0001f3fe}", "wave_tone5": "\u{0001f44b}\u{0001f3ff}", "thumbsup_tone1": "\u{0001f44d}\u{0001f3fb}", "thumbsup_tone2": "\u{0001f44d}\u{0001f3fc}", "thumbsup_tone3": "\u{0001f44d}\u{0001f3fd}", "thumbsup_tone4": "\u{0001f44d}\u{0001f3fe}", "thumbsup_tone5": "\u{0001f44d}\u{0001f3ff}", "thumbsdown_tone1": "\u{0001f44e}\u{0001f3fb}", "thumbsdown_tone2": "\u{0001f44e}\u{0001f3fc}", "thumbsdown_tone3": "\u{0001f44e}\u{0001f3fd}", "thumbsdown_tone4": "\u{0001f44e}\u{0001f3fe}", "thumbsdown_tone5": "\u{0001f44e}\u{0001f3ff}", "punch_tone1": "\u{0001f44a}\u{0001f3fb}", "punch_tone2": "\u{0001f44a}\u{0001f3fc}", "punch_tone3": "\u{0001f44a}\u{0001f3fd}", "punch_tone4": "\u{0001f44a}\u{0001f3fe}", "punch_tone5": "\u{0001f44a}\u{0001f3ff}", "fist_tone1": "\u{0000270a}\u{0001f3fb}", "fist_tone2": "\u{0000270a}\u{0001f3fc}", "fist_tone3": "\u{0000270a}\u{0001f3fd}", "fist_tone4": "\u{0000270a}\u{0001f3fe}", "fist_tone5": "\u{0000270a}\u{0001f3ff}", "v_tone1": "\u{0000270c}\u{0001f3fb}", "v_tone2": "\u{0000270c}\u{0001f3fc}", "v_tone3": "\u{0000270c}\u{0001f3fd}", "v_tone4": "\u{0000270c}\u{0001f3fe}", "v_tone5": "\u{0000270c}\u{0001f3ff}", "ok_hand_tone1": "\u{0001f44c}\u{0001f3fb}", "ok_hand_tone2": "\u{0001f44c}\u{0001f3fc}", "ok_hand_tone3": "\u{0001f44c}\u{0001f3fd}", "ok_hand_tone4": "\u{0001f44c}\u{0001f3fe}", "ok_hand_tone5": "\u{0001f44c}\u{0001f3ff}", "raised_hand_tone1": "\u{0000270b}\u{0001f3fb}", "raised_hand_tone2": "\u{0000270b}\u{0001f3fc}", "raised_hand_tone3": "\u{0000270b}\u{0001f3fd}", "raised_hand_tone4": "\u{0000270b}\u{0001f3fe}", "raised_hand_tone5": "\u{0000270b}\u{0001f3ff}", "open_hands_tone1": "\u{0001f450}\u{0001f3fb}", "open_hands_tone2": "\u{0001f450}\u{0001f3fc}", "open_hands_tone3": "\u{0001f450}\u{0001f3fd}", "open_hands_tone4": "\u{0001f450}\u{0001f3fe}", "open_hands_tone5": "\u{0001f450}\u{0001f3ff}", "muscle_tone1": "\u{0001f4aa}\u{0001f3fb}", "muscle_tone2": "\u{0001f4aa}\u{0001f3fc}", "muscle_tone3": "\u{0001f4aa}\u{0001f3fd}", "muscle_tone4": "\u{0001f4aa}\u{0001f3fe}", "muscle_tone5": "\u{0001f4aa}\u{0001f3ff}", "pray_tone1": "\u{0001f64f}\u{0001f3fb}", "pray_tone2": "\u{0001f64f}\u{0001f3fc}", "pray_tone3": "\u{0001f64f}\u{0001f3fd}", "pray_tone4": "\u{0001f64f}\u{0001f3fe}", "pray_tone5": "\u{0001f64f}\u{0001f3ff}", "point_up_tone1": "\u{0000261d}\u{0001f3fb}", "point_up_tone2": "\u{0000261d}\u{0001f3fc}", "point_up_tone3": "\u{0000261d}\u{0001f3fd}", "point_up_tone4": "\u{0000261d}\u{0001f3fe}", "point_up_tone5": "\u{0000261d}\u{0001f3ff}", "point_up_2_tone1": "\u{0001f446}\u{0001f3fb}", "point_up_2_tone2": "\u{0001f446}\u{0001f3fc}", "point_up_2_tone3": "\u{0001f446}\u{0001f3fd}", "point_up_2_tone4": "\u{0001f446}\u{0001f3fe}", "point_up_2_tone5": "\u{0001f446}\u{0001f3ff}", "point_down_tone1": "\u{0001f447}\u{0001f3fb}", "point_down_tone2": "\u{0001f447}\u{0001f3fc}", "point_down_tone3": "\u{0001f447}\u{0001f3fd}", "point_down_tone4": "\u{0001f447}\u{0001f3fe}", "point_down_tone5": "\u{0001f447}\u{0001f3ff}", "point_left_tone1": "\u{0001f448}\u{0001f3fb}", "point_left_tone2": "\u{0001f448}\u{0001f3fc}", "point_left_tone3": "\u{0001f448}\u{0001f3fd}", "point_left_tone4": "\u{0001f448}\u{0001f3fe}", "point_left_tone5": "\u{0001f448}\u{0001f3ff}", "point_right_tone1": "\u{0001f449}\u{0001f3fb}", "point_right_tone2": "\u{0001f449}\u{0001f3fc}", "point_right_tone3": "\u{0001f449}\u{0001f3fd}", "point_right_tone4": "\u{0001f449}\u{0001f3fe}", "point_right_tone5": "\u{0001f449}\u{0001f3ff}", "middle_finger_tone1": "\u{0001f595}\u{0001f3fb}", "middle_finger_tone2": "\u{0001f595}\u{0001f3fc}", "middle_finger_tone3": "\u{0001f595}\u{0001f3fd}", "middle_finger_tone4": "\u{0001f595}\u{0001f3fe}", "middle_finger_tone5": "\u{0001f595}\u{0001f3ff}", "hand_splayed_tone1": "\u{0001f590}\u{0001f3fb}", "hand_splayed_tone2": "\u{0001f590}\u{0001f3fc}", "hand_splayed_tone3": "\u{0001f590}\u{0001f3fd}", "hand_splayed_tone4": "\u{0001f590}\u{0001f3fe}", "hand_splayed_tone5": "\u{0001f590}\u{0001f3ff}", "metal_tone1": "\u{0001f918}\u{0001f3fb}", "metal_tone2": "\u{0001f918}\u{0001f3fc}", "metal_tone3": "\u{0001f918}\u{0001f3fd}", "metal_tone4": "\u{0001f918}\u{0001f3fe}", "metal_tone5": "\u{0001f918}\u{0001f3ff}", "vulcan_tone1": "\u{0001f596}\u{0001f3fb}", "vulcan_tone2": "\u{0001f596}\u{0001f3fc}", "vulcan_tone3": "\u{0001f596}\u{0001f3fd}", "vulcan_tone4": "\u{0001f596}\u{0001f3fe}", "vulcan_tone5": "\u{0001f596}\u{0001f3ff}", "writing_hand_tone1": "\u{0000270d}\u{0001f3fb}", "writing_hand_tone2": "\u{0000270d}\u{0001f3fc}", "writing_hand_tone3": "\u{0000270d}\u{0001f3fd}", "writing_hand_tone4": "\u{0000270d}\u{0001f3fe}", "writing_hand_tone5": "\u{0000270d}\u{0001f3ff}", "nail_care_tone1": "\u{0001f485}\u{0001f3fb}", "nail_care_tone2": "\u{0001f485}\u{0001f3fc}", "nail_care_tone3": "\u{0001f485}\u{0001f3fd}", "nail_care_tone4": "\u{0001f485}\u{0001f3fe}", "nail_care_tone5": "\u{0001f485}\u{0001f3ff}", "ear_tone1": "\u{0001f442}\u{0001f3fb}", "ear_tone2": "\u{0001f442}\u{0001f3fc}", "ear_tone3": "\u{0001f442}\u{0001f3fd}", "ear_tone4": "\u{0001f442}\u{0001f3fe}", "ear_tone5": "\u{0001f442}\u{0001f3ff}", "nose_tone1": "\u{0001f443}\u{0001f3fb}", "nose_tone2": "\u{0001f443}\u{0001f3fc}", "nose_tone3": "\u{0001f443}\u{0001f3fd}", "nose_tone4": "\u{0001f443}\u{0001f3fe}", "nose_tone5": "\u{0001f443}\u{0001f3ff}", "baby_tone1": "\u{0001f476}\u{0001f3fb}", "baby_tone2": "\u{0001f476}\u{0001f3fc}", "baby_tone3": "\u{0001f476}\u{0001f3fd}", "baby_tone4": "\u{0001f476}\u{0001f3fe}", "baby_tone5": "\u{0001f476}\u{0001f3ff}", "boy_tone1": "\u{0001f466}\u{0001f3fb}", "boy_tone2": "\u{0001f466}\u{0001f3fc}", "boy_tone3": "\u{0001f466}\u{0001f3fd}", "boy_tone4": "\u{0001f466}\u{0001f3fe}", "boy_tone5": "\u{0001f466}\u{0001f3ff}", "girl_tone1": "\u{0001f467}\u{0001f3fb}", "girl_tone2": "\u{0001f467}\u{0001f3fc}", "girl_tone3": "\u{0001f467}\u{0001f3fd}", "girl_tone4": "\u{0001f467}\u{0001f3fe}", "girl_tone5": "\u{0001f467}\u{0001f3ff}", "man_tone1": "\u{0001f468}\u{0001f3fb}", "man_tone2": "\u{0001f468}\u{0001f3fc}", "man_tone3": "\u{0001f468}\u{0001f3fd}", "man_tone4": "\u{0001f468}\u{0001f3fe}", "man_tone5": "\u{0001f468}\u{0001f3ff}", "woman_tone1": "\u{0001f469}\u{0001f3fb}", "woman_tone2": "\u{0001f469}\u{0001f3fc}", "woman_tone3": "\u{0001f469}\u{0001f3fd}", "woman_tone4": "\u{0001f469}\u{0001f3fe}", "woman_tone5": "\u{0001f469}\u{0001f3ff}", "person_with_blond_hair_tone1": "\u{0001f471}\u{0001f3fb}", "person_with_blond_hair_tone2": "\u{0001f471}\u{0001f3fc}", "person_with_blond_hair_tone3": "\u{0001f471}\u{0001f3fd}", "person_with_blond_hair_tone4": "\u{0001f471}\u{0001f3fe}", "person_with_blond_hair_tone5": "\u{0001f471}\u{0001f3ff}", "older_man_tone1": "\u{0001f474}\u{0001f3fb}", "older_man_tone2": "\u{0001f474}\u{0001f3fc}", "older_man_tone3": "\u{0001f474}\u{0001f3fd}", "older_man_tone4": "\u{0001f474}\u{0001f3fe}", "older_man_tone5": "\u{0001f474}\u{0001f3ff}", "older_woman_tone1": "\u{0001f475}\u{0001f3fb}", "older_woman_tone2": "\u{0001f475}\u{0001f3fc}", "older_woman_tone3": "\u{0001f475}\u{0001f3fd}", "older_woman_tone4": "\u{0001f475}\u{0001f3fe}", "older_woman_tone5": "\u{0001f475}\u{0001f3ff}", "man_with_gua_pi_mao_tone1": "\u{0001f472}\u{0001f3fb}", "man_with_gua_pi_mao_tone2": "\u{0001f472}\u{0001f3fc}", "man_with_gua_pi_mao_tone3": "\u{0001f472}\u{0001f3fd}", "man_with_gua_pi_mao_tone4": "\u{0001f472}\u{0001f3fe}", "man_with_gua_pi_mao_tone5": "\u{0001f472}\u{0001f3ff}", "man_with_turban_tone1": "\u{0001f473}\u{0001f3fb}", "man_with_turban_tone2": "\u{0001f473}\u{0001f3fc}", "man_with_turban_tone3": "\u{0001f473}\u{0001f3fd}", "man_with_turban_tone4": "\u{0001f473}\u{0001f3fe}", "man_with_turban_tone5": "\u{0001f473}\u{0001f3ff}", "cop_tone1": "\u{0001f46e}\u{0001f3fb}", "cop_tone2": "\u{0001f46e}\u{0001f3fc}", "cop_tone3": "\u{0001f46e}\u{0001f3fd}", "cop_tone4": "\u{0001f46e}\u{0001f3fe}", "cop_tone5": "\u{0001f46e}\u{0001f3ff}", "construction_worker_tone1": "\u{0001f477}\u{0001f3fb}", "construction_worker_tone2": "\u{0001f477}\u{0001f3fc}", "construction_worker_tone3": "\u{0001f477}\u{0001f3fd}", "construction_worker_tone4": "\u{0001f477}\u{0001f3fe}", "construction_worker_tone5": "\u{0001f477}\u{0001f3ff}", "guardsman_tone1": "\u{0001f482}\u{0001f3fb}", "guardsman_tone2": "\u{0001f482}\u{0001f3fc}", "guardsman_tone3": "\u{0001f482}\u{0001f3fd}", "guardsman_tone4": "\u{0001f482}\u{0001f3fe}", "guardsman_tone5": "\u{0001f482}\u{0001f3ff}", "santa_tone1": "\u{0001f385}\u{0001f3fb}", "santa_tone2": "\u{0001f385}\u{0001f3fc}", "santa_tone3": "\u{0001f385}\u{0001f3fd}", "santa_tone4": "\u{0001f385}\u{0001f3fe}", "santa_tone5": "\u{0001f385}\u{0001f3ff}", "angel_tone1": "\u{0001f47c}\u{0001f3fb}", "angel_tone2": "\u{0001f47c}\u{0001f3fc}", "angel_tone3": "\u{0001f47c}\u{0001f3fd}", "angel_tone4": "\u{0001f47c}\u{0001f3fe}", "angel_tone5": "\u{0001f47c}\u{0001f3ff}", "princess_tone1": "\u{0001f478}\u{0001f3fb}", "princess_tone2": "\u{0001f478}\u{0001f3fc}", "princess_tone3": "\u{0001f478}\u{0001f3fd}", "princess_tone4": "\u{0001f478}\u{0001f3fe}", "princess_tone5": "\u{0001f478}\u{0001f3ff}", "bride_with_veil_tone1": "\u{0001f470}\u{0001f3fb}", "bride_with_veil_tone2": "\u{0001f470}\u{0001f3fc}", "bride_with_veil_tone3": "\u{0001f470}\u{0001f3fd}", "bride_with_veil_tone4": "\u{0001f470}\u{0001f3fe}", "bride_with_veil_tone5": "\u{0001f470}\u{0001f3ff}", "walking_tone1": "\u{0001f6b6}\u{0001f3fb}", "walking_tone2": "\u{0001f6b6}\u{0001f3fc}", "walking_tone3": "\u{0001f6b6}\u{0001f3fd}", "walking_tone4": "\u{0001f6b6}\u{0001f3fe}", "walking_tone5": "\u{0001f6b6}\u{0001f3ff}", "runner_tone1": "\u{0001f3c3}\u{0001f3fb}", "runner_tone2": "\u{0001f3c3}\u{0001f3fc}", "runner_tone3": "\u{0001f3c3}\u{0001f3fd}", "runner_tone4": "\u{0001f3c3}\u{0001f3fe}", "runner_tone5": "\u{0001f3c3}\u{0001f3ff}", "dancer_tone1": "\u{0001f483}\u{0001f3fb}", "dancer_tone2": "\u{0001f483}\u{0001f3fc}", "dancer_tone3": "\u{0001f483}\u{0001f3fd}", "dancer_tone4": "\u{0001f483}\u{0001f3fe}", "dancer_tone5": "\u{0001f483}\u{0001f3ff}", "bow_tone1": "\u{0001f647}\u{0001f3fb}", "bow_tone2": "\u{0001f647}\u{0001f3fc}", "bow_tone3": "\u{0001f647}\u{0001f3fd}", "bow_tone4": "\u{0001f647}\u{0001f3fe}", "bow_tone5": "\u{0001f647}\u{0001f3ff}", "information_desk_person_tone1": "\u{0001f481}\u{0001f3fb}", "information_desk_person_tone2": "\u{0001f481}\u{0001f3fc}", "information_desk_person_tone3": "\u{0001f481}\u{0001f3fd}", "information_desk_person_tone4": "\u{0001f481}\u{0001f3fe}", "information_desk_person_tone5": "\u{0001f481}\u{0001f3ff}", "no_good_tone1": "\u{0001f645}\u{0001f3fb}", "no_good_tone2": "\u{0001f645}\u{0001f3fc}", "no_good_tone3": "\u{0001f645}\u{0001f3fd}", "no_good_tone4": "\u{0001f645}\u{0001f3fe}", "no_good_tone5": "\u{0001f645}\u{0001f3ff}", "ok_woman_tone1": "\u{0001f646}\u{0001f3fb}", "ok_woman_tone2": "\u{0001f646}\u{0001f3fc}", "ok_woman_tone3": "\u{0001f646}\u{0001f3fd}", "ok_woman_tone4": "\u{0001f646}\u{0001f3fe}", "ok_woman_tone5": "\u{0001f646}\u{0001f3ff}", "raising_hand_tone1": "\u{0001f64b}\u{0001f3fb}", "raising_hand_tone2": "\u{0001f64b}\u{0001f3fc}", "raising_hand_tone3": "\u{0001f64b}\u{0001f3fd}", "raising_hand_tone4": "\u{0001f64b}\u{0001f3fe}", "raising_hand_tone5": "\u{0001f64b}\u{0001f3ff}", "person_with_pouting_face_tone1": "\u{0001f64e}\u{0001f3fb}", "person_with_pouting_face_tone2": "\u{0001f64e}\u{0001f3fc}", "person_with_pouting_face_tone3": "\u{0001f64e}\u{0001f3fd}", "person_with_pouting_face_tone4": "\u{0001f64e}\u{0001f3fe}", "person_with_pouting_face_tone5": "\u{0001f64e}\u{0001f3ff}", "person_frowning_tone1": "\u{0001f64d}\u{0001f3fb}", "person_frowning_tone2": "\u{0001f64d}\u{0001f3fc}", "person_frowning_tone3": "\u{0001f64d}\u{0001f3fd}", "person_frowning_tone4": "\u{0001f64d}\u{0001f3fe}", "person_frowning_tone5": "\u{0001f64d}\u{0001f3ff}", "haircut_tone1": "\u{0001f487}\u{0001f3fb}", "haircut_tone2": "\u{0001f487}\u{0001f3fc}", "haircut_tone3": "\u{0001f487}\u{0001f3fd}", "haircut_tone4": "\u{0001f487}\u{0001f3fe}", "haircut_tone5": "\u{0001f487}\u{0001f3ff}", "massage_tone1": "\u{0001f486}\u{0001f3fb}", "massage_tone2": "\u{0001f486}\u{0001f3fc}", "massage_tone3": "\u{0001f486}\u{0001f3fd}", "massage_tone4": "\u{0001f486}\u{0001f3fe}", "massage_tone5": "\u{0001f486}\u{0001f3ff}", "rowboat_tone1": "\u{0001f6a3}\u{0001f3fb}", "rowboat_tone2": "\u{0001f6a3}\u{0001f3fc}", "rowboat_tone3": "\u{0001f6a3}\u{0001f3fd}", "rowboat_tone4": "\u{0001f6a3}\u{0001f3fe}", "rowboat_tone5": "\u{0001f6a3}\u{0001f3ff}", "swimmer_tone1": "\u{0001f3ca}\u{0001f3fb}", "swimmer_tone2": "\u{0001f3ca}\u{0001f3fc}", "swimmer_tone3": "\u{0001f3ca}\u{0001f3fd}", "swimmer_tone4": "\u{0001f3ca}\u{0001f3fe}", "swimmer_tone5": "\u{0001f3ca}\u{0001f3ff}", "surfer_tone1": "\u{0001f3c4}\u{0001f3fb}", "surfer_tone2": "\u{0001f3c4}\u{0001f3fc}", "surfer_tone3": "\u{0001f3c4}\u{0001f3fd}", "surfer_tone4": "\u{0001f3c4}\u{0001f3fe}", "surfer_tone5": "\u{0001f3c4}\u{0001f3ff}", "bath_tone1": "\u{0001f6c0}\u{0001f3fb}", "bath_tone2": "\u{0001f6c0}\u{0001f3fc}", "bath_tone3": "\u{0001f6c0}\u{0001f3fd}", "bath_tone4": "\u{0001f6c0}\u{0001f3fe}", "bath_tone5": "\u{0001f6c0}\u{0001f3ff}", "basketball_player_tone1": "\u{000026f9}\u{0001f3fb}", "basketball_player_tone2": "\u{000026f9}\u{0001f3fc}", "basketball_player_tone3": "\u{000026f9}\u{0001f3fd}", "basketball_player_tone4": "\u{000026f9}\u{0001f3fe}", "basketball_player_tone5": "\u{000026f9}\u{0001f3ff}", "lifter_tone1": "\u{0001f3cb}\u{0001f3fb}", "lifter_tone2": "\u{0001f3cb}\u{0001f3fc}", "lifter_tone3": "\u{0001f3cb}\u{0001f3fd}", "lifter_tone4": "\u{0001f3cb}\u{0001f3fe}", "lifter_tone5": "\u{0001f3cb}\u{0001f3ff}", "bicyclist_tone1": "\u{0001f6b4}\u{0001f3fb}", "bicyclist_tone2": "\u{0001f6b4}\u{0001f3fc}", "bicyclist_tone3": "\u{0001f6b4}\u{0001f3fd}", "bicyclist_tone4": "\u{0001f6b4}\u{0001f3fe}", "bicyclist_tone5": "\u{0001f6b4}\u{0001f3ff}", "mountain_bicyclist_tone1": "\u{0001f6b5}\u{0001f3fb}", "mountain_bicyclist_tone2": "\u{0001f6b5}\u{0001f3fc}", "mountain_bicyclist_tone3": "\u{0001f6b5}\u{0001f3fd}", "mountain_bicyclist_tone4": "\u{0001f6b5}\u{0001f3fe}", "mountain_bicyclist_tone5": "\u{0001f6b5}\u{0001f3ff}", "horse_racing_tone1": "\u{0001f3c7}\u{0001f3fb}", "horse_racing_tone2": "\u{0001f3c7}\u{0001f3fc}", "horse_racing_tone3": "\u{0001f3c7}\u{0001f3fd}", "horse_racing_tone4": "\u{0001f3c7}\u{0001f3fe}", "horse_racing_tone5": "\u{0001f3c7}\u{0001f3ff}", "spy_tone1": "\u{0001f575}\u{0001f3fb}", "spy_tone2": "\u{0001f575}\u{0001f3fc}", "spy_tone3": "\u{0001f575}\u{0001f3fd}", "spy_tone4": "\u{0001f575}\u{0001f3fe}", "spy_tone5": "\u{0001f575}\u{0001f3ff}", "tone1": "\u{0001f3fb}", "tone2": "\u{0001f3fc}", "tone3": "\u{0001f3fd}", "tone4": "\u{0001f3fe}", "tone5": "\u{0001f3ff}", "prince_tone1": "\u{0001f934}\u{0001f3fb}", "prince_tone2": "\u{0001f934}\u{0001f3fc}", "prince_tone3": "\u{0001f934}\u{0001f3fd}", "prince_tone4": "\u{0001f934}\u{0001f3fe}", "prince_tone5": "\u{0001f934}\u{0001f3ff}", "mrs_claus_tone1": "\u{0001f936}\u{0001f3fb}", "mrs_claus_tone2": "\u{0001f936}\u{0001f3fc}", "mrs_claus_tone3": "\u{0001f936}\u{0001f3fd}", "mrs_claus_tone4": "\u{0001f936}\u{0001f3fe}", "mrs_claus_tone5": "\u{0001f936}\u{0001f3ff}", "man_in_tuxedo_tone1": "\u{0001f935}\u{0001f3fb}", "man_in_tuxedo_tone2": "\u{0001f935}\u{0001f3fc}", "man_in_tuxedo_tone3": "\u{0001f935}\u{0001f3fd}", "man_in_tuxedo_tone4": "\u{0001f935}\u{0001f3fe}", "man_in_tuxedo_tone5": "\u{0001f935}\u{0001f3ff}", "shrug_tone1": "\u{0001f937}\u{0001f3fb}", "shrug_tone2": "\u{0001f937}\u{0001f3fc}", "shrug_tone3": "\u{0001f937}\u{0001f3fd}", "shrug_tone4": "\u{0001f937}\u{0001f3fe}", "shrug_tone5": "\u{0001f937}\u{0001f3ff}", "face_palm_tone1": "\u{0001f926}\u{0001f3fb}", "face_palm_tone2": "\u{0001f926}\u{0001f3fc}", "face_palm_tone3": "\u{0001f926}\u{0001f3fd}", "face_palm_tone4": "\u{0001f926}\u{0001f3fe}", "face_palm_tone5": "\u{0001f926}\u{0001f3ff}", "pregnant_woman_tone1": "\u{0001f930}\u{0001f3fb}", "pregnant_woman_tone2": "\u{0001f930}\u{0001f3fc}", "pregnant_woman_tone3": "\u{0001f930}\u{0001f3fd}", "pregnant_woman_tone4": "\u{0001f930}\u{0001f3fe}", "pregnant_woman_tone5": "\u{0001f930}\u{0001f3ff}", "man_dancing_tone1": "\u{0001f57a}\u{0001f3fb}", "man_dancing_tone2": "\u{0001f57a}\u{0001f3fc}", "man_dancing_tone3": "\u{0001f57a}\u{0001f3fd}", "man_dancing_tone4": "\u{0001f57a}\u{0001f3fe}", "man_dancing_tone5": "\u{0001f57a}\u{0001f3ff}", "selfie_tone1": "\u{0001f933}\u{0001f3fb}", "selfie_tone2": "\u{0001f933}\u{0001f3fc}", "selfie_tone3": "\u{0001f933}\u{0001f3fd}", "selfie_tone4": "\u{0001f933}\u{0001f3fe}", "selfie_tone5": "\u{0001f933}\u{0001f3ff}", "fingers_crossed_tone1": "\u{0001f91e}\u{0001f3fb}", "fingers_crossed_tone2": "\u{0001f91e}\u{0001f3fc}", "fingers_crossed_tone3": "\u{0001f91e}\u{0001f3fd}", "fingers_crossed_tone4": "\u{0001f91e}\u{0001f3fe}", "fingers_crossed_tone5": "\u{0001f91e}\u{0001f3ff}", "call_me_tone1": "\u{0001f919}\u{0001f3fb}", "call_me_tone2": "\u{0001f919}\u{0001f3fc}", "call_me_tone3": "\u{0001f919}\u{0001f3fd}", "call_me_tone4": "\u{0001f919}\u{0001f3fe}", "call_me_tone5": "\u{0001f919}\u{0001f3ff}", "left_facing_fist_tone1": "\u{0001f91b}\u{0001f3fb}", "left_facing_fist_tone2": "\u{0001f91b}\u{0001f3fc}", "left_facing_fist_tone3": "\u{0001f91b}\u{0001f3fd}", "left_facing_fist_tone4": "\u{0001f91b}\u{0001f3fe}", "left_facing_fist_tone5": "\u{0001f91b}\u{0001f3ff}", "right_facing_fist_tone1": "\u{0001f91c}\u{0001f3fb}", "right_facing_fist_tone2": "\u{0001f91c}\u{0001f3fc}", "right_facing_fist_tone3": "\u{0001f91c}\u{0001f3fd}", "right_facing_fist_tone4": "\u{0001f91c}\u{0001f3fe}", "right_facing_fist_tone5": "\u{0001f91c}\u{0001f3ff}", "raised_back_of_hand_tone1": "\u{0001f91a}\u{0001f3fb}", "raised_back_of_hand_tone2": "\u{0001f91a}\u{0001f3fc}", "raised_back_of_hand_tone3": "\u{0001f91a}\u{0001f3fd}", "raised_back_of_hand_tone4": "\u{0001f91a}\u{0001f3fe}", "raised_back_of_hand_tone5": "\u{0001f91a}\u{0001f3ff}", "handshake_tone1": "\u{0001f91d}\u{0001f3fb}", "handshake_tone2": "\u{0001f91d}\u{0001f3fc}", "handshake_tone3": "\u{0001f91d}\u{0001f3fd}", "handshake_tone4": "\u{0001f91d}\u{0001f3fe}", "handshake_tone5": "\u{0001f91d}\u{0001f3ff}", "cartwheel_tone1": "\u{0001f938}\u{0001f3fb}", "cartwheel_tone2": "\u{0001f938}\u{0001f3fc}", "cartwheel_tone3": "\u{0001f938}\u{0001f3fd}", "cartwheel_tone4": "\u{0001f938}\u{0001f3fe}", "cartwheel_tone5": "\u{0001f938}\u{0001f3ff}", "wrestlers_tone1": "\u{0001f93c}\u{0001f3fb}", "wrestlers_tone2": "\u{0001f93c}\u{0001f3fc}", "wrestlers_tone3": "\u{0001f93c}\u{0001f3fd}", "wrestlers_tone4": "\u{0001f93c}\u{0001f3fe}", "wrestlers_tone5": "\u{0001f93c}\u{0001f3ff}", "water_polo_tone1": "\u{0001f93d}\u{0001f3fb}", "water_polo_tone2": "\u{0001f93d}\u{0001f3fc}", "water_polo_tone3": "\u{0001f93d}\u{0001f3fd}", "water_polo_tone4": "\u{0001f93d}\u{0001f3fe}", "water_polo_tone5": "\u{0001f93d}\u{0001f3ff}", "handball_tone1": "\u{0001f93e}\u{0001f3fb}", "handball_tone2": "\u{0001f93e}\u{0001f3fc}", "handball_tone3": "\u{0001f93e}\u{0001f3fd}", "handball_tone4": "\u{0001f93e}\u{0001f3fe}", "handball_tone5": "\u{0001f93e}\u{0001f3ff}", "juggling_tone1": "\u{0001f939}\u{0001f3fb}", "juggling_tone2": "\u{0001f939}\u{0001f3fc}", "juggling_tone3": "\u{0001f939}\u{0001f3fd}", "juggling_tone4": "\u{0001f939}\u{0001f3fe}", "juggling_tone5": "\u{0001f939}\u{0001f3ff}", "speech_left": "\u{0001f5e8}", "eject": "\u{000023cf}", "gay_pride_flag": "\u{0001f3f3}\u{0001f308}", "cowboy": "\u{0001f920}", "clown": "\u{0001f921}", "nauseated_face": "\u{0001f922}", "rofl": "\u{0001f923}", "drooling_face": "\u{0001f924}", "lying_face": "\u{0001f925}", "sneezing_face": "\u{0001f927}", "prince": "\u{0001f934}", "man_in_tuxedo": "\u{0001f935}", "mrs_claus": "\u{0001f936}", "face_palm": "\u{0001f926}", "shrug": "\u{0001f937}", "pregnant_woman": "\u{0001f930}", "selfie": "\u{0001f933}", "man_dancing": "\u{0001f57a}", "call_me": "\u{0001f919}", "raised_back_of_hand": "\u{0001f91a}", "left_facing_fist": "\u{0001f91b}", "right_facing_fist": "\u{0001f91c}", "handshake": "\u{0001f91d}", "fingers_crossed": "\u{0001f91e}", "black_heart": "\u{0001f5a4}", "eagle": "\u{0001f985}", "duck": "\u{0001f986}", "bat": "\u{0001f987}", "shark": "\u{0001f988}", "owl": "\u{0001f989}", "fox": "\u{0001f98a}", "butterfly": "\u{0001f98b}", "deer": "\u{0001f98c}", "gorilla": "\u{0001f98d}", "lizard": "\u{0001f98e}", "rhino": "\u{0001f98f}", "wilted_rose": "\u{0001f940}", "croissant": "\u{0001f950}", "avocado": "\u{0001f951}", "cucumber": "\u{0001f952}", "bacon": "\u{0001f953}", "potato": "\u{0001f954}", "carrot": "\u{0001f955}", "french_bread": "\u{0001f956}", "salad": "\u{0001f957}", "shallow_pan_of_food": "\u{0001f958}", "stuffed_flatbread": "\u{0001f959}", "champagne_glass": "\u{0001f942}", "tumbler_glass": "\u{0001f943}", "spoon": "\u{0001f944}", "octagonal_sign": "\u{0001f6d1}", "shopping_cart": "\u{0001f6d2}", "scooter": "\u{0001f6f4}", "motor_scooter": "\u{0001f6f5}", "canoe": "\u{0001f6f6}", "cartwheel": "\u{0001f938}", "juggling": "\u{0001f939}", "wrestlers": "\u{0001f93c}", "boxing_glove": "\u{0001f94a}", "martial_arts_uniform": "\u{0001f94b}", "water_polo": "\u{0001f93d}", "handball": "\u{0001f93e}", "goal": "\u{0001f945}", "fencer": "\u{0001f93a}", "first_place": "\u{0001f947}", "second_place": "\u{0001f948}", "third_place": "\u{0001f949}", "drum": "\u{0001f941}", "shrimp": "\u{0001f990}", "squid": "\u{0001f991}", "egg": "\u{0001f95a}", "milk": "\u{0001f95b}", "peanuts": "\u{0001f95c}", "kiwi": "\u{0001f95d}", "pancakes": "\u{0001f95e}", "regional_indicator_z": "\u{0001f1ff}", "regional_indicator_y": "\u{0001f1fe}", "regional_indicator_x": "\u{0001f1fd}", "regional_indicator_w": "\u{0001f1fc}", "regional_indicator_v": "\u{0001f1fb}", "regional_indicator_u": "\u{0001f1fa}", "regional_indicator_t": "\u{0001f1f9}", "regional_indicator_s": "\u{0001f1f8}", "regional_indicator_r": "\u{0001f1f7}", "regional_indicator_q": "\u{0001f1f6}", "regional_indicator_p": "\u{0001f1f5}", "regional_indicator_o": "\u{0001f1f4}", "regional_indicator_n": "\u{0001f1f3}", "regional_indicator_m": "\u{0001f1f2}", "regional_indicator_l": "\u{0001f1f1}", "regional_indicator_k": "\u{0001f1f0}", "regional_indicator_j": "\u{0001f1ef}", "regional_indicator_i": "\u{0001f1ee}", "regional_indicator_h": "\u{0001f1ed}", "regional_indicator_g": "\u{0001f1ec}", "regional_indicator_f": "\u{0001f1eb}", "regional_indicator_e": "\u{0001f1ea}", "regional_indicator_d": "\u{0001f1e9}", "regional_indicator_c": "\u{0001f1e8}", "regional_indicator_b": "\u{0001f1e7}", "regional_indicator_a": "\u{0001f1e6}" ] static func transform(string: String) -> String { let oldString = string as NSString var transformedString = string as NSString let regex = try? NSRegularExpression(pattern: ":([-+\\w]+):", options: []) let matches = regex?.matches(in: transformedString as String, options: [], range: NSRange(location: 0, length: transformedString.length)) ?? [] for result in matches { guard result.numberOfRanges == 2 else { continue } let shortname = oldString.substring(with: result.rangeAt(1)) if let emoji = values[shortname] { transformedString = transformedString.replacingOccurrences(of: ":\(shortname):", with: emoji) as NSString } } return transformedString as String } }
3ab931edbc7591a9d7ff4c2529f7592e
42.070658
151
0.514007
false
false
false
false
MengQuietly/MQDouYuTV
refs/heads/master
MQDouYuTV/MQDouYuTV/Classes/Main/View/MQRecommendBaseCell.swift
mit
1
// // MQRecommendBaseCell.swift // MQDouYuTV // // Created by mengmeng on 16/12/28. // Copyright © 2016年 mengQuietly. All rights reserved. // 推荐界面:抽取normalCell & prettyCell 基础类 import UIKit import Kingfisher class MQRecommendBaseCell: UICollectionViewCell { // MARK:-控件属性 @IBOutlet weak var anchorRoomImg: UIImageView! @IBOutlet weak var anchorRoomOnLine: UIButton! @IBOutlet weak var anchorNickName: UIButton! // MARK:-定义模型属性 var anchorModel:MQAnchorModel?{ didSet { guard let anchorModel = anchorModel else { return } guard let roomImgUrl:URL = URL(string: anchorModel.vertical_src) else { return } anchorRoomImg.kf.setImage(with: roomImgUrl) anchorNickName.setTitle(anchorModel.nickname, for: UIControlState.normal) var online = "" if anchorModel.online >= 10000{ online = "\(Int(anchorModel.online)/10000)万" } else { online = "\(anchorModel.online)" } anchorRoomOnLine.setTitle(online, for: UIControlState.normal) } } }
34c5fcc431138b35e3aab4baa81c0dfe
31.941176
92
0.6375
false
false
false
false
Chriskuei/Bon-for-Mac
refs/heads/master
Bon/BonButton.swift
mit
1
// // BonButton.swift // Bon // // Created by Chris on 16/5/14. // Copyright © 2016年 Chris. All rights reserved. // import Cocoa class BonButton: NSButton { fileprivate let cursor = NSCursor.pointingHand fileprivate var normalStateImage: NSImage? fileprivate var highlightedStateImage: NSImage? fileprivate var trackingArea: NSTrackingArea? override func resetCursorRects() { addCursorRect(bounds, cursor: cursor) cursor.set() } override init(frame frameRect: NSRect) { super.init(frame: frameRect) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } override func awakeFromNib() { super.awakeFromNib() commonInit() } func commonInit() { } func setImages(_ normalImage: String, highlitedImage: String) { self.setButtonType(.momentaryChange) normalStateImage = NSImage(named: NSImage.Name(rawValue: normalImage)) highlightedStateImage = NSImage(named: NSImage.Name(rawValue: highlitedImage)) } func resetTrackingArea() { trackingArea = nil if let normalStateImage = normalStateImage { image = normalStateImage } } fileprivate func createTrackingAreaIfNeeded() { if trackingArea == nil { trackingArea = NSTrackingArea(rect: CGRect.zero, options: [NSTrackingArea.Options.inVisibleRect, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil) } } override func updateTrackingAreas() { super.updateTrackingAreas() createTrackingAreaIfNeeded() if !trackingAreas.contains(trackingArea!) { addTrackingArea(trackingArea!) } } override func mouseEntered(with theEvent: NSEvent) { if let highlightedImage = highlightedStateImage { image = highlightedImage } } override func mouseExited(with theEvent: NSEvent) { if let normalStateImage = normalStateImage { image = normalStateImage } } }
394dc4a2f2d911445f87798f3d6568d9
25.831325
220
0.628648
false
false
false
false
mabels/ipaddress
refs/heads/main
swift/Sources/IpAddress/prefix.swift
mit
1
//import IpBits from './ip_bits'; import BigInt typealias From = (_ source: Prefix,_ num: UInt8) -> Prefix?; public class Prefix { public let num: UInt8; public let ip_bits: IpBits; let net_mask: BigUInt; let vt_from: From; init(num: UInt8, ip_bits: IpBits, net_mask: BigUInt, vt_from: @escaping From) { self.num = num; self.ip_bits = ip_bits; self.net_mask = net_mask; self.vt_from = vt_from; } public func clone() -> Prefix { return Prefix( num: self.num, ip_bits: self.ip_bits, net_mask: self.net_mask, vt_from: self.vt_from ); } public func eq(_ other: Prefix)-> Bool { return self.ip_bits.version == other.ip_bits.version && self.num == other.num; } public func ne(_ other: Prefix)-> Bool { return !self.eq(other); } public func cmp(_ oth: Prefix)-> Int { if (self.ip_bits.version != oth.ip_bits.version && self.ip_bits.version == IpVersion.V4) { return -1; } else if (self.ip_bits.version != oth.ip_bits.version && self.ip_bits.version == IpVersion.V6) { return 1; } else { if (self.num < oth.num) { return -1; } else if (self.num > oth.num) { return 1; } else { return 0; } } } public func from(_ num: UInt8)-> Prefix? { return (self.vt_from)(self, num); } public func to_ip_str() -> String { return self.ip_bits.vt_as_compressed_string(self.ip_bits, self.net_mask); } public func size() -> BigUInt { return BigUInt(1) << Int(self.ip_bits.bits - self.num); } public class func new_netmask(_ prefix: UInt8, _ bits: UInt8) -> BigUInt { var mask = BigUInt(0); let host_prefix = bits - prefix; for i in stride(from:UInt8(0), to: prefix, by: 1) { // console.log(">>>", i, host_prefix, mask); mask = mask + (BigUInt(1) << Int(host_prefix + i)); } return mask } public func netmask() -> BigUInt { return self.net_mask; } public func get_prefix() -> UInt8 { return self.num; } // The hostmask is the contrary of the subnet mask, // as it shows the bits that can change within the // hosts // // prefix = IPAddress::Prefix32.new 24 // // prefix.hostmask // // => "0.0.0.255" // public func host_mask() -> BigUInt { var ret = BigUInt(0); for _ in 1...(self.ip_bits.bits - self.num) { ret = (ret << 1) + BigUInt(1); } return ret; } // // Returns the length of the host portion // of a netmask. // // prefix = Prefix128.new 96 // // prefix.host_prefix // // => 128 // public func host_prefix() -> UInt8 { return self.ip_bits.bits - self.num; } // // Transforms the prefix into a string of bits // representing the netmask // // prefix = IPAddress::Prefix128.new 64 // // prefix.bits // // => "1111111111111111111111111111111111111111111111111111111111111111" // "0000000000000000000000000000000000000000000000000000000000000000" // public func bits() -> String { return String(self.netmask(), radix: 2); } // #[allow(dead_code)] // public net_mask(&self) -> BigUint { // return (self.in_mask.clone() >> (self.host_prefix() as usize)) << (self.host_prefix() as usize); // } public func to_s()-> String { return String(self.get_prefix()); } //#[allow(dead_code)] // public inspect(&self) -> String { // return self.to_s(); // } public func to_i() -> UInt8 { return self.get_prefix(); } public func add_prefix(_ other: Prefix) -> Prefix? { return self.from(self.get_prefix() + other.get_prefix()); } public func add(_ other: UInt8) -> Prefix? { return self.from(self.get_prefix() + other) } public func sub_prefix(_ other: Prefix) -> Prefix? { return self.sub(other.get_prefix()); } public func sub(_ other: UInt8) -> Prefix? { if (other > self.get_prefix()) { return self.from(other - self.get_prefix()); } return self.from(self.get_prefix() - other); } }
95c1e828403f994ad47fb771be3eec68
23.842424
105
0.574042
false
false
false
false
frajaona/LiFXSwiftKit
refs/heads/master
Sources/LiFXDeviceManager.swift
apache-2.0
1
/* * Copyright (C) 2016 Fred Rajaona * * 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 public protocol LiFXDeviceManagerObserver { var observerHashValue: String { get } func onDeviceListChanged(_ newList: [LiFXDevice]) } public class LiFXDeviceManager { public static let sharedInstance = LiFXDeviceManager() public var devices = [String: LiFXDevice]() #if os(OSX) fileprivate var session = LiFXSession(socket: LiFXSocksSocket()) #else fileprivate var session = LiFXSession(socket: LiFXCASSocket()) #endif public var broadcastAddress: String? { get { return session.broadcastAddress ?? LiFXSession.DefaultBroadcastAddress } set { session.broadcastAddress = newValue } } fileprivate var deviceListObservable = [String: LiFXDeviceManagerObserver]() init() { session.delegate = self } public func registerDeviceListObserver(_ observer: LiFXDeviceManagerObserver) { if deviceListObservable[observer.observerHashValue] == nil { deviceListObservable[observer.observerHashValue] = observer } } public func unregisterDeviceListObserver(_ observer: LiFXDeviceManagerObserver) { deviceListObservable[observer.observerHashValue] = nil } public func loadDevices() { if session.isConnected() { notifyDeviceListObservers() } else { // Use default discovery interval session.start(withDiscoveryInterval: -1) } } public func refreshDeviceList() { if session.isConnected() { session.discoverDevices() } } public func switchOnDevices() { for (_, device) in devices { device.switchOn() } } public func switchOffDevices() { for (_, device) in devices { device.switchOff() } } public func switchOn(_ deviceUid: String) { for (_, device) in devices { if device.uid == deviceUid { device.switchOn() } } } public func switchOff(_ deviceUid: String) { for (_, device) in devices { if device.uid == deviceUid { device.switchOff() } } } public func switchOnGroup(_ group: String) { for (_, device) in devices { if let deviceGroup = device.group , deviceGroup.label == group { device.switchOn() } } } public func switchOffGroup(_ group: String) { for (_, device) in devices { if let deviceGroup = device.group , deviceGroup.label == group { device.switchOff() } } } public func toggle(_ deviceUid: String) { for (_, device) in devices { if device.uid == deviceUid { device.toggle() } } } public func toggleDevices() { for (_, device) in devices { device.toggle() } } public func toggleGroup(_ group: String) { for (_, device) in devices { if let deviceGroup = device.group , deviceGroup.label == group { device.toggle() } } } public func getDevicePowers() { for (_, device) in devices { device.getPower() } } public func getPower(_ deviceUid: String) { for (_, device) in devices { if device.uid == deviceUid { device.getPower() } } } public func getDeviceInfo() { for (_, device) in devices { device.getInfo() } } public func getInfo(_ deviceUid: String) { for (_, device) in devices { if device.uid == deviceUid { device.getInfo() } } } public func setBrightness(_ brightness: Int) { for (_, device) in devices { device.setBrightness(brightness) } } public func setBrightness(_ deviceUid: String, brightness: Int) { for (_, device) in devices { if device.uid == deviceUid { device.setBrightness(brightness) } } } func cancelDeviceLoading() { session.stop() } func notifyDeviceListObservers() { var newList = [LiFXDevice]() for (_, device) in devices { newList.append(device) } for (_, observer) in deviceListObservable { observer.onDeviceListChanged(newList) } } } extension LiFXDeviceManager: LiFXSessionDelegate { func liFXSession(_ session: LiFXSession, didReceiveMessage message: LiFXMessage, fromAddress address: String) { switch message.messageType { case LiFXMessage.MessageType.deviceStateService: if devices[address] == nil { devices[address] = LiFXDevice(fromMessage: message, address: address, session: session) Log.debug("Found new device with IP address: \(address)") notifyDeviceListObservers() devices[address]!.getGroup() devices[address]!.getInfo() } default: if let device = devices[address] { device.onNewMessage(message) } break } } }
9417c589f8d902595e63128f2efcf4c5
26.438914
115
0.560026
false
false
false
false
fuzzymeme/TutorApp
refs/heads/master
TutorTests/JsonModelReaderTests.swift
mit
1
// // JsonModelReaderTests.swift // Tutor // // Created by Fuzzymeme on 31/05/2017. // Copyright © 2017 Fuzzymeme. All rights reserved. // import XCTest @testable import Tutor class JsonModelReaderTests: XCTestCase { private var reader = JsonModelReader() override func setUp() { super.setUp() reader = JsonModelReader() } func test_retrieveFromJsonFile_withSimpleFormatNoGapHistoryOrWrongsAnswers() { let actual = reader.retrieveFromJsonFile(filename: "test.json", forceFromBundle: true) let expected = Helper.sampleKnowledgeEntries() XCTAssertEqual(expected[0], actual[0]) XCTAssertEqual(expected[1], actual[1]) XCTAssertEqual(expected[2], actual[2]) XCTAssertEqual(expected[3], actual[3]) XCTAssertEqual(expected[4], actual[4]) XCTAssert(expected == actual) } }
f800dd778336625042851af0caa4773e
25.228571
94
0.648148
false
true
false
false
korgx9/QRCodeReader.swift
refs/heads/master
Example/QRCodeReader.swift/ViewController.swift
mit
1
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import AVFoundation import UIKit class ViewController: UIViewController, QRCodeReaderViewControllerDelegate { @IBOutlet weak var previewView: UIView! lazy var reader: QRCodeReader = QRCodeReader() lazy var readerVC: QRCodeReaderViewController = { let builder = QRCodeReaderViewControllerBuilder { $0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObjectTypeQRCode], captureDevicePosition: .back) $0.showTorchButton = true } return QRCodeReaderViewController(builder: builder) }() // MARK: - Actions private func checkScanPermissions() -> Bool { do { return try QRCodeReader.supportsMetadataObjectTypes() } catch let error as NSError { let alert: UIAlertController? switch error.code { case -11852: alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert) alert?.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in DispatchQueue.main.async { if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(settingsURL) } } })) alert?.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) case -11814: alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert) alert?.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) default: alert = nil } guard let vc = alert else { return false } present(vc, animated: true, completion: nil) return false } } @IBAction func scanInModalAction(_ sender: AnyObject) { guard checkScanPermissions() else { return } readerVC.modalPresentationStyle = .formSheet readerVC.delegate = self readerVC.completionBlock = { (result: QRCodeReaderResult?) in if let result = result { print("Completion with result: \(result.value) of type \(result.metadataType)") } } present(readerVC, animated: true, completion: nil) } @IBAction func scanInPreviewAction(_ sender: Any) { guard checkScanPermissions(), !reader.isRunning else { return } reader.previewLayer.frame = previewView.bounds previewView.layer.addSublayer(reader.previewLayer) reader.startScanning() reader.didFindCode = { result in let alert = UIAlertController( title: "QRCodeReader", message: String (format:"%@ (of type %@)", result.value, result.metadataType), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) } } // MARK: - QRCodeReader Delegate Methods func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { reader.stopScanning() dismiss(animated: true) { [weak self] in let alert = UIAlertController( title: "QRCodeReader", message: String (format:"%@ (of type %@)", result.value, result.metadataType), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self?.present(alert, animated: true, completion: nil) } } func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) { if let cameraName = newCaptureDevice.device.localizedName { print("Switching capturing to: \(cameraName)") } } func readerDidCancel(_ reader: QRCodeReaderViewController) { reader.stopScanning() dismiss(animated: true, completion: nil) } }
98a096a9fc4b6297f3b6464cc91d4d0c
34.326087
132
0.695179
false
false
false
false
ledwards/ios-twitter-redux
refs/heads/master
Twit/ProfileViewController.swift
mit
1
// // ProfileViewController.swift // Twit // // Created by Lee Edwards on 2/26/16. // Copyright © 2016 Lee Edwards. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var headerImageView: UIImageView! @IBOutlet weak var tweetsCountLabel: UILabel! @IBOutlet weak var followingCountLabel: UILabel! @IBOutlet weak var followerCountLabel: UILabel! var user: User? override func viewDidLoad() { super.viewDidLoad() if let user = user { nameLabel.text = user.name! usernameLabel.text = "@\(user.screenname!)" profileImageView.af_setImageWithURL(NSURL(string: user.profileImageURL!)!) headerImageView.af_setImageWithURL(NSURL(string: user.headerImageURL!)!) tweetsCountLabel.text = String(user.tweetsCount!) followingCountLabel.text = String(user.followingCount!) followerCountLabel.text = String(user.followerCount!) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
4e83f301e222b0b0852ddead7e3da897
32.339623
106
0.67459
false
false
false
false
machelix/SwiftLocation
refs/heads/master
SwiftLocationExample/SwiftLocationExample/ViewController.swift
mit
1
// // ViewController.swift // SwiftLocationExample // // Created by daniele on 31/07/15. // Copyright (c) 2015 danielemargutti. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() SwiftLocation.shared.currentLocation(Accuracy.Neighborhood, timeout: 20, onSuccess: { (location) -> Void in // location is a CLPlacemark println("Location found \(location?.description)") }) { (error) -> Void in // something went wrong println("Something went wrong -> \(error?.localizedDescription)") } return SwiftLocation.shared.reverseAddress(Service.Apple, address: "1 Infinite Loop, Cupertino (USA)", region: nil, onSuccess: { (place) -> Void in // our CLPlacemark is here }) { (error) -> Void in // something went wrong } let coordinates = CLLocationCoordinate2DMake(41.890198, 12.492204) SwiftLocation.shared.reverseCoordinates(Service.Apple, coordinates: coordinates, onSuccess: { (place) -> Void in // our placemark is here }) { (error) -> Void in // something went wrong } let requestID = SwiftLocation.shared.continuousLocation(Accuracy.Room, onSuccess: { (location) -> Void in // a new location has arrived }) { (error) -> Void in // something went wrong. request will be cancelled automatically } // Sometime in the future... you may want to interrupt it SwiftLocation.shared.cancelRequest(requestID) SwiftLocation.shared.significantLocation({ (location) -> Void in // a new significant location has arrived }, onFail: { (error) -> Void in // something went wrong. request will be cancelled automatically }) let regionCoordinates = CLLocationCoordinate2DMake(41.890198, 12.492204) var region = CLCircularRegion(center: regionCoordinates, radius: CLLocationDistance(50), identifier: "identifier_region") SwiftLocation.shared.monitorRegion(region, onEnter: { (region) -> Void in // events called on enter }) { (region) -> Void in // event called on exit } let bRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "ciao"), identifier: "myIdentifier") SwiftLocation.shared.monitorBeaconsInRegion(bRegion, onRanging: { (regions) -> Void in // events called on ranging }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
5801487277fb42a40d1dcf5dc991444a
30.605263
142
0.713156
false
false
false
false
Obisoft2017/BeautyTeamiOS
refs/heads/master
BeautyTeam/BeautyTeam/RadioStationEventCell.swift
apache-2.0
1
// // RadioStationEventCell.swift // BeautyTeam // // Created by Carl Lee on 4/24/16. // Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved. // import UIKit import FontAwesome_swift class RadioStationEventCell: UITableViewCell, CustomPresentCellProtocol { var titleLabel: UILabel? var projectImageView: UIImageView? var projectLabel: UILabel? var timeImageView: UIImageView? var timeLabel: UILabel? var emergencyLabel: UILabel? var locationImageView: UIImageView? var locationLabel: UILabel? required init(reuseIdentifier: String) { super.init(style: .Default, reuseIdentifier: reuseIdentifier) let fontAwesomeSize = CGSize(width: 12, height: 12) self.titleLabel = UILabel(frame: CGRectMake(10, 10, 300, 20)) self.titleLabel?.font = UIFont.systemFontOfSize(20) // 74 144 226 self.timeImageView = UIImageView(frame: CGRectMake(10, 70, 12, 12)) self.timeImageView?.image = UIImage.fontAwesomeIconWithName(.ClockO, textColor: UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1), size: fontAwesomeSize) self.timeLabel = UILabel(frame: CGRectMake(30, 70, 300, 12)) self.timeLabel?.font = UIFont.systemFontOfSize(12) // 208 2 27 self.emergencyLabel = UILabel(frame: CGRectMake(310, 70, 100, 12)) self.emergencyLabel?.font = UIFont.boldSystemFontOfSize(12) // 0 0 0 self.locationImageView = UIImageView(frame: CGRectMake(10, 110, 12, 12)) self.locationImageView?.image = UIImage.fontAwesomeIconWithName(.LocationArrow, textColor: UIColor.blackColor(), size: fontAwesomeSize) self.locationLabel = UILabel(frame: CGRectMake(30, 110, 300, 12)) self.locationLabel?.font = UIFont.systemFontOfSize(12) } func assignValue(title: String, happenTime: NSDate, endTime: NSDate, location: String) { self.titleLabel?.text = title let happenTimeStr = ObiBeautyTeam.ObiDateFormatter().stringFromDate(happenTime) let endTimeStr = ObiBeautyTeam.ObiDateFormatter().stringFromDate(endTime) // TODO: Solve the problem of presenting the happentime and endtime. // like this one: // Today 21:00 - 22:00 // Today 09:00 - Tomorrow 14:00 // 21:00 - 22:00 April 9 // Modify this line and the one in `TeanEventCell.swift` after having any idea. let combinedTimeStr = "\(happenTimeStr) - \(endTimeStr)" let combinedAttrStr = NSMutableAttributedString(string: combinedTimeStr) combinedAttrStr.setAttributes([NSForegroundColorAttributeName : UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1)], range: NSMakeRange(0, combinedTimeStr.characters.count)) self.timeLabel?.attributedText = combinedAttrStr self.locationLabel?.text = location } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
bbae3082779de43743a27a6b9040a341
39.292683
192
0.673426
false
false
false
false
victorchee/CollectionView
refs/heads/master
BookCollectionView/BookCollectionView/BookViewController.swift
mit
2
// // BookViewController.swift // BookCollectionView // // Created by qihaijun on 11/30/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class BookViewController: UICollectionViewController { var recognizer: UIGestureRecognizer? { didSet { if let recognizer = recognizer { collectionView?.addGestureRecognizer(recognizer) } } } var book: Book? { didSet { collectionView?.reloadData() } } // MARK: - UICollectionViewDataSrouce override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let book = book else { return 0 } return book.numberOfPages() + 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BookPageCell", for: indexPath) as! BookPageCell if indexPath.item == 0 { // cover cell.label.text = nil cell.image = book?.coverImage() } else { // page cell.label.text = "\(indexPath.item)" cell.image = book?.pageImage(indexPath.item - 1) } return cell } }
408c885ca2a0a78829154664de71a8c9
28.137255
130
0.605653
false
false
false
false
imex94/NetworkKit
refs/heads/master
NetworkKit/NKReachability.swift
mit
1
// // NKReachability.swift // HackerNews // // The MIT License (MIT) // // Copyright (c) 2016 Alex Telek // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if os(watchOS) #else import Foundation import SystemConfiguration /// reachability class for checking if the internet connection is available class NKReachability: NSObject { /** Reachability method to check internet connection, using System Configuration - Returns: *true* if thee is internet connection, *false* otherwise */ class func isNetworkAvailable() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } } #endif
70e965c23be86ea72edcccd1576dca42
36.746269
95
0.685647
false
false
false
false
amnuaym/TiAppBuilder
refs/heads/master
Day7/MyWebServiceApp/MyWebServiceApp/MainViewController.swift
gpl-3.0
1
// // MainViewController.swift // MyWebServiceApp // // Created by DrKeng on 9/23/2560 BE. // Copyright © 2560 ANT. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var bottomConstraint: NSLayoutConstraint! var moveAlready = false @IBOutlet weak var txtUserName: UITextField! @IBOutlet weak var txtPassword: UITextField! func parseJSON(myData : Data){ let json = try! JSONSerialization.jsonObject(with: myData, options: .mutableContainers) // do{ // let json = try JSONSerialization.jsonObject(with: myData, options: .mutableContainers) // } catch let error as NSError { // print(error.description) // return() // } // // do { // try <#throwing expression#> // } catch <#pattern#> { // <#statements#> // } let loginResults = json as! [[String : String]] var myResult : String = "" if loginResults.count > 0 { myResult = loginResults.first!["myResult"]! if myResult == "OK" { let vc = self.storyboard?.instantiateViewController(withIdentifier: "MediaListTBV") as! MediaListTableViewController let navigationController = UINavigationController(rootViewController: vc) self.present(navigationController, animated: true, completion: nil) }else{ let alertController = UIAlertController(title: "An error occurred", message: "Username or Password not correct", preferredStyle: .alert) let okButton = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okButton) self.present(alertController, animated: true, completion: nil) } } } @IBAction func loginMethod() { self.saveUserName() //HTTP Request initialization let myURL : URL = URL(string: "http://www.worasit.com/iosbuilder/login.php")! var myRequest : URLRequest = URLRequest(url: myURL) let mySession = URLSession.shared myRequest.httpMethod = "POST" //Initialize parameter let params = ["username":"\(txtUserName.text!)", "password":"\(txtPassword.text!)"] as Dictionary<String, String> myRequest.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) myRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") myRequest.addValue("application/json", forHTTPHeaderField: "Accept") let myTask = mySession.dataTask(with: myRequest){(responseData, responseStatus, error) in //Force Operation into Main Queue -> So that it waits for return OperationQueue.main.addOperation { print("responseStatus = \(responseStatus!)") print("responseData = \(responseData!)") self.parseJSON(myData: responseData!) } } myTask.resume() } func adjustingHeight(_ show:Bool, notification:NSNotification){ var userInfo = notification.userInfo! //read Keyboard size // let keyboardFrame:CGSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size let keyboardBounds:CGSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size //Change Sign In Button location if (show && !moveAlready){ // bottomConstraint.constant += keyboardFrame.height bottomConstraint.constant += keyboardBounds.height moveAlready = true } if (!show && moveAlready){ // bottomConstraint.constant -= keyboardFrame.height bottomConstraint.constant -= keyboardBounds.height moveAlready = false } } @objc func keyboardWillShow(notification:NSNotification) { adjustingHeight(true, notification: notification) } @objc func keyboardWillHide(notification:NSNotification) { adjustingHeight(false, notification: notification) } override func viewWillAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: Notification.Name.UIKeyboardWillHide, object: nil) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func saveUserName(){ let defaults : UserDefaults = UserDefaults.standard defaults.set(txtUserName.text!, forKey: "myUserName") } override func viewDidLoad() { super.viewDidLoad() //Read data from Detaults and put it in TextField let defaults = UserDefaults.standard txtUserName.text = defaults.string(forKey: "myUserName") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
a58594b07136419f79cfc3f6827d27bc
37.434483
152
0.63682
false
false
false
false
uias/Tabman
refs/heads/main
Sources/Tabman/AutoInsetter/Utilities/UIViewController+ScrollViewDetection.swift
mit
1
// // UIViewController+ScrollViewDetection.swift // AutoInset // // Created by Merrick Sapsford on 16/01/2018. // Copyright © 2018 UI At Six. All rights reserved. // import UIKit internal extension UIViewController { var embeddedScrollViews: [UIScrollView?] { if let tableViewController = self as? UITableViewController { // UITableViewController return [tableViewController.tableView] } else if let collectionViewController = self as? UICollectionViewController { // UICollectionViewController return [collectionViewController.collectionView] } else { // standard subview filtering return scrollViews(in: self.view) } } func scrollViews(in view: UIView) -> [UIScrollView] { var scrollViews = [UIScrollView]() for subview in view.subviews { // if current view is scroll view add it and ignore the subviews // - as it can be assumed they will be insetted correctly within the parent scroll view. if let scrollView = subview as? UIScrollView { scrollViews.append(scrollView) } else { scrollViews.append(contentsOf: self.scrollViews(in: subview)) } } return scrollViews } func forEachEmbeddedScrollView(_ action: (UIScrollView) -> Void) { for scrollView in self.embeddedScrollViews { guard let scrollView = scrollView, scrollView.window != nil else { continue } action(scrollView) } } func shouldEvaluateEmbeddedScrollViews() -> Bool { if self is UIPageViewController { // Ignore UIPageViewController return false } return true } }
7a61587215109602063b3a5df8d36ae6
33.173077
116
0.628025
false
false
false
false
vector-im/vector-ios
refs/heads/master
RiotSwiftUI/Modules/Room/RoomUpgrade/RoomUpgradeViewModel.swift
apache-2.0
1
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI import Combine @available(iOS 14, *) typealias RoomUpgradeViewModelType = StateStoreViewModel<RoomUpgradeViewState, Never, RoomUpgradeViewAction> @available(iOS 14, *) class RoomUpgradeViewModel: RoomUpgradeViewModelType, RoomUpgradeViewModelProtocol { // MARK: - Properties // MARK: Private private let roomUpgradeService: RoomUpgradeServiceProtocol // MARK: Public var completion: ((RoomUpgradeViewModelResult) -> Void)? // MARK: - Setup static func makeRoomUpgradeViewModel(roomUpgradeService: RoomUpgradeServiceProtocol) -> RoomUpgradeViewModelProtocol { return RoomUpgradeViewModel(roomUpgradeService: roomUpgradeService) } private init(roomUpgradeService: RoomUpgradeServiceProtocol) { self.roomUpgradeService = roomUpgradeService super.init(initialViewState: Self.defaultState(roomUpgradeService: roomUpgradeService)) setupObservers() } private static func defaultState(roomUpgradeService: RoomUpgradeServiceProtocol) -> RoomUpgradeViewState { return RoomUpgradeViewState(waitingMessage: nil, isLoading: false) } private func setupObservers() { roomUpgradeService .upgradingSubject .sink { [weak self] isUpgrading in self?.state.isLoading = isUpgrading self?.state.waitingMessage = isUpgrading ? VectorL10n.roomAccessSettingsScreenUpgradeAlertUpgrading: nil } .store(in: &cancellables) } // MARK: - Public override func process(viewAction: RoomUpgradeViewAction) { switch viewAction { case .cancel: completion?(.cancel(roomUpgradeService.currentRoomId)) case .done(let autoInviteUsers): roomUpgradeService.upgradeRoom(autoInviteUsers: autoInviteUsers) { [weak self] success, roomId in guard let self = self else { return } if success { self.completion?(.done(self.roomUpgradeService.currentRoomId)) } } } } }
d0c15ddc34ddc96bf06fa1d24b1b246d
35
122
0.665242
false
false
false
false
rene-dohan/CS-IOS
refs/heads/master
Renetik/Renetik/Classes/CocoaLumberjack/CSCocoaLumberjack.swift
mit
1
// // Created by Rene Dohan on 2019-01-17. // import CocoaLumberjack public class CocoaLumberjackCSLogger: NSObject, CSLoggerProtocol { var isDisabled: Bool = false var isToast: Bool = false public init(disabled: Bool = false) { isDisabled = disabled } public init(toast: Bool = false) { isToast = toast } public func logDebug(_ value: String) { if !isDisabled { DDLogDebug(value) if isToast { CSNotification().title(value).time(5).show() } } } public func logInfo(_ value: String) { if !isDisabled { DDLogInfo(value) if isToast { CSNotification().title(value).time(5).show() } } } public func logWarn(_ value: String) { if !isDisabled { DDLogWarn(value) if isToast { CSNotification().title(value).time(5).show() } } } public func logError(_ value: String) { if !isDisabled { DDLogError(value) if isToast { CSNotification().title(value).time(5).show() } } } } public class CSCocoaLumberjackFormatter: NSObject, DDLogFormatter { var loggerCount = 0 let threadUnsafeDateFormatter = DateFormatter().also { $0.formatterBehavior = .behavior10_4 $0.dateFormat = "HH:mm:ss:SSS" } public func format(message: DDLogMessage) -> String? { var logLevel: String switch message.flag { case DDLogFlag.debug: logLevel = "Debug" case DDLogFlag.error: logLevel = "Error" case DDLogFlag.warning: logLevel = "Warning" case DDLogFlag.info: logLevel = "Info" default: logLevel = "Verbose" } var dateAndTime = threadUnsafeDateFormatter.string(from: message.timestamp) return "\(dateAndTime) \(logLevel) \(message.fileName ?? "") \(message.function) \(message.line) = \(message.message)" } public func didAdd(to logger: DDLogger) { loggerCount += 1 assert(loggerCount <= 1, "This logger isn't thread-safe") } public func willRemove(from logger: DDLogger) { loggerCount -= 1 } }
cf498645f3b8c5cb0b4bbe87009ccc6c
27.573333
126
0.601493
false
false
false
false
esttorhe/RxSwift
refs/heads/feature/swift2.0
RxCocoa/RxCocoa/Common/RxCocoa.swift
mit
1
// // RxCocoa.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift #if os(iOS) import UIKit #endif public enum RxCocoaError : Int { case Unknown = 0 case NetworkError = 1 case InvalidOperation = 2 case KeyPathInvalid = 3 } let defaultHeight: CGFloat = -1 public let RxCocoaErrorDomain = "RxCocoaError" public let RxCocoaErrorHTTPResponseKey = "RxCocoaErrorHTTPResponseKey" func rxError(errorCode: RxCocoaError, _ message: String) -> NSError { return NSError(domain: RxCocoaErrorDomain, code: errorCode.rawValue, userInfo: [NSLocalizedDescriptionKey: message]) } #if !RELEASE public func _rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError { return rxError(errorCode, message: message, userInfo: userInfo) } #endif func rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError { var resultInfo: [NSObject: AnyObject] = [:] resultInfo[NSLocalizedDescriptionKey] = message for k in userInfo.allKeys { resultInfo[k as! NSObject] = userInfo[k as! NSCopying] } return NSError(domain: RxCocoaErrorDomain, code: Int(errorCode.rawValue), userInfo: resultInfo) } func removingObserverFailed() { rxFatalError("Removing observer for key failed") } func handleVoidObserverResult(result: RxResult<Void>) { handleObserverResult(result) } func rxFatalError(lastMessage: String) { // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. fatalError(lastMessage) } func bindingErrorToInterface(error: ErrorType) { #if DEBUG rxFatalError("Binding error to UI: \(error)") #endif } // There are certain kinds of errors that shouldn't be silenced, but it could be weird to crash the app because of them. // DEBUG -> crash the app // RELEASE -> log to console func rxPossiblyFatalError(error: String) { #if DEBUG rxFatalError(error) #else print("[RxSwift]: \(error)") #endif } func rxFatalErrorAndDontReturn<T>(lastMessage: String) -> T { rxFatalError(lastMessage) return (nil as T!)! } func rxAbstractMethodWithMessage<T>(message: String) -> T { return rxFatalErrorAndDontReturn(message) } func rxAbstractMethod<T>() -> T { return rxFatalErrorAndDontReturn("Abstract method") } func handleObserverResult<T>(result: RxResult<T>) { switch result { case .Failure(let error): print("Error happened \(error)") rxFatalError("Error '\(error)' happened while "); default: break } } // workaround for Swift compiler bug, cheers compiler team :) func castOptionalOrFatalError<T>(value: AnyObject?) -> T? { if value == nil { return nil } let v: T = castOrFatalError(value) return v } func castOrFatalError<T>(value: AnyObject!, message: String) -> T { let result: RxResult<T> = castOrFail(value) if result.isFailure { rxFatalError(message) } return result.get() } func castOrFatalError<T>(value: AnyObject!) -> T { let result: RxResult<T> = castOrFail(value) if result.isFailure { rxFatalError("Failure converting from \(value) to \(T.self)") } return result.get() } // Error messages { let dataSourceNotSet = "DataSource not set" let delegateNotSet = "Delegate not set" // } extension NSObject { func rx_synchronized<T>(@noescape action: () -> T) -> T { objc_sync_enter(self) let result = action() objc_sync_exit(self) return result } }
7bd49d2f8a2d92f917974a3339c6f07b
24.314685
120
0.692541
false
false
false
false
OscarSwanros/swift
refs/heads/master
stdlib/public/Darwin/Foundation/NSSortDescriptor.swift
apache-2.0
20
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2017 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension NSSortDescriptor { public convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool) { self.init(key: _bridgeKeyPathToString(keyPath), ascending: ascending) } public convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool, comparator cmptr: @escaping Foundation.Comparator) { self.init(key: _bridgeKeyPathToString(keyPath), ascending: ascending, comparator: cmptr) } public var keyPath: AnyKeyPath? { guard let key = self.key else { return nil } return _bridgeStringToKeyPath(key) } }
0df0ae0f3444ab00e7c84c918cbcb3c2
40.678571
141
0.614396
false
false
false
false
dnpp73/SimpleCamera
refs/heads/master
Sources/SimpleCamera.swift
mit
1
#if canImport(UIKit) import Foundation import UIKit import AVFoundation // struct にしたいけど deinit が使えないのと、 // AVCaptureVideoDataOutputSampleBufferDelegate が class 指定というか NSObject 指定なのでしょうがない。 public final class SimpleCamera: NSObject, SimpleCameraInterface { public static let shared = SimpleCamera() // Singleton override private init() {} fileprivate let sessionQueue = DispatchQueue(label: "org.dnpp.SimpleCamera.sessionQueue") // attributes: .concurrent しなければ serial queue private let videoDataOutputQueue = DispatchQueue(label: "org.dnpp.SimpleCamera.VideoDataOutput.delegateQueue") fileprivate let captureSession = AVCaptureSession() private let photoOutput = AVCapturePhotoOutput() fileprivate let videoDataOutput = AVCaptureVideoDataOutput() // extension の AVCaptureVideoDataOutputSampleBufferDelegate 内で使っているため fileprivate fileprivate let audioDataOutput = AVCaptureAudioDataOutput() // extension の AVCaptureVideoDataOutputSampleBufferDelegate 内で使っているため fileprivate fileprivate let movieFileOutput = AVCaptureMovieFileOutput() private var frontCameraVideoInput: AVCaptureDeviceInput? private var backCameraVideoInput: AVCaptureDeviceInput? private var audioDeviceInput: AVCaptureDeviceInput? fileprivate var isPhotoCapturingImage: Bool = false fileprivate var isSilentCapturingImage: Bool = false fileprivate var photoCaptureImageCompletion: ((_ image: UIImage?, _ metadata: [String: Any]?) -> Void)? // extension で使っているため fileprivate fileprivate var silentCaptureImageCompletion: ((_ image: UIImage?, _ metadata: [String: Any]?) -> Void)? // extension の AVCaptureVideoDataOutputSampleBufferDelegate 内で使っているため fileprivate private let observers: NSHashTable<SimpleCameraObservable> = NSHashTable.weakObjects() fileprivate let videoDataOutputObservers: NSHashTable<SimpleCameraVideoDataOutputObservable> = NSHashTable.weakObjects() fileprivate let audioDataOutputObservers: NSHashTable<SimpleCameraAudioDataOutputObservable> = NSHashTable.weakObjects() private weak var captureVideoPreviewView: AVCaptureVideoPreviewView? // MARK: - Initializer deinit { // deinit は class だけだよ tearDown() } // MARK: - Public Functions public func setSession(to captureVideoPreviewView: AVCaptureVideoPreviewView) { if let c = self.captureVideoPreviewView, c.session != nil { c.session = nil } // sessionQueue.async { } で囲ってしまうとメインスレッド外から UI を触ってしまうので外す。 captureVideoPreviewView.session = captureSession self.captureVideoPreviewView = captureVideoPreviewView } public var isRunning: Bool { guard isConfigured else { return false } return captureSession.isRunning } public func startRunning() { DispatchQueue.global().async { self.configure() // この実行でカメラの許可ダイアログが出る guard self.isConfigured else { return } if !self.isRunning { DispatchQueue.main.async { OrientationDetector.shared.startSensor() } self.sessionQueue.async { self.captureSession.startRunning() self.resetZoomFactor(sync: false) // true にしたり zoomFactor の setter に入れるとデッドロックするので注意 self.resetFocusAndExposure() } } } } public func stopRunning() { guard isConfigured else { return } if isRunning { sessionQueue.async { self.captureSession.stopRunning() } OrientationDetector.shared.stopSensor() } } // MARK: Preset public private(set) var mode: CameraMode = .unknown public func setPhotoMode() { sessionQueue.sync { guard isRecordingMovie == false else { return } guard mode != .photo else { return } captureSession.beginConfiguration() // defer より前の段階で commit したい captureSession.removeOutput(movieFileOutput) if let audioDeviceInput = audioDeviceInput { captureSession.removeInput(audioDeviceInput) } if captureSession.canSetSessionPreset(.photo) { captureSession.canSetSessionPreset(.photo) } if let frontCameraDevice = frontCameraVideoInput?.device { if let f = frontCameraDevice.formats.fliter420v.filterAspect4_3.sortedByQuality.first { frontCameraDevice.lockAndConfiguration { frontCameraDevice.activeFormat = f } } } if let backCameraDevice = backCameraVideoInput?.device { if let f = backCameraDevice.formats.fliter420v.filterAspect4_3.sortedByQuality.first { backCameraDevice.lockAndConfiguration { backCameraDevice.activeFormat = f } } } captureSession.commitConfiguration() mode = .photo resetZoomFactor(sync: false) // true にしたり zoomFactor の setter に入れるとデッドロックするので注意 resetFocusAndExposure() } } public func setMovieMode() { sessionQueue.sync { guard isRecordingMovie == false else { return } guard mode != .movie else { return } captureSession.beginConfiguration() // defer より前の段階で commit したい // 最初は configure() 内で作っていたんだけど、そうするとマイクの許可画面とかが出てきて // マイク使わない、動画無しの場合のアプリみたいなの作るときに不便そうだったのでこっちにした。 if isEnabledAudioRecording { if audioDeviceInput == nil { do { if let audioDevice = AVCaptureDevice.default(for: .audio) { // ここで AVCaptureDeviceInput を作ると、その時は落ちないんだけど、その先の適当なタイミングで落ちる。 // マイクの許可が必要。 iOS 10 以降では plist に書かないとダメだよ。 audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice) } else { audioDeviceInput = nil } } catch let error /* as NSError */ { print(error) audioDeviceInput = nil } } if let audioDeviceInput = audioDeviceInput, captureSession.canAddInput(audioDeviceInput) { captureSession.addInput(audioDeviceInput) } } /* // ここで movieFileOutput を addOutput してしまうと videoDataOutput に何も流れてこなくなるのでダメ。 // 一瞬暗くなるけど録画直前に addOutput するしかなさそう。 if captureSession.canAddOutput(movieFileOutput) { captureSession.addOutput(movieFileOutput) } */ if captureSession.canSetSessionPreset(.high) { captureSession.canSetSessionPreset(.high) } if let frontCameraDevice = frontCameraVideoInput?.device { if let f = frontCameraDevice.formats.fliter420v.filterAspect16_9.sortedByQuality.first { frontCameraDevice.lockAndConfiguration { frontCameraDevice.activeFormat = f } } } if let backCameraDevice = backCameraVideoInput?.device { if let f = backCameraDevice.formats.fliter420v.filterAspect16_9.sortedByQuality.first { backCameraDevice.lockAndConfiguration { backCameraDevice.activeFormat = f } } } captureSession.commitConfiguration() mode = .movie resetZoomFactor(sync: false) // true にしたり zoomFactor の setter に入れるとデッドロックするので注意 resetFocusAndExposure() } } // MARK: Capture Image public var isCapturingImage: Bool { isSilentCapturingImage || isPhotoCapturingImage } public var captureLimitSize: CGSize = .zero public func capturePhotoImageAsynchronously(completion: @escaping (_ image: UIImage?, _ metadata: [String: Any]?) -> Void) { guard isConfigured else { completion(nil, nil) return } guard isRecordingMovie == false else { completion(nil, nil) return } guard captureSession.isRunning else { completion(nil, nil) return } if isPhotoCapturingImage { completion(nil, nil) return } if isSilentCapturingImage { // 連打などで前のやつが処理中な場合 completion(nil, nil) return } let settings = AVCapturePhotoSettings() // settings.flashMode = .auto // settings.isHighResolutionPhotoEnabled = false isPhotoCapturingImage = true photoCaptureImageCompletion = completion /* // AVCaptureStillImageOutput の captureStillImageAsynchronously であれば撮影直前に connection の videoOrientation を弄っても問題なかったが // AVCapturePhotoOutput ではどうやら弄っても効かない模様。 let videoOrientation: AVCaptureVideoOrientation if self.isFollowDeviceOrientationWhenCapture { videoOrientation = OrientationDetector.shared.captureVideoOrientation } else { videoOrientation = .portrait } sessionQueue.async { if let photoOutputConnection = self.photoOutput.connection(with: AVMediaType.video) { if photoOutputConnection.isVideoOrientationSupported { self.captureSession.beginConfiguration() photoOutputConnection.videoOrientation = videoOrientation self.captureSession.commitConfiguration() // defer より前のタイミングで commit したい } } self.photoOutput.capturePhoto(with: settings, delegate: self) } */ photoOutput.capturePhoto(with: settings, delegate: self) } @available(*, deprecated, renamed: "capturePhotoImageAsynchronously") public func captureStillImageAsynchronously(completion: @escaping (_ image: UIImage?, _ metadata: [String: Any]?) -> Void) { capturePhotoImageAsynchronously(completion: completion) } /* public func captureStillImageAsynchronously(completion: @escaping (_ image: UIImage?, _ metadata: [String: Any]?) -> Void) { guard isConfigured else { completion(nil, nil) return } guard isRecordingMovie == false else { completion(nil, nil) return } guard captureSession.isRunning else { completion(nil, nil) return } guard stillImageOutput.isCapturingStillImage == false else { completion(nil, nil) return } let videoOrientation: AVCaptureVideoOrientation if self.isFollowDeviceOrientationWhenCapture { videoOrientation = OrientationDetector.shared.captureVideoOrientation } else { videoOrientation = .portrait } sessionQueue.async { let stillImageOutputCaptureConnection: AVCaptureConnection = self.stillImageOutput.connection(with: .video)! // swiftlint:disable:this force_unwrapping // captureStillImageAsynchronously であれば撮影直前に connection の videoOrientation を弄っても問題なさそう self.captureSession.beginConfiguration() stillImageOutputCaptureConnection.videoOrientation = videoOrientation self.captureSession.commitConfiguration() // defer より前のタイミングで commit したい self.stillImageOutput.captureStillImageAsynchronously(from: stillImageOutputCaptureConnection) { (imageDataBuffer, error) -> Void in guard let imageDataBuffer = imageDataBuffer, let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataBuffer) else { onMainThreadAsync { completion(nil, nil) } return } guard let rawImage = UIImage(data: data) else { onMainThreadAsync { completion(nil, nil) } return } let scaledImage: UIImage if self.captureLimitSize == .zero { scaledImage = rawImage } else { guard let c = CIImage(image: rawImage), let i = createUIImage(from: c, limitSize: self.captureLimitSize, imageOrientation: rawImage.imageOrientation) else { onMainThreadAsync { completion(nil, nil) } return } scaledImage = i } let metadata = CMCopyDictionaryOfAttachments(allocator: nil, target: imageDataBuffer, attachmentMode: kCMAttachmentMode_ShouldPropagate) as? [String: Any] let mirrored = self.isMirroredImageIfFrontCamera && stillImageOutputCaptureConnection.isFrontCameraDevice let image = mirrored ? scaledImage.mirrored : scaledImage onMainThreadAsync { completion(image, metadata) } } } } */ public func captureSilentImageAsynchronously(completion: @escaping (_ image: UIImage?, _ metadata: [String: Any]?) -> Void) { guard isConfigured else { completion(nil, nil) return } guard isRecordingMovie == false else { completion(nil, nil) return } guard captureSession.isRunning else { completion(nil, nil) return } if isSilentCapturingImage { // 連打などで前のやつが処理中な場合 completion(nil, nil) return } // Block を保持しておいて、次に AVCaptureVideoDataOutputSampleBufferDelegate で呼ばれた時に UIImage 作って返す。 isSilentCapturingImage = true videoDataOutputQueue.sync { silentCaptureImageCompletion = completion } } // MARK: - Record Movie public var isEnabledAudioRecording: Bool = false public fileprivate(set) var isRecordingMovie: Bool = false @discardableResult public func startRecordMovie(to url: URL) -> Bool { guard isRecordingMovie == false else { return false } guard mode == .movie else { return false } guard url.isFileURL else { return false } guard captureSession.canAddOutput(movieFileOutput) else { return false } sessionQueue.sync { captureSession.beginConfiguration() defer { captureSession.commitConfiguration() } // movieFileOutput を使うと自動で videoDataOutput と audioDataOutput へのデータの流れが止まるのでこうなってる。 captureSession.removeOutput(videoDataOutput) captureSession.removeOutput(audioDataOutput) captureSession.addOutput(movieFileOutput) let videoOrientation: AVCaptureVideoOrientation if self.isFollowDeviceOrientationWhenCapture { videoOrientation = OrientationDetector.shared.captureVideoOrientation } else { videoOrientation = .portrait } movieFileOutput.connection(with: .video)?.videoOrientation = videoOrientation } isRecordingMovie = true // videoDataOutput, audioDataOutput, movieFileOutput を captureSession に足したり消したりしてる関係で、デバイスの初期化が走ってしまい少し暗くなるので気持ちの待ちを入れる。 sessionQueue.asyncAfter(deadline: .now() + 0.3) { self.movieFileOutput.startRecording(to: url, recordingDelegate: self) } return true } public func stopRecordMovie() { sessionQueue.async { self.movieFileOutput.stopRecording() } } // MARK: Camera Setting #warning("ズームだけ実装した。ホワイトバランスや ISO やシャッタースピードの調整は後で lockCurrentCameraDeviceAndConfigure を使って作る。") private var currentInput: AVCaptureDeviceInput? { guard isConfigured else { return nil } // input は 1 つだけという前提(現状の iOS では全部そうなので) return captureSession.inputs.first as? AVCaptureDeviceInput } internal var currentDevice: AVCaptureDevice? { guard isConfigured else { return nil } return currentInput?.device } private func lockCurrentCameraDeviceAndConfigure(sync: Bool = true, configurationBlock: @escaping () -> Void) { guard isConfigured else { return } currentDevice?.lockAndConfiguration(queue: sessionQueue, sync: sync, configurationBlock: configurationBlock) } // MARK: Zoom public var zoomFactor: CGFloat { get { guard let device = currentDevice else { return 1.0 } if isCurrentInputBack && hasUltraWideCameraInBackCamera { return device.videoZoomFactor / 2.0 } else { return device.videoZoomFactor } } set { lockCurrentCameraDeviceAndConfigure { guard let lockedDevice = self.currentDevice else { return } let minZoomFactor = self.minZoomFactor let maxZoomFactor = self.maxZoomFactor let validatedZoomFactor = min(max(newValue, minZoomFactor), maxZoomFactor) if self.isCurrentInputBack && self.hasUltraWideCameraInBackCamera { lockedDevice.videoZoomFactor = validatedZoomFactor * 2.0 } else { lockedDevice.videoZoomFactor = validatedZoomFactor } } } } private func resetZoomFactor(sync: Bool) { lockCurrentCameraDeviceAndConfigure(sync: sync) { guard let lockedDevice = self.currentDevice else { return } if self.isCurrentInputBack && self.hasUltraWideCameraInBackCamera { lockedDevice.videoZoomFactor = 2.0 } else { lockedDevice.videoZoomFactor = 1.0 } } } public var zoomFactorLimit: CGFloat = 6.0 { didSet { if zoomFactor > zoomFactorLimit { zoomFactor = zoomFactorLimit } } } public var maxZoomFactor: CGFloat { guard let videoMaxZoomFactor = currentDevice?.activeFormat.videoMaxZoomFactor else { return 1.0 } return min(zoomFactorLimit, videoMaxZoomFactor) } public var minZoomFactor: CGFloat { if isCurrentInputBack && hasUltraWideCameraInBackCamera { return 0.5 } else { return 1.0 } } // MARK: Focus, Exposure public var focusPointOfInterest: CGPoint { guard let device = currentDevice else { return CGPoint.zero } return device.focusPointOfInterest } public func focus(at devicePoint: CGPoint, focusMode: AVCaptureDevice.FocusMode, monitorSubjectAreaChange: Bool) { lockCurrentCameraDeviceAndConfigure(sync: false) { guard let device = self.currentDevice else { return } if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) { device.focusPointOfInterest = devicePoint device.focusMode = focusMode } device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange } } public var exposurePointOfInterest: CGPoint { guard let device = currentDevice else { return CGPoint.zero } return device.exposurePointOfInterest } public func exposure(at devicePoint: CGPoint, exposureMode: AVCaptureDevice.ExposureMode, monitorSubjectAreaChange: Bool) { lockCurrentCameraDeviceAndConfigure(sync: false) { guard let device = self.currentDevice else { return } if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) { device.exposurePointOfInterest = devicePoint device.exposureMode = exposureMode } device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange } } public func focusAndExposure(at devicePoint: CGPoint, focusMode: AVCaptureDevice.FocusMode, exposureMode: AVCaptureDevice.ExposureMode, monitorSubjectAreaChange: Bool) { lockCurrentCameraDeviceAndConfigure(sync: false) { guard let device = self.currentDevice else { return } if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) { device.focusPointOfInterest = devicePoint device.focusMode = focusMode } if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) { device.exposurePointOfInterest = devicePoint device.exposureMode = exposureMode } device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange } } public func resetFocusAndExposure() { guard let device = self.currentDevice else { return } lockCurrentCameraDeviceAndConfigure(sync: false) { let center = CGPoint(x: 0.5, y: 0.5) if device.isFocusPointOfInterestSupported { let focusMode: AVCaptureDevice.FocusMode if device.isFocusModeSupported(.continuousAutoFocus) { focusMode = .continuousAutoFocus } else { focusMode = .autoFocus } device.focusPointOfInterest = center device.focusMode = focusMode } if device.isExposurePointOfInterestSupported { let exposureMode: AVCaptureDevice.ExposureMode if device.isExposureModeSupported(.continuousAutoExposure) { exposureMode = .continuousAutoExposure } else { exposureMode = .autoExpose } device.exposurePointOfInterest = center device.exposureMode = exposureMode } device.isSubjectAreaChangeMonitoringEnabled = true onMainThreadAsync { for observer in self.observers.allObjects { observer.simpleCameraDidResetFocusAndExposure(simpleCamera: self) } } } } // MARK: Switch Camera Input Front/Back private func switchCaptureDeviceInput(_ captureDeviceInput: AVCaptureDeviceInput) { guard isConfigured else { return } guard let currentInput = currentInput else { return } guard !isRecordingMovie else { // 動画記録中も切り替えられることは切り替えられるけど、iOS 側は記録の方が中断される感じの優先度になってる。 return } var switchSucceed: Bool = false sessionQueue.sync { captureSession.beginConfiguration() defer { captureSession.commitConfiguration() } captureSession.removeInput(currentInput) if captureSession.canAddInput(captureDeviceInput) { captureSession.addInput(captureDeviceInput) switchSucceed = true } else if captureSession.canAddInput(currentInput) { captureSession.addInput(currentInput) } // let videoOrientation = AVCaptureVideoOrientation(interfaceOrientation: UIApplication.shared.statusBarOrientation) ?? .portrait // とりあえず portrait に戻す let videoOrientation = AVCaptureVideoOrientation.portrait videoDataOutput.connection(with: .video)?.videoOrientation = videoOrientation } if switchSucceed { // 内部で sessionQueue.async してるので外に出しておきたい onMainThreadAsync { for observer in self.observers.allObjects { observer.simpleCameraDidSwitchCameraInput(simpleCamera: self) } } resetZoomFactor(sync: true) resetFocusAndExposure() } } public var isCurrentInputFront: Bool { guard let device = currentDevice else { return false } return device.position == .front } public func switchCameraInputToFront() { guard let device = currentDevice, let frontCameraVideoInput = frontCameraVideoInput else { return } if device.position != .front { switchCaptureDeviceInput(frontCameraVideoInput) } } public var isCurrentInputBack: Bool { guard let device = currentDevice else { return false } return device.position == .back } public func switchCameraInputToBack() { guard let device = currentDevice, let backCameraVideoInput = backCameraVideoInput else { return } if device.position != .back { switchCaptureDeviceInput(backCameraVideoInput) } } public func switchCameraInput() { if isCurrentInputFront { switchCameraInputToBack() } else if isCurrentInputBack { switchCameraInputToFront() } } // MARK: Orientation, Mirrored Setting public var isMirroredImageIfFrontCamera = false public var isFollowDeviceOrientationWhenCapture = true // MARK: Manage SimpleCamera Observers public func add(simpleCameraObserver: SimpleCameraObservable) { if !observers.contains(simpleCameraObserver) { observers.add(simpleCameraObserver) } } public func remove(simpleCameraObserver: SimpleCameraObservable) { if observers.contains(simpleCameraObserver) { observers.remove(simpleCameraObserver) } } // MARK: Manage VideoDataOutput Observer public func add(videoDataOutputObserver: SimpleCameraVideoDataOutputObservable) { if !videoDataOutputObservers.contains(videoDataOutputObserver) { videoDataOutputObservers.add(videoDataOutputObserver) } } public func remove(videoDataOutputObserver: SimpleCameraVideoDataOutputObservable) { if videoDataOutputObservers.contains(videoDataOutputObserver) { videoDataOutputObservers.remove(videoDataOutputObserver) } } // MARK: Manage AudioDataOutput Observers public func add(audioDataOutputObserver: SimpleCameraAudioDataOutputObservable) { if !audioDataOutputObservers.contains(audioDataOutputObserver) { audioDataOutputObservers.add(audioDataOutputObserver) } } public func remove(audioDataOutputObserver: SimpleCameraAudioDataOutputObservable) { if audioDataOutputObservers.contains(audioDataOutputObserver) { audioDataOutputObservers.remove(audioDataOutputObserver) } } // MARK: - Private Functions private var hasUltraWideCameraInBackCamera = false // configure() 内で backCameraVideoInput を探すときに決める。 private var isConfigured: Bool = false private func configure() { // この configure 実行でカメラの許可ダイアログが出る if isConfigured || (TARGET_OS_SIMULATOR != 0) { return } defer { isConfigured = true } sessionQueue.sync { // CaptureDeviceInput の準備 // iOS 8 以降に限定しているのでバックカメラとフロントカメラは大体全ての機種にあるけど、 // 唯一 iPod Touch 5th Generation にのみバックカメラが無いモデルがある。 do { // iOS 8,9 のカメラアクセス許可ダイアログはここで出る。 // iOS 10 では info.plist の NSCameraUsageDescription に許可の文言を書かないとアプリごと abort() してしまう。 if let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) { frontCameraVideoInput = try AVCaptureDeviceInput(device: device) } else { print("[SimpleCamera.configure()] frontCameraVideoInput is nil") frontCameraVideoInput = nil } } catch let error { print(error) print("[SimpleCamera.configure()] frontCameraVideoInput is nil") frontCameraVideoInput = nil } do { let device: AVCaptureDevice? // 汎用カメラライブラリを目指して作っているので、デバイスの優先順位の決め方は // - 用途を絞った 1 枚のカメラ (広角・望遠・超広角) は使わない // - 複数カメラを一気に扱えるカメラを指定する // - カメラの数が多い方を優先する // という感じでやっていく。 if #available(iOS 13.0, *) { if let tripleCameraDevice = AVCaptureDevice.default(.builtInTripleCamera, for: .video, position: .back) { hasUltraWideCameraInBackCamera = true device = tripleCameraDevice } else if let dualCameraDevice = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) { device = dualCameraDevice } else if let dualWideCameraDevice = AVCaptureDevice.default(.builtInDualWideCamera, for: .video, position: .back) { hasUltraWideCameraInBackCamera = true device = dualWideCameraDevice } else if let wideAngleCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) { device = wideAngleCameraDevice } else { device = nil } } else { if let dualCameraDevice = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) { device = dualCameraDevice } else if let wideAngleCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) { device = wideAngleCameraDevice } else { device = nil } } if let device = device { backCameraVideoInput = try AVCaptureDeviceInput(device: device) } else { print("[SimpleCamera.configure()] backCameraVideoInput is nil") backCameraVideoInput = nil } } catch let error { print(error) print("[SimpleCamera.configure()] backCameraVideoInput is nil") backCameraVideoInput = nil } captureSession.beginConfiguration() defer { captureSession.commitConfiguration() } if captureSession.canAddOutput(photoOutput) { captureSession.addOutput(photoOutput) photoOutput.isLivePhotoCaptureEnabled = false } // videoDataOutput を調整して captureSession に放り込む // kCVPixelBufferPixelFormatTypeKey の部分だけど、 // Available pixel format types on this platform are ( // 420v, // たぶん kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange // 420f, // BGRA // kCVPixelFormatType_32BGRA // ). // とのこと。 // iPhone 4s でのみ再現するんだけど、マジで何も言わずデバッガにも引っ掛からずにアプリが落ちるので // cameraVideoInputDevice と videoDataOutput のフォーマットを 420v の統一してみたところ落ちなくなった。 videoDataOutput.videoSettings = [String(kCVPixelBufferPixelFormatTypeKey): NSNumber(value: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange as UInt32)] videoDataOutput.setSampleBufferDelegate(self, queue: videoDataOutputQueue) if captureSession.canAddOutput(videoDataOutput) { captureSession.addOutput(videoDataOutput) } audioDataOutput.setSampleBufferDelegate(self, queue: videoDataOutputQueue) if captureSession.canAddOutput(audioDataOutput) { captureSession.addOutput(audioDataOutput) } // backCamera を captureSession に放り込む if let backCameraVideoInput = backCameraVideoInput { if captureSession.canAddInput(backCameraVideoInput) { captureSession.addInput(backCameraVideoInput) } } // バックカメラだけじゃなくてフロントカメラもセッションに突っ込んでみようとすると // Multiple audio/video AVCaptureInputs are not currently supported. // と怒られる。 // バックカメラを caputureSession に放り込めなかった場合にここを通過するので // デフォルトではバックカメラ、iPod Touch 5th の一部モデルのみフロントカメラで初期化される。 if let frontCameraVideoInput = frontCameraVideoInput { if captureSession.canAddInput(frontCameraVideoInput) { captureSession.addInput(frontCameraVideoInput) } } // stillImageOutput と videoDataOutput の videoOrientation を InterfaceOrientation に揃えるか縦にしておく。 // captureSession に addInput した後じゃないと connection は nil なので videoOrientation を取ろうとすると nil アクセスで死にます。 // デフォルトでは stillImageOutput が 1 (portrait) で videoDataOutput が 3 (landscapeRight) // let videoOrientation = AVCaptureVideoOrientation(interfaceOrientation: UIApplication.shared.statusBarOrientation) ?? .portrait // とりあえず portrait に戻す let videoOrientation = AVCaptureVideoOrientation.portrait if let photoOutputConnection = photoOutput.connection(with: AVMediaType.video) { if photoOutputConnection.isVideoOrientationSupported { photoOutputConnection.videoOrientation = videoOrientation } photoOutputConnection.videoScaleAndCropFactor = 1.0 } if let videoDataOutputConnection = videoDataOutput.connection(with: AVMediaType.video) { if videoDataOutputConnection.isVideoOrientationSupported { videoDataOutputConnection.videoOrientation = videoOrientation } videoDataOutputConnection.videoScaleAndCropFactor = 1.0 } } // captureSession に preset を放り込んだり AVCaptureDevice に format を放り込んだりする。 // sessionQueue.sync で放り込むと同じ DispatchQueue なのでデッドロックするため外に出す。 setPhotoMode() // NotificationCenter と KVO 周り sessionQueue.sync { addObservers() } } private func tearDown() { if !isConfigured || (TARGET_OS_SIMULATOR != 0) { return } videoDataOutputQueue.sync { silentCaptureImageCompletion = nil isSilentCapturingImage = false isPhotoCapturingImage = false } sessionQueue.sync { removeObservers() if captureSession.isRunning { captureSession.stopRunning() } for output in captureSession.outputs.reversed() { captureSession.removeOutput(output) } for input in captureSession.inputs.reversed() { captureSession.removeInput(input) } frontCameraVideoInput = nil backCameraVideoInput = nil audioDeviceInput = nil isConfigured = false } } // MARK: KVO and Notifications private var keyValueObservations: [NSKeyValueObservation] = [] private var showDebugMessages = false private func addObservers() { #warning("kaku") var observations: [NSKeyValueObservation?] = [] observations.append(captureSession.observe(\.isRunning, options: .new) { (captureSession, changes) in guard let isRunning = changes.newValue else { return } onMainThreadAsync { self.isRunningForObserve = isRunning } }) observations.append(frontCameraVideoInput?.device.observe(\.isAdjustingFocus, options: .new) { (device, changes) in guard let isAdjustingFocus = changes.newValue else { return } if self.showDebugMessages { print("[KVO] frontCameraDevice isAdjustingFocus: \(isAdjustingFocus)") } }) observations.append(backCameraVideoInput?.device.observe(\.isAdjustingFocus, options: .new) { (device, changes) in guard let isAdjustingFocus = changes.newValue else { return } if self.showDebugMessages { print("[KVO] backCameraDevice isAdjustingFocus: \(isAdjustingFocus)") } }) observations.append(frontCameraVideoInput?.device.observe(\.isAdjustingExposure, options: .new) { (device, changes) in guard let isAdjustingExposure = changes.newValue else { return } if self.showDebugMessages { print("[KVO] frontCameraDevice isAdjustingExposure: \(isAdjustingExposure)") } }) observations.append(backCameraVideoInput?.device.observe(\.isAdjustingExposure, options: .new) { (device, changes) in guard let isAdjustingExposure = changes.newValue else { return } if self.showDebugMessages { print("[KVO] backCameraDevice isAdjustingExposure: \(isAdjustingExposure)") } }) observations.append(frontCameraVideoInput?.device.observe(\.isAdjustingWhiteBalance, options: .new) { (device, changes) in guard let isAdjustingWhiteBalance = changes.newValue else { return } if self.showDebugMessages { print("[KVO] frontCameraDevice adjustingWhiteBalance: \(isAdjustingWhiteBalance)") } // 白色点を清く正しく取ってくるの、色々ありそうなのでめんどくさそう。Dash で 'AVCaptureDevice white' くらいまで打てば出てくる英語を読まないといけない。 }) observations.append(backCameraVideoInput?.device.observe(\.isAdjustingWhiteBalance, options: .new) { (device, changes) in guard let isAdjustingWhiteBalance = changes.newValue else { return } if self.showDebugMessages { print("[KVO] backCameraDevice adjustingWhiteBalance: \(isAdjustingWhiteBalance)") } // 白色点を清く正しく取ってくるの、色々ありそうなのでめんどくさそう。Dash で 'AVCaptureDevice white' くらいまで打てば出てくる英語を読まないといけない。 }) observations.append(frontCameraVideoInput?.device.observe(\.focusPointOfInterest, options: .new) { (device, changes) in guard let focusPointOfInterest = changes.newValue else { return } onMainThreadAsync { self.focusPointOfInterestForObserve = focusPointOfInterest } }) observations.append(backCameraVideoInput?.device.observe(\.focusPointOfInterest, options: .new) { (device, changes) in guard let focusPointOfInterest = changes.newValue else { return } onMainThreadAsync { self.focusPointOfInterestForObserve = focusPointOfInterest } }) observations.append(frontCameraVideoInput?.device.observe(\.exposurePointOfInterest, options: .new) { (device, changes) in guard let exposurePointOfInterest = changes.newValue else { return } onMainThreadAsync { self.exposurePointOfInterestForObserve = exposurePointOfInterest } }) observations.append(backCameraVideoInput?.device.observe(\.exposurePointOfInterest, options: .new) { (device, changes) in guard let exposurePointOfInterest = changes.newValue else { return } onMainThreadAsync { self.exposurePointOfInterestForObserve = exposurePointOfInterest } }) observations.append(frontCameraVideoInput?.device.observe(\.videoZoomFactor, options: .new) { (device, changes) in guard let videoZoomFactor = changes.newValue else { return } onMainThreadAsync { self.zoomFactorForObserve = videoZoomFactor } }) observations.append(backCameraVideoInput?.device.observe(\.videoZoomFactor, options: .new) { (device, changes) in guard let videoZoomFactor = changes.newValue else { return } onMainThreadAsync { if self.hasUltraWideCameraInBackCamera { self.zoomFactorForObserve = videoZoomFactor / 2.0 } else { self.zoomFactorForObserve = videoZoomFactor } } }) keyValueObservations = observations.compactMap { $0 } NotificationCenter.default.addObserver(self, selector: #selector(subjectAreaDidChange), name: Notification.Name("AVCaptureDeviceSubjectAreaDidChangeNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sessionRuntimeError), name: Notification.Name("AVCaptureSessionRuntimeErrorNotification"), object: captureSession) NotificationCenter.default.addObserver(self, selector: #selector(sessionWasInterrupted), name: Notification.Name("AVCaptureSessionWasInterruptedNotification"), object: captureSession) NotificationCenter.default.addObserver(self, selector: #selector(sessionInterruptionEnded), name: Notification.Name("AVCaptureSessionInterruptionEndedNotification"), object: captureSession) } private func removeObservers() { NotificationCenter.default.removeObserver(self) keyValueObservations.removeAll() // NSKeyValueObservation の deinit を発行させるだけで良い。 } @objc private func subjectAreaDidChange(notification: Notification) { if showDebugMessages { print("[Notification] Subject Area Did Change") } if let device = notification.object as? AVCaptureDevice, device == currentDevice { // print("notification.object == currentDevice") resetFocusAndExposure() } } @objc private func sessionRuntimeError(notification: Notification) { #warning("TODO") /* guard let errorValue = notification.userInfo?[AVCaptureSessionErrorKey] as? NSError else { return } let error = AVError(_nsError: errorValue) onMainThreadAsync { for observer in self.observers.allObjects { observer.simpleCameraSessionRuntimeError(simpleCamera: self, error: error) } } */ } @objc private func sessionWasInterrupted(notification: Notification) { #warning("TODO") /* guard #available(iOS 9.0, *) else { return } guard let userInfoValue = notification.userInfo?[AVCaptureSessionInterruptionReasonKey] as AnyObject?, let reasonIntegerValue = userInfoValue.integerValue, let reason = AVCaptureSession.InterruptionReason(rawValue: reasonIntegerValue) else { return } onMainThreadAsync { for observer in self.observers.allObjects { observer.simpleCameraSessionWasInterrupted(simpleCamera: self, reason: reason) } } */ } @objc private func sessionInterruptionEnded(notification: Notification) { onMainThreadAsync { for observer in self.observers.allObjects { observer.simpleCameraSessionInterruptionEnded(simpleCamera: self) } } } // MARK: - SimpleCameraObservable private var shouldSendIsRunningDidChange: Bool = false private var isRunningForObserve: Bool = false { willSet { shouldSendIsRunningDidChange = (isRunningForObserve != newValue) } didSet { if shouldSendIsRunningDidChange { for observer in observers.allObjects { if isRunning { observer.simpleCameraDidStartRunning(simpleCamera: self) } else { observer.simpleCameraDidStopRunning(simpleCamera: self) } } } } } private var shouldSendZoomFactorDidChange: Bool = false private var zoomFactorForObserve: CGFloat = 1.0 { willSet { shouldSendZoomFactorDidChange = (zoomFactorForObserve != newValue) } didSet { if shouldSendZoomFactorDidChange { for observer in observers.allObjects { observer.simpleCameraDidChangeZoomFactor(simpleCamera: self) } } } } private var shouldSendFocusPointOfInterestDidChange: Bool = false private var focusPointOfInterestForObserve: CGPoint = CGPoint(x: 0.5, y: 0.5) { willSet { shouldSendFocusPointOfInterestDidChange = (focusPointOfInterestForObserve != newValue && newValue != CGPoint(x: 0.5, y: 0.5)) } didSet { if shouldSendFocusPointOfInterestDidChange { for observer in observers.allObjects { observer.simpleCameraDidChangeFocusPointOfInterest(simpleCamera: self) } } } } private var shouldSendExposurePointOfInterestDidChange: Bool = false private var exposurePointOfInterestForObserve: CGPoint = CGPoint(x: 0.5, y: 0.5) { willSet { shouldSendExposurePointOfInterestDidChange = (exposurePointOfInterestForObserve != newValue && newValue != CGPoint(x: 0.5, y: 0.5)) } didSet { if shouldSendExposurePointOfInterestDidChange { for observer in observers.allObjects { observer.simpleCameraDidChangeExposurePointOfInterest(simpleCamera: self) } } } } } // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate extension SimpleCamera: AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate { public var preferredUIImageOrientationForVideoDataOutput: UIImage.Orientation { guard isRunning else { return .up } // 撮影直前に connection の videoOrientation を弄ると実用的に問題があるので、UIImageOrientation をここで放り込む実装が現実的 // caputureVideoConnection の videoOrientation は .up に固定して初期化しているはずなので、その前提で進める。 let imageOrientation: UIImage.Orientation let captureVideoOrientation = !isFollowDeviceOrientationWhenCapture ? .portrait : OrientationDetector.shared.captureVideoOrientation let i = UIImage.Orientation(captureVideoOrientation: captureVideoOrientation) if let connection = videoDataOutput.connection(with: .video), connection.isFrontCameraDevice { // Front Camera のときはちょっとややこしい imageOrientation = isMirroredImageIfFrontCamera ? i.swapLeftRight.mirrored : i.swapLeftRight } else { // Back Camera のときはそのまま使う imageOrientation = i } return imageOrientation } // AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate で同じ名前のメソッドという…。 public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { if output == videoDataOutput { // 無音カメラの実装 if let silentCaptureImageCompletion = silentCaptureImageCompletion { self.silentCaptureImageCompletion = nil let image = createUIImage(from: sampleBuffer, limitSize: captureLimitSize, imageOrientation: preferredUIImageOrientationForVideoDataOutput) let metadata = CMCopyDictionaryOfAttachments(allocator: nil, target: sampleBuffer, attachmentMode: kCMAttachmentMode_ShouldPropagate) as? [String: Any] isSilentCapturingImage = false onMainThreadAsync { silentCaptureImageCompletion(image, metadata) } } // videoDataOutputObservers for observer in videoDataOutputObservers.allObjects { observer.simpleCameraVideoDataOutputObserve(captureOutput: output, didOutput: sampleBuffer, from: connection) } } else if output == audioDataOutput { // audioDataOutputObservers for observer in audioDataOutputObservers.allObjects { observer.simpleCameraAudioDataOutputObserve(captureOutput: output, didOutput: sampleBuffer, from: connection) } } } public func captureOutput(_ captureOutput: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard captureOutput == videoDataOutput else { return } for observer in videoDataOutputObservers.allObjects { observer.simpleCameraVideoDataOutputObserve(captureOutput: captureOutput, didDrop: sampleBuffer, from: connection) } } } extension SimpleCamera: AVCaptureFileOutputRecordingDelegate { public func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { } public func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { isRecordingMovie = false sessionQueue.async { self.captureSession.beginConfiguration() defer { self.captureSession.commitConfiguration() } // movieFileOutput を使うと自動で videoDataOutput と audioDataOutput へのデータの流れが止まるのでこうなってる。 self.captureSession.removeOutput(self.movieFileOutput) if self.captureSession.canAddOutput(self.videoDataOutput) { self.captureSession.addOutput(self.videoDataOutput) } if self.captureSession.canAddOutput(self.audioDataOutput) { self.captureSession.addOutput(self.audioDataOutput) } // let videoOrientation = AVCaptureVideoOrientation(interfaceOrientation: UIApplication.shared.statusBarOrientation) ?? .portrait // とりあえず portrait に戻す let videoOrientation = AVCaptureVideoOrientation.portrait self.videoDataOutput.connection(with: .video)?.videoOrientation = videoOrientation } } } extension SimpleCamera: AVCapturePhotoCaptureDelegate { // Monitoring Capture Progress public func photoOutput(_ output: AVCapturePhotoOutput, willBeginCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings) { } public func photoOutput(_ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) { } public func photoOutput(_ output: AVCapturePhotoOutput, didCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) { } public func photoOutput(_ output: AVCapturePhotoOutput, didFinishCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings, error: Error?) { isPhotoCapturingImage = false } // Receiving Capture Results private var preferredUIImageOrientationForPhotoOutput: UIImage.Orientation { guard isRunning else { return .up } // AVCaptureStillImageOutput の captureStillImageAsynchronously であれば撮影直前に connection の videoOrientation を弄っても問題なかったが // AVCapturePhotoOutput ではどうやら弄っても効かない模様なのでここでなんとかする。 let imageOrientation: UIImage.Orientation let captureVideoOrientation = !isFollowDeviceOrientationWhenCapture ? .portrait : OrientationDetector.shared.captureVideoOrientation let i = UIImage.Orientation(captureVideoOrientation: captureVideoOrientation) if let connection = photoOutput.connection(with: .video), connection.isFrontCameraDevice { // Front Camera のときはちょっとややこしい imageOrientation = isMirroredImageIfFrontCamera ? i.swapLeftRight.mirrored.rotateLeft : i.swapLeftRight.rotateRight } else { // Back Camera のときはそのまま使う imageOrientation = i.rotateRight } return imageOrientation } public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { guard let photoCaptureImageCompletion = photoCaptureImageCompletion else { return } self.photoCaptureImageCompletion = nil if let _ = error { onMainThreadAsync { photoCaptureImageCompletion(nil, nil) } return } guard let cgImage = photo.cgImageRepresentation() else { onMainThreadAsync { photoCaptureImageCompletion(nil, nil) } return } let rawImage = UIImage(cgImage: cgImage, scale: 1.0, orientation: preferredUIImageOrientationForPhotoOutput) let scaledImage: UIImage if self.captureLimitSize == .zero { scaledImage = rawImage } else { guard let c = CIImage(image: rawImage), let i = createUIImage(from: c, limitSize: self.captureLimitSize, imageOrientation: rawImage.imageOrientation) else { onMainThreadAsync { photoCaptureImageCompletion(nil, nil) } return } scaledImage = i } onMainThreadAsync { photoCaptureImageCompletion(scaledImage, photo.metadata) } } /* // LivePhoto は使わないことにする public func photoOutput(_ output: AVCapturePhotoOutput, didFinishRecordingLivePhotoMovieForEventualFileAt outputFileURL: URL, resolvedSettings: AVCaptureResolvedPhotoSettings) { } public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingLivePhotoToMovieFileAt outputFileURL: URL, duration: CMTime, photoDisplayTime: CMTime, resolvedSettings: AVCaptureResolvedPhotoSettings, error: Error?) { } */ } #endif
2a9280817c8b8e75bbb22358c5d2ae32
39.207353
249
0.62324
false
false
false
false
flutter/put-flutter-to-work
refs/heads/main
newsfeed_ios/newsfeedApp/ContentDataSource.swift
bsd-3-clause
1
// // ContentDataSource.swift // newsfeed_app // import Combine import Foundation import SwiftUI @MainActor class ContentDataSource: ObservableObject { @Published var items: [Int] = Array(0...9) @Published var isLoadingPage = false private var currentPage = 1 private var canLoadMorePages = true func loadMoreContentIfNeeded(currentItem item: Int?) { guard let item = item else { Task { await loadMoreContent() } return } let thresholdIndex = items.index(items.endIndex, offsetBy: -5) if items.first(where: { $0 == item }) == thresholdIndex { Task { await loadMoreContent() } } } private func loadMoreContent() async { guard !isLoadingPage && canLoadMorePages else { return } isLoadingPage = true // Mimic the network delay. do { try await Task.sleep(nanoseconds: 2_000_000_000) } catch {} canLoadMorePages = true items += Array(items.count...items.count+9) isLoadingPage = false } }
58f18c89df7cc8cd4bd2935250a246a5
19.918367
66
0.644878
false
false
false
false
flypaper0/ethereum-wallet
refs/heads/release/1.1
ethereum-wallet/Common/Extensions/New Group/Decimal+Ethereum.swift
gpl-3.0
1
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit // MARK: - Converters extension Decimal { func fromWei() -> Decimal { return self / 1e18 } func toWei() -> Decimal { return self * 1e18 } func localToEther(rate: Double) -> Decimal { return self / Decimal(rate) } func etherToLocal(rate: Double) -> Decimal { return self * Decimal(rate) } func weiToGwei() -> Decimal { return self / 1000000000 } func toHex() -> String { return representationOf(base: 16) } func amount(for iso: String) -> String { let currencyFormatter = NumberFormatter() currencyFormatter.numberStyle = .currency currencyFormatter.locale = .current currencyFormatter.currencyCode = iso return currencyFormatter.string(from: self as NSDecimalNumber)! } init(hexString: String) { self.init(hexString, base: 16) } init(data: Data) { self.init(hexString: data.hex()) } func serialize(bitWidth: Decimal = 256) -> Data { var buffer: [UInt8] = [] var n = self while n > 0 { buffer.append((n.truncatingRemainder(dividingBy: bitWidth) as NSDecimalNumber).uint8Value) n = n.integerDivisionBy(bitWidth) } return Data(bytes: buffer.reversed()) } } // MARK: - Privates extension Decimal { private func rounded(mode: NSDecimalNumber.RoundingMode) -> Decimal { var this = self var result = Decimal() NSDecimalRound(&result, &this, 0, mode) return result } private func integerDivisionBy(_ operand: Decimal) -> Decimal{ let result = (self / operand) return result.rounded(mode: result < 0 ? .up : .down) } private func truncatingRemainder(dividingBy operand: Decimal) -> Decimal { return self - self.integerDivisionBy(operand) * operand } private init(_ string: String, base: Int) { var decimal: Decimal = 0 let digits = string .map { String($0) } .map { Int($0, radix: base)! } for digit in digits { decimal *= Decimal(base) decimal += Decimal(digit) } self.init(string: decimal.description)! } private func representationOf(base: Decimal) -> String { var buffer: [Int] = [] var n = self while n > 0 { buffer.append((n.truncatingRemainder(dividingBy: base) as NSDecimalNumber).intValue) n = n.integerDivisionBy(base) } return buffer .reversed() .map { String($0, radix: (base as NSDecimalNumber).intValue ) } .joined() } }
966ed0ea8e6f0b07b8b3e2853225d7c1
21.102564
96
0.626063
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Utils/Categories/AACustomPresentationAnimationController.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit class AACustomPresentationAnimationController: NSObject, UIViewControllerAnimatedTransitioning { let isPresenting :Bool let duration :NSTimeInterval = 0.5 init(isPresenting: Bool) { self.isPresenting = isPresenting super.init() } // ---- UIViewControllerAnimatedTransitioning methods func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return self.duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if isPresenting { animatePresentationWithTransitionContext(transitionContext) } else { animateDismissalWithTransitionContext(transitionContext) } } // ---- Helper methods func animatePresentationWithTransitionContext(transitionContext: UIViewControllerContextTransitioning) { let presentedController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let presentedControllerView = transitionContext.viewForKey(UITransitionContextToViewKey)! let containerView = transitionContext.containerView() // Position the presented view off the top of the container view presentedControllerView.frame = transitionContext.finalFrameForViewController(presentedController) //presentedControllerView.center.y -= containerView!.bounds.size.height containerView!.addSubview(presentedControllerView) // Animate the presented view to it's final position UIView.animateWithDuration(self.duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .AllowUserInteraction, animations: { //presentedControllerView.center.y += containerView!.bounds.size.height }, completion: {(completed: Bool) -> Void in transitionContext.completeTransition(completed) }) } func animateDismissalWithTransitionContext(transitionContext: UIViewControllerContextTransitioning) { let presentedControllerView = transitionContext.viewForKey(UITransitionContextFromViewKey)! //let containerView = transitionContext.containerView() // Animate the presented view off the bottom of the view UIView.animateWithDuration(self.duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .AllowUserInteraction, animations: { //presentedControllerView.center.y += containerView!.bounds.size.height presentedControllerView.alpha = 0.0 }, completion: {(completed: Bool) -> Void in transitionContext.completeTransition(completed) }) } }
814419b54f0385a753ef2d5821f00b02
39.463768
164
0.72851
false
false
false
false
fancymax/12306ForMac
refs/heads/master
12306ForMac/TicketViewControllers/TrainFilterWindowController.swift
mit
1
// // TrainFilterWindowController.swift // 12306ForMac // // Created by fancymax on 16/8/2. // Copyright © 2016年 fancy. All rights reserved. // import Cocoa enum FilterItemType:Int { case Group = 0, SeatType, StartTime,EndTime, TrainType, Train, FromStation, ToStation } enum FilterKeyType:Int { // single: xxx // multi: O|1 // section: 00:00~06:00 case single = 0, multi, section } class FilterItem: NSObject { init(type:FilterItemType,key:String = "",presentation:String,isChecked:Bool = false) { self.type = type self.presentation = presentation self.key = key self.isChecked = isChecked if key.contains("|") { self.keyType = .multi } else if key.contains("~") { self.keyType = .section } else { self.keyType = .single } } let type:FilterItemType let key:String let presentation:String let keyType: FilterKeyType var isChecked:Bool func IsMatchKey(of filterItem:FilterItem) -> Bool { assert(self.type == .Train) assert(self.keyType == .multi) let trainCode = self.key.components(separatedBy: "|")[0] let startTime = self.key.components(separatedBy: "|")[1] let arriveTime = self.key.components(separatedBy: "|")[4] if filterItem.keyType == .multi { let filterKeys = filterItem.key.components(separatedBy: "|") for filterKey in filterKeys { if trainCode.hasPrefix(filterKey) { return true } } } else if filterItem.keyType == .single { if filterItem.type == .TrainType { if self.key.hasPrefix(filterItem.key) { return true } } else { if self.key.contains(filterItem.key) { return true } } } else if filterItem.keyType == .section { let filterKeys = filterItem.key.components(separatedBy: "~") if filterItem.type == .StartTime { if (startTime >= filterKeys[0]) && (startTime <= filterKeys[1]) { return true } } else if filterItem.type == .EndTime { if arriveTime >= filterKeys[0] && arriveTime <= filterKeys[1] { return true } } } return false } } class TrainFilterWindowController: BaseWindowController { var trains:[QueryLeftNewDTO]! { didSet(oldValue) { if oldValue == nil { return } if oldValue.count != trains.count { filterItems = [FilterItem]() createFilterItemBy(trains!) trainFilterTable.reloadData() } } } var fromStationName = "" var toStationName = "" var trainDate = "" var trainFilterKey = "" var seatFilterKey = "" fileprivate var filterItems = [FilterItem]() @IBOutlet weak var trainFilterTable: NSTableView! override func windowDidLoad() { super.windowDidLoad() createFilterItemBy(trains!) if trainFilterKey == "" { initItemByPreferenceTimeFilterItem() } else { initItemByTrainFilterKey(trainFilterKey) initFilterItemByTrainItem() } if seatFilterKey != "" { initItemBySeatFilterKey(seatFilterKey) } } override var windowNibName: String{ return "TrainFilterWindowController" } func initFilterItemByTrainItem() { let items = filterItems.filter { (item) -> Bool in if [.FromStation, .ToStation, .StartTime, .EndTime, .TrainType].contains(item.type) { return true } else { return false } } for item in items { var shouldUnCheck = true for trainItem in filterItems where trainItem.type == .Train && trainItem.isChecked { if trainItem.IsMatchKey(of: item) { shouldUnCheck = false break } } if shouldUnCheck { item.isChecked = false } } } func initItemByTrainFilterKey(_ trainFilterKey:String) { for item in filterItems where item.type == .Train { if trainFilterKey.contains(item.key) { item.isChecked = true } else { item.isChecked = false } } } func initItemBySeatFilterKey(_ seatFilterKey:String) { for item in filterItems where item.type == .SeatType { if seatFilterKey.contains(item.presentation) { item.isChecked = true } else { item.isChecked = false } } } func initItemByPreferenceTimeFilterItem() { var initFilterItems = [FilterItem]() var timeSpan = GeneralPreferenceManager.sharedInstance.userDefindStartFilterTimeSpan var timeStatus = GeneralPreferenceManager.sharedInstance.userDefindStartFilterTimeStatus var count = min(timeSpan.count, timeStatus.count) for i in 0..<count { let item = FilterItem(type: .StartTime,key:timeSpan[i],presentation: timeSpan[i],isChecked: timeStatus[i]) if !item.isChecked { initFilterItems.append(item) } } timeSpan = GeneralPreferenceManager.sharedInstance.userDefindEndFilterTimeSpan timeStatus = GeneralPreferenceManager.sharedInstance.userDefindEndFilterTimeStatus count = min(timeSpan.count, timeStatus.count) for i in 0..<count { let item = FilterItem(type: .EndTime,key:timeSpan[i],presentation: timeSpan[i],isChecked: timeStatus[i]) if !item.isChecked { initFilterItems.append(item) } } for item in initFilterItems { for filterItem in filterItems where filterItem.key == item.key && filterItem.type == item.type { filterItem.isChecked = item.isChecked break } filterTrainBy(item, Off2On: false) } } func createFilterItemBy(_ trains:[QueryLeftNewDTO]){ filterItems.append(FilterItem(type: .Group,presentation: "席别类型")) filterItems.append(FilterItem(type: .SeatType,key:"9|P|4|6",presentation: "商务座|特等座|软卧|高级软卧",isChecked: false)) filterItems.append(FilterItem(type: .SeatType,key:"M|3",presentation: "一等座|硬卧",isChecked: false)) filterItems.append(FilterItem(type: .SeatType,key:"O|1",presentation: "二等座|硬座",isChecked: true)) filterItems.append(FilterItem(type: .SeatType,key:"1|O",presentation: "无座",isChecked: false)) filterItems.append(FilterItem(type: .Group,presentation: "出发时段")) var timeSpan = GeneralPreferenceManager.sharedInstance.userDefindStartFilterTimeSpan for i in 0..<timeSpan.count { let item = FilterItem(type: .StartTime,key:timeSpan[i],presentation: timeSpan[i],isChecked: true) filterItems.append(item) } filterItems.append(FilterItem(type: .Group,presentation: "到达时段")) timeSpan = GeneralPreferenceManager.sharedInstance.userDefindEndFilterTimeSpan for i in 0..<timeSpan.count { let item = FilterItem(type: .EndTime,key:timeSpan[i],presentation: timeSpan[i],isChecked: true) filterItems.append(item) } filterItems.append(FilterItem(type: .Group,presentation: "车次类型")) var hasTrainG = false var hasTrainC = false var hasTrainD = false var hasTrainZ = false var hasTrainT = false var hasTrainK = false var hasTrainL = false for train in trains { if train.TrainCode.hasPrefix("G") { hasTrainG = true continue } if train.TrainCode.hasPrefix("C") { hasTrainC = true continue } if train.TrainCode.hasPrefix("D") { hasTrainD = true continue } if train.TrainCode.hasPrefix("Z") { hasTrainZ = true continue } if train.TrainCode.hasPrefix("T") { hasTrainT = true continue } if train.TrainCode.hasPrefix("K") { hasTrainK = true continue } let keys = ["L","Y","1","2","3","4","5","6","7","8","9"] for key in keys { if train.TrainCode.hasPrefix(key) { hasTrainL = true break } } } if hasTrainG { filterItems.append(FilterItem(type: .TrainType,key:"G",presentation: "G高铁",isChecked: true)) } if hasTrainC { filterItems.append(FilterItem(type: .TrainType,key:"C",presentation: "C城际",isChecked: true)) } if hasTrainD { filterItems.append(FilterItem(type: .TrainType,key:"D",presentation: "D动车",isChecked: true)) } if hasTrainZ { filterItems.append(FilterItem(type: .TrainType,key:"Z",presentation: "Z直达",isChecked: true)) } if hasTrainT { filterItems.append(FilterItem(type: .TrainType,key:"T",presentation: "T特快",isChecked: true)) } if hasTrainK { filterItems.append(FilterItem(type: .TrainType,key:"K",presentation: "K快车",isChecked: true)) } if hasTrainL { filterItems.append(FilterItem(type: .TrainType,key:"L|Y|1|2|3|4|5|6|7|8|9",presentation: "LY临客|纯数字",isChecked: true)) } filterItems.append(FilterItem(type: .Group,presentation: "出发车站")) var fromStations = [String]() for train in trains where !fromStations.contains(train.FromStationName!) { fromStations.append(train.FromStationName!) filterItems.append(FilterItem(type: .FromStation, key: train.FromStationCode!, presentation: train.FromStationName!, isChecked: true)) } filterItems.append(FilterItem(type: .Group,presentation: "到达车站")) var toStations = [String]() for train in trains where !toStations.contains(train.ToStationName!){ toStations.append(train.ToStationName!) filterItems.append(FilterItem(type: .ToStation, key: train.ToStationCode!, presentation: train.ToStationName!, isChecked: true)) } filterItems.append(FilterItem(type: .Group,presentation: "指定车次")) for train in trains { let key = "\(train.TrainCode!)|\(train.start_time!)|\(train.FromStationCode!)|\(train.ToStationCode!)|\(train.arrive_time!)" let presentation = "\(train.TrainCode!) |1\(train.start_time!)~\(train.arrive_time!) |2\(train.FromStationName!)->\(train.ToStationName!)" filterItems.append(FilterItem(type: .Train, key: key, presentation: presentation, isChecked: true)) } } func getFilterKey(){ trainFilterKey = "|" seatFilterKey = "|" for item in filterItems { if ((item.type == .Train) && (item.isChecked)) { trainFilterKey += "\(item.key)|" } if ((item.type == .SeatType) && (item.isChecked)) { seatFilterKey += "\(item.presentation)|" } } } @IBAction func clickResetFilterItem(_ sender: NSButton) { filterItems = [FilterItem]() createFilterItemBy(trains!) initItemByPreferenceTimeFilterItem() trainFilterTable.reloadData() } @IBAction func clickTrainFilterBtn(_ sender: NSButton) { let row = trainFilterTable.row(for: sender) let selectedItem = filterItems[row] if selectedItem.type == .Train || selectedItem.type == .SeatType { return } var Off2On:Bool if sender.state == NSOnState { Off2On = true } else { Off2On = false } filterTrainBy(selectedItem, Off2On: Off2On) trainFilterTable.reloadData() } func filterTrainBy(_ selectedItem: FilterItem,Off2On:Bool) { for item in filterItems where (item.type == .Train && item.isChecked != Off2On) { //1 -> 0 if Off2On == false { if item.IsMatchKey(of: selectedItem) { item.isChecked = Off2On } }//0 -> 1 else { //检查其他筛选条件 var otherItemCanChange = true for filterItem in filterItems where ((filterItem.type == .FromStation) || (filterItem.type == .ToStation) || (filterItem.type == .StartTime) || (filterItem.type == .EndTime) || (filterItem.type == .TrainType)) && (filterItem != selectedItem) { if filterItem.isChecked == true { continue } if item.IsMatchKey(of: filterItem) { otherItemCanChange = false break } } //若满足其他筛选条件 则进行本次筛选判断 if otherItemCanChange { if item.IsMatchKey(of: selectedItem) { item.isChecked = Off2On } } } } } @IBAction func clickCancel(_ sender: AnyObject) { dismissWithModalResponse(NSModalResponseCancel) } @IBAction func clickOK(_ sender: AnyObject) { getFilterKey() dismissWithModalResponse(NSModalResponseOK) } deinit { print("TrainFilterWindowController deinit") } } // MARK: - NSTableViewDelegate / NSTableViewDataSource extension TrainFilterWindowController:NSTableViewDelegate,NSTableViewDataSource { func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { return filterItems[row] } func numberOfRows(in tableView: NSTableView) -> Int { return filterItems.count } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { if filterItems[row].type == .Group { return 20 } else{ return 25 } } func tableView(_ tableView: NSTableView, isGroupRow row: Int) -> Bool { if filterItems[row].type == .Group { return true } else { return false } } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let mainCell:NSView? if filterItems[row].type == .Group { mainCell = tableView.make(withIdentifier: "TextCell", owner: nil) } else if filterItems[row].type == .Train { mainCell = tableView.make(withIdentifier: "TrainInfoCell", owner: nil) } else{ mainCell = tableView.make(withIdentifier: "MainCell", owner: nil) } if let view = mainCell?.viewWithTag(100) { let btn = view as! NSButton btn.target = self btn.action = #selector(clickTrainFilterBtn(_:)) } return mainCell } }
24a7b0da78fe34d3ad9f137caccae2e0
33.37581
259
0.548442
false
false
false
false
raphaelhanneken/iconizer
refs/heads/master
Iconizer/Helper/NSImageExtensions.swift
mit
1
// // NSImageExtensions.swift // Iconizer // https://github.com/raphaelhanneken/iconizer // import Cocoa extension NSImage { /// The height of the image. var height: CGFloat { return size.height } /// The width of the image. var width: CGFloat { return size.width } /// The image size in pixels. var sizeInPixels: NSSize? { guard let imageRep = representations.first else { return nil } return NSSize(width: imageRep.pixelsWide, height: imageRep.pixelsHigh) } /// A PNG representation of the image. var PNGRepresentation: Data? { if let tiff = self.tiffRepresentation, let tiffData = NSBitmapImageRep(data: tiff) { return tiffData.representation(using: .png, properties: [:]) } return nil } /// A PNG representation of the image, but without the alpha channel var pngRepresentationWithoutAlpha: Data? { guard let tiff = self.tiffRepresentation, let imgDataWithoutAlpha = NSBitmapImageRep(data: tiff)?.representation(using: .jpeg, properties: [:]) else { return nil } return NSBitmapImageRep(data: imgDataWithoutAlpha)?.representation(using: .png, properties: [:]) } /// Resize the image to the given size. /// /// - Parameter size: The size to resize the image to. /// - Returns: The resized image. func resize(toSize targetSize: NSSize, aspectMode: AspectMode) -> NSImage? { let newSize = self.calculateAspectSize(withTargetSize: targetSize, aspectMode: aspectMode) ?? targetSize let xCoordinate = round((targetSize.width - newSize.width) / 2) let yCoordinate = round((targetSize.height - newSize.height) / 2) let targetFrame = NSRect(origin: NSPoint.zero, size: targetSize) let frame = NSRect(origin: NSPoint(x: xCoordinate, y: yCoordinate), size: newSize) var backColor = NSColor.clear if let tiff = self.tiffRepresentation, let tiffData = NSBitmapImageRep(data: tiff) { backColor = tiffData.colorAt(x: 0, y: 0) ?? NSColor.clear } return NSImage(size: targetSize, flipped: false) { (_: NSRect) -> Bool in backColor.setFill() NSBezierPath.fill(targetFrame) guard let rep = self.bestRepresentation(for: NSRect(origin: NSPoint.zero, size: newSize), context: nil, hints: nil) else { return false } return rep.draw(in: frame) } } /// Saves the PNG representation of the image to the supplied URL parameter. /// /// - Parameter url: The URL to save the image data to. /// - Throws: An NSImageExtensionError if unwrapping the image data fails. /// An error in the Cocoa domain, if there is an error writing to the URL. func savePng(url: URL, withoutAlpha: Bool = false) throws { guard let png = withoutAlpha ? pngRepresentationWithoutAlpha : PNGRepresentation else { throw NSImageExtensionError.unwrappingPNGRepresentationFailed } try png.write(to: url, options: .atomicWrite) } /// Calculate the image size for a given aspect mode. /// /// - Parameters: /// - targetSize: The size the image should be resized to /// - aspectMode: The aspect mode to calculate the actual image size /// - Returns: The new image size private func calculateAspectSize(withTargetSize targetSize: NSSize, aspectMode: AspectMode) -> NSSize? { if aspectMode == .fit { return self.calculateFitAspectSize(widthRatio: targetSize.width / self.width, heightRatio: targetSize.height / self.height) } if aspectMode == .fill { return self.calculateFillAspectSize(widthRatio: targetSize.width / self.width, heightRatio: targetSize.height / self.height) } return nil } /// Calculate the size for an image to be resized in aspect fit mode; That is resizing it without /// cropping the image. /// /// - Parameters: /// - widthRatio: The width ratio of the image and the target size the image should be resized to. /// - heightRatio: The height retio of the image and the targed size the image should be resized to. /// - Returns: The maximum size the image can have, to fit inside the targed size, without cropping anything. private func calculateFitAspectSize(widthRatio: CGFloat, heightRatio: CGFloat) -> NSSize { if widthRatio < heightRatio { return NSSize(width: floor(self.width * widthRatio), height: floor(self.height * widthRatio)) } return NSSize(width: floor(self.width * heightRatio), height: floor(self.height * heightRatio)) } /// Calculate the size for an image to be resized in aspect fill mode; That is resizing it and cropping /// the edges of the image, if necessary. /// /// - Parameters: /// - widthRatio: The width ratio of the image and the target size the image should be resized to. /// - heightRatio: The height retio of the image and the targed size the image should be resized to. /// - Returns: The minimum size the image needs to have to fill the complete target area. private func calculateFillAspectSize(widthRatio: CGFloat, heightRatio: CGFloat) -> NSSize? { if widthRatio > heightRatio { return NSSize(width: floor(self.width * widthRatio), height: floor(self.height * widthRatio)) } return NSSize(width: floor(self.width * heightRatio), height: floor(self.height * heightRatio)) } }
f41c431e4b3010d603ce370a699c5944
41.330935
116
0.624235
false
false
false
false
LeeMZC/MZCWB
refs/heads/master
MZCWB/MZCWB/Classes/Home-首页/View/MZCHomeTitleButton.swift
artistic-2.0
1
// // MZCHomeTitleButton.swift // MZCWB // // Created by 马纵驰 on 16/7/21. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit import QorumLogs class MZCHomeTitleButton: UIButton { private let spacing = 20 override init(frame: CGRect) { super.init(frame: frame) setupNotificationCenter() setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func setupNotificationCenter(){ // 3.注册通知 NSNotificationCenter.defaultCenter().addObserver(self, selector : #selector(MZCHomeTitleButton.titleChange), name: MZCHomeTitleButtonDidChange, object: nil) } private func setupUI(){ assert(accountTokenMode != nil, "用户信息无法获取") self.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal) self.setTitle(accountTokenMode!.user?.screen_name, forState: UIControlState.Normal) self.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) self.sizeToFit() self.frame.size.width += (CGFloat)(spacing) } override func layoutSubviews() { super.layoutSubviews() titleLabel?.frame.origin.x = 0.0 imageView?.frame.origin.x = (titleLabel?.frame.size.width )! + (CGFloat)(spacing / 2) } func imgAnimation(){ guard let tempImgView = imageView else{ return } selected = !selected let timer = 0.5 if selected { UIView.animateWithDuration(timer, animations: { tempImgView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) }) }else{ UIView.animateWithDuration(timer, animations: { tempImgView.transform = CGAffineTransformIdentity }) } } func titleChange(){ imgAnimation() } deinit{ // 移除通知 NSNotificationCenter.defaultCenter().removeObserver(self) } }
a5c4858f3b91badbecf841630a247923
25.43038
164
0.598659
false
false
false
false