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
ios-archy/Sinaweibo_swift
refs/heads/master
SinaWeibo_swift/SinaWeibo_swift/Classess/Home/Popover/ArchyPresentationController.swift
mit
1
// // ArchyPresentationController.swift // SinaWeibo_swift // // Created by archy on 16/10/21. // Copyright © 2016年 archy. All rights reserved. // import UIKit class ArchyPresentationController: UIPresentationController { //MARK: --对外提供属性 var presentedFrame : CGRect = CGRectZero //MARK: --懒加载属性 private lazy var coverView = UIView() //MARK: --系统回调函数 override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() //1.设置弹出View的尺寸 presentedView()?.frame = presentedFrame //2.添加蒙版 setupCoverView() } } extension ArchyPresentationController { private func setupCoverView() { //1.添加蒙版 containerView?.insertSubview(coverView, atIndex: 0) //2.设置蒙版属性 coverView.backgroundColor = UIColor(white: 0.8, alpha: 0.2) coverView.frame = containerView!.bounds //3.添加手势 let tapGes = UITapGestureRecognizer(target: self, action: "coverViewClick") coverView.addGestureRecognizer(tapGes) } } extension ArchyPresentationController { @objc private func coverViewClick(){ presentedViewController.dismissViewControllerAnimated(true, completion: nil) } }
e196338f13ce98930aac43f2dda832fb
21.789474
84
0.641757
false
false
false
false
johnno1962d/swift
refs/heads/master
test/SILOptimizer/devirt_covariant_return.swift
apache-2.0
1
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -Xllvm -disable-sil-cm-rr-cm=0 -primary-file %s -emit-sil -sil-inline-threshold 1000 -sil-verify-all | FileCheck %s // Make sure that we can dig all the way through the class hierarchy and // protocol conformances with covariant return types correctly. The verifier // should trip if we do not handle things correctly. // // As a side-test it also checks if all allocs can be promoted to the stack. // CHECK-LABEL: sil hidden @_TF23devirt_covariant_return6driverFT_T_ : $@convention(thin) () -> () { // CHECK: bb0 // CHECK: alloc_ref [stack] // CHECK: alloc_ref [stack] // CHECK: alloc_ref [stack] // CHECK: function_ref @unknown1a : $@convention(thin) () -> () // CHECK: apply // CHECK: function_ref @defenestrate : $@convention(thin) () -> () // CHECK: apply // CHECK: function_ref @unknown2a : $@convention(thin) () -> () // CHECK: apply // CHECK: apply // CHECK: function_ref @unknown3a : $@convention(thin) () -> () // CHECK: apply // CHECK: apply // CHECK: dealloc_ref [stack] // CHECK: dealloc_ref [stack] // CHECK: dealloc_ref [stack] // CHECK: tuple // CHECK: return @_silgen_name("unknown1a") func unknown1a() -> () @_silgen_name("unknown1b") func unknown1b() -> () @_silgen_name("unknown2a") func unknown2a() -> () @_silgen_name("unknown2b") func unknown2b() -> () @_silgen_name("unknown3a") func unknown3a() -> () @_silgen_name("unknown3b") func unknown3b() -> () @_silgen_name("defenestrate") func defenestrate() -> () class B<T> { // We do not specialize typealias's correctly now. //typealias X = B func doSomething() -> B<T> { unknown1a() return self } // See comment in protocol P //class func doSomethingMeta() { // unknown1b() //} func doSomethingElse() { defenestrate() } } class B2<T> : B<T> { // When we have covariance in protocols, change this to B2. // We do not specialize typealias correctly now. //typealias X = B override func doSomething() -> B2<T> { unknown2a() return self } // See comment in protocol P //override class func doSomethingMeta() { // unknown2b() //} } class B3<T> : B2<T> { override func doSomething() -> B3<T> { unknown3a() return self } } func WhatShouldIDo<T>(_ b : B<T>) -> B<T> { b.doSomething().doSomethingElse() return b } func doSomethingWithB<T>(_ b : B<T>) { } struct S {} func driver() -> () { let b = B<S>() let b2 = B2<S>() let b3 = B3<S>() WhatShouldIDo(b) WhatShouldIDo(b2) WhatShouldIDo(b3) } driver() public class Bear { public init?(fail: Bool) { if fail { return nil } } // Check that devirtualizer can handle convenience initializers, which have covariant optional // return types. // CHECK-LABEL: sil @_TFC23devirt_covariant_return4Bearc // CHECK: checked_cast_br [exact] %{{.*}} : $Bear to $PolarBear // CHECK: upcast %{{.*}} : $Optional<PolarBear> to $Optional<Bear> // CHECK: } public convenience init?(delegateFailure: Bool, failAfter: Bool) { self.init(fail: delegateFailure) if failAfter { return nil } } } final class PolarBear: Bear { override init?(fail: Bool) { super.init(fail: fail) } init?(chainFailure: Bool, failAfter: Bool) { super.init(fail: chainFailure) if failAfter { return nil } } } class Payload { let value: Int32 init(_ n: Int32) { value = n } func getValue() -> Int32 { return value } } final class Payload1: Payload { override init(_ n: Int32) { super.init(n) } } class C { func doSomething() -> Payload? { return Payload(1) } } final class C1:C { // Override base method, but return a non-optional result override func doSomething() -> Payload { return Payload(2) } } final class C2:C { // Override base method, but return a non-optional result of a type, // which is derived from the expected type. override func doSomething() -> Payload1 { return Payload1(2) } } // Check that the Optional return value from doSomething // gets properly unwrapped into a Payload object and then further // devirtualized. // CHECK-LABEL: sil hidden @_TTSf4dg___TF23devirt_covariant_return7driver1FCS_2C1Vs5Int32 // CHECK: integer_literal $Builtin.Int32, 2 // CHECK: struct $Int32 (%{{.*}} : $Builtin.Int32) // CHECK-NOT: class_method // CHECK-NOT: function_ref // CHECK: return func driver1(_ c: C1) -> Int32 { return c.doSomething().getValue() } // Check that the Optional return value from doSomething // gets properly unwrapped into a Payload object and then further // devirtualized. // CHECK-LABEL: sil hidden @_TTSf4g___TF23devirt_covariant_return7driver3FCS_1CVs5Int32 // CHECK: bb{{[0-9]+}}(%{{[0-9]+}} : $C2): // CHECK-NOT: bb{{.*}}: // check that for C2, we convert the non-optional result into an optional and then cast. // CHECK: enum $Optional // CHECK-NEXT: upcast // CHECK: return func driver3(_ c: C) -> Int32 { return c.doSomething()!.getValue() } public class D { let v: Int32 init(_ n: Int32) { v = n } } public class D1 : D { public func foo() -> D? { return nil } public func boo() -> Int32 { return foo()!.v } } let sD = D(0) public class D2: D1 { // Override base method, but return a non-optional result override public func foo() -> D { return sD } } // Check that the boo call gets properly devirtualized and that // that D2.foo() is inlined thanks to this. // CHECK-LABEL: sil hidden @_TTSf4g___TF23devirt_covariant_return7driver2FCS_2D2Vs5Int32 // CHECK-NOT: class_method // CHECK: checked_cast_br [exact] %{{.*}} : $D1 to $D2 // CHECK: bb2 // CHECK: global_addr // CHECK: load // CHECK: ref_element_addr // CHECK: bb3 // CHECK: class_method // CHECK: } func driver2(_ d: D2) -> Int32 { return d.boo() } class AA { } class BB : AA { } class CCC { @inline(never) func foo(_ b: BB) -> (AA, AA) { return (b, b) } } class DDD : CCC { @inline(never) override func foo(_ b: BB) -> (BB, BB) { return (b, b) } } class EEE : CCC { @inline(never) override func foo(_ b: BB) -> (AA, AA) { return (b, b) } } // Check that c.foo() is devirtualized, because the optimizer can handle the casting the return type // correctly, i.e. it can cast (BBB, BBB) into (AAA, AAA) // CHECK-LABEL: sil hidden @_TTSf4g_n___TF23devirt_covariant_return37testDevirtOfMethodReturningTupleTypesFTCS_3CCC1bCS_2BB_TCS_2AAS2__ // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $CCC // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $DDD // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $EEE // CHECK: class_method // CHECK: } func testDevirtOfMethodReturningTupleTypes(_ c: CCC, b: BB) -> (AA, AA) { return c.foo(b) } class AAAA { } class BBBB : AAAA { } class CCCC { let a: BBBB var foo : (AAAA, AAAA) { @inline(never) get { return (a, a) } } init(x: BBBB) { a = x } } class DDDD : CCCC { override var foo : (BBBB, BBBB) { @inline(never) get { return (a, a) } } } // Check devirtualization of methods with optional results, where // optional results need to be casted. // CHECK-LABEL: sil @{{.*}}testOverridingMethodWithOptionalResult // CHECK: checked_cast_br [exact] %{{.*}} : $F to $F // CHECK: checked_cast_br [exact] %{{.*}} : $F to $G // CHECK: switch_enum // CHECK: checked_cast_br [exact] %{{.*}} : $F to $H // CHECK: switch_enum public func testOverridingMethodWithOptionalResult(_ f: F) -> (F?, Int)? { return f.foo() } public class F { @inline(never) public func foo() -> (F?, Int)? { return (F(), 1) } } public class G: F { @inline(never) override public func foo() -> (G?, Int)? { return (G(), 2) } } public class H: F { @inline(never) override public func foo() -> (H?, Int)? { return nil } }
7e288bce3daadda27cb2579a613aecd4
21.344828
176
0.633102
false
false
false
false
zmian/xcore.swift
refs/heads/main
Sources/Xcore/Cocoa/Extensions/UIApplication+Extensions.swift
mit
1
// // Xcore // Copyright © 2015 Xcore // MIT license, see LICENSE file for details // import UIKit extension UIApplication { /// Swift doesn't allow marking parts of Swift framework unavailable for the App /// Extension target. This solution let's us overcome this limitation for now. /// /// `UIApplication.shared` is marked as unavailable for these for App Extension /// target. /// /// https://bugs.swift.org/browse/SR-1226 is still unresolved /// and cause problems. It seems that as of now, marking API as unavailable /// for extensions in Swift still doesn’t let you compile for App extensions. public static var sharedOrNil: UIApplication? { let sharedApplicationSelector = NSSelectorFromString("sharedApplication") guard UIApplication.responds(to: sharedApplicationSelector) else { return nil } guard let unmanagedSharedApplication = UIApplication.perform(sharedApplicationSelector) else { return nil } return unmanagedSharedApplication.takeUnretainedValue() as? UIApplication } /// Swift doesn't allow marking parts of Swift framework unavailable for the App /// Extension target. This solution let's us overcome this limitation for now. /// /// `UIApplication.shared.open(_:options:completionHandler:)"` is marked as /// unavailable for these for App Extension target. /// /// https://bugs.swift.org/browse/SR-1226 is still unresolved /// and cause problems. It seems that as of now, marking API as unavailable /// for extensions in Swift still doesn’t let you compile for App extensions. public func appExtensionSafeOpen(_ url: URL) { guard let application = UIApplication.sharedOrNil else { return } let selector = NSSelectorFromString("openURL:options:completionHandler:") guard let method = application.method(for: selector) else { Console.warn("Dynamic selector \(selector) isn't available.") return } typealias ClosureType = @convention(c) (UIApplication, Selector, URL, [UIApplication.OpenExternalURLOptionsKey: Any], ((Bool) -> Void)?) -> Void let _open: ClosureType = unsafeBitCast(method, to: ClosureType.self) _open(application, selector, url, [:], nil) } } extension UIApplication { /// A property to determine whether it's the Main App or App Extension target. /// /// - [Creating an App Extension](https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionCreation.html) public static var isAppExtension: Bool { Bundle.main.bundlePath.hasSuffix(".appex") } } // MARK: - TopViewController extension UIApplication { open class func topViewController(_ base: UIViewController? = UIApplication.sharedOrNil?.firstSceneKeyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = base?.presentedViewController { return topViewController(presented) } return base } /// Returns the top navigation controller from top windows in this application /// instance. public var topNavigationController: UINavigationController? { let visibleWindows = windows.filter { !$0.isHidden }.reversed() for window in visibleWindows { let topViewController = window.topViewController if let topNavigationController = topViewController?.navigationController { return topNavigationController } // Look for child view controllers for childViewController in topViewController?.children ?? [] { if let topNavigationController = childViewController as? UINavigationController { return topNavigationController } } } return nil } } // MARK: - UIWindow - TopViewController extension UIWindow { /// The view controller at the top of the window's `rootViewController` stack. open var topViewController: UIViewController? { UIApplication.topViewController(rootViewController) } } extension UIApplication { /// Iterates through `windows` from top to bottom and returns window matching /// the given `keyPaths`. /// /// - Returns: Returns an optional window object based on attributes options. /// - Complexity: O(_n_), where _n_ is the length of the `windows` array. public func window(_ keyPaths: KeyPath<UIWindow, Bool>...) -> UIWindow? { windows.reversed().first(keyPaths) } /// Iterates through app's first currently active scene's `windows` from top to /// bottom and returns window matching the given `keyPaths`. /// /// - Returns: Returns an optional window object based on attributes options. /// - Complexity: O(_n_), where _n_ is the length of the `windows` array. public func sceneWindow(_ keyPaths: KeyPath<UIWindow, Bool>...) -> UIWindow? { firstWindowScene? .windows .lazy .reversed() .first(keyPaths) } /// Returns the app's first currently active scene's first key window. public var firstSceneKeyWindow: UIWindow? { sceneWindow(\.isKeyWindow) } /// Returns the app's first window scene. public var firstWindowScene: UIWindowScene? { windowScenes.first } /// Returns all of the connected window scenes sorted by from active state to /// background state. public var windowScenes: [UIWindowScene] { connectedScenes .lazy .compactMap { $0 as? UIWindowScene } .sorted { $0.activationState.sortOrder < $1.activationState.sortOrder } } } // MARK: - ActivationState extension UIScene.ActivationState: CustomStringConvertible { public var description: String { switch self { case .foregroundActive: return "foregroundActive" case .foregroundInactive: return "foregroundInactive" case .background: return "background" case .unattached: return "unattached" @unknown default: warnUnknown(self) return "unknown" } } fileprivate var sortOrder: Int { switch self { case .foregroundActive: return 0 case .foregroundInactive: return 1 case .background: return 2 case .unattached: return 3 @unknown default: warnUnknown(self) return 4 } } }
f05d56d531e2ed63d19ca7d77164cf04
34.225
156
0.639177
false
false
false
false
DarlingXIe/WeiBoProject
refs/heads/master
WeiBo/WeiBo/Classes/View/compose/view/emotionKeyBoard/XDLEmotionCollectionViewCell.swift
mit
1
// // XDLEmotionCollectionViewCell.swift // WeiBo // // Created by DalinXie on 16/10/6. // Copyright © 2016年 itcast. All rights reserved. // import UIKit let XDLEmotionButtonsCount = 20; class XDLEmotionCollectionViewCell: UICollectionViewCell { lazy var emtionButtons = [XDLEmotionButton]() var emotions : [XDLEmotion]?{ didSet{ print(emotions) //MARK: add buttons for each cell for button in emtionButtons{ button.isHidden = true } for (index, emotion) in emotions!.enumerated(){ let button = emtionButtons[index] button.isHidden = false button.emotions = emotion } } } var indexpPath: IndexPath?{ didSet{ Testlabel.text = "第\(indexpPath!.section)组, 第 \(indexpPath!.item)页" recentEmotionLabel.isHidden = indexpPath!.section != 0 } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } override func layoutSubviews() { super.layoutSubviews() let itemW = self.bounds.size.width/7 let itemH = self.bounds.size.height/3 for(index, value) in emtionButtons.enumerated(){ // buttons for 6, col = 6%7 = 6, row = 6/7 = 6; for 7 col = 7%7 = 0 row = 7/7 = 1 let col = index % 7 let row = index / 7 let x = CGFloat(col) * itemW let y = CGFloat(row) * itemH value.frame = CGRect(x: x, y: y, width: itemW, height: itemH) } deleteButton.frame = CGRect(x: self.bounds.width - itemW, y: itemH * 2, width: itemW, height: itemH) } //itemW = self.screen.width/3 //itemH = self.screen.height/21 // col = index % 3 // row = index /3 // let x = CGFloat(col) * itemW // let y = CGFLoat(row) * itemH private func setupUI(){ contentView.addSubview(Testlabel) Testlabel.snp_makeConstraints { (make) in make.center.equalTo(self) } addButtons() contentView.addSubview(deleteButton) contentView.addSubview(recentEmotionLabel) recentEmotionLabel.snp_makeConstraints { (make) in make.centerX.equalTo(contentView.snp_centerX) make.bottom.equalTo(contentView).offset(-10) } let ges = UILongPressGestureRecognizer(target: self, action: #selector(longPress(ges:))) addGestureRecognizer(ges) } @objc private func longPress(ges: UILongPressGestureRecognizer){ func getButton(loction: CGPoint) -> XDLEmotionButton?{ for button in emtionButtons{ if button.frame.contains(loction){ return button } } return nil } switch ges.state { case .began, .changed: let location = ges.location(in: self) if let button = getButton(loction: location), button.isHidden == false { let emotion = button.emotions paopaoView.XDLEmotionButton.emotions = emotion let window = UIApplication.shared.windows.last! let rect = button.convert(button.bounds, to: window) paopaoView.center.x = rect.midX paopaoView.frame.origin.y = rect.maxY - paopaoView.frame.height window.addSubview(paopaoView) }else{ paopaoView.removeFromSuperview() } case .ended, .cancelled, .failed: paopaoView.removeFromSuperview() default: break } } //MARK: - deleteButtonFunction @objc private func deleteButtonfunc(){ NotificationCenter.default.post(name: NSNotification.Name(rawValue:XDLEmoticonButtonDidSelectedNotification), object: nil) } //MARK: - addChildButtons private func addButtons(){ for _ in 0..<XDLEmotionButtonsCount{ let button = XDLEmotionButton() button.titleLabel?.font = UIFont.systemFont(ofSize: 34) //button.backgroundColor = RandomColor button.addTarget(self, action: #selector(emotionButtonClick(button:)), for: .touchUpInside) contentView.addSubview(button) emtionButtons.append(button) } } @objc private func emotionButtonClick(button:XDLEmotionButton){ let emotion = button.emotions paopaoView.XDLEmotionButton.emotions = emotion XDLEmotionViewModel.sharedViewModel.savetoRecent(emotion!) NotificationCenter.default.post(name: NSNotification.Name(rawValue: XDLEmoticonButtonDidSelectedNotification), object: nil, userInfo: ["emotion" : emotion!]) let window = UIApplication.shared.windows.last! let rect = button.convert(button.bounds, to: window) paopaoView.center.x = rect.midX paopaoView.frame.origin.y = rect.maxY - paopaoView.frame.height window.addSubview(paopaoView) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: { self.paopaoView.removeFromSuperview() }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var Testlabel : UILabel = {()-> UILabel in let label = UILabel() return label }() private lazy var deleteButton :UIButton = {()-> UIButton in let button = UIButton() button.addTarget(self, action: #selector(deleteButtonfunc),for: .touchUpInside) button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), for: .highlighted) button.setImage(UIImage(named: "compose_emotion_delete"), for: .normal) return button }() private lazy var recentEmotionLabel :UILabel = {()-> UILabel in let label = UILabel(textColor: UIColor.lightGray, fontSize: 12) label.text = "Recent emotions" return label }() private lazy var paopaoView: XDLEmotionButtonPaopaoView = XDLEmotionButtonPaopaoView.paopaoView() }
2d232ff34cb4b58c6ab062811224978d
28.418103
165
0.546667
false
false
false
false
mikkokut/SHMenu
refs/heads/master
SHMenu/SHMenuViewController.swift
mit
1
// // SHMenuViewController.h // SHMenuViewController // // Created by Mikko Kutilainen on 5.12.2015. // Copyright © 2015 Shingle Oy. All rights reserved. // import Foundation import UIKit open class SHMenuViewController: UITableViewController { open var sections = [SHMenuSection]() /** Override in order to respond to refresh event. Call self.endRefresh() after refreshing is finished. Please make sure you populate and reload your table view yourself. */ open func shouldRefresh() { self.endRefresh() } /** Call after refreshing is finished */ open func endRefresh() { self.refreshControl?.endRefreshing() } open func analyzeCells() -> Bool { for (sectionIndex, section) in self.sections.enumerated() { for (rowIndex, row) in section.rows.enumerated() { if let analyze = row.analyze { let cell = tableView.cellForRow(at: IndexPath(row: rowIndex, section: sectionIndex)) if analyze(cell) == false { return false } } } } return true } open func populate() { self.sections = [SHMenuSection]() } func prepareData( _ doneCb: ( (_ ok: Bool, _ error: NSError?) -> () ) ) { doneCb(true, nil) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.populate() } override open func numberOfSections(in tableView: UITableView) -> Int { return self.sections.count } override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sections[section].rows.count } override open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sections[section].header } override open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return self.sections[section].footer } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row] return row.cell(self.tableView) } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row] if let action = row.action { action(indexPath) if row.automaticallyDeselectSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } } } override open func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row] if let action = row.accessoryAction { action(indexPath) } } override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let row = self.sections[(indexPath as NSIndexPath).section].rows[(indexPath as NSIndexPath).row] return row.preferredHeight } override open func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { if let view = view as? UITableViewHeaderFooterView { let section = self.sections[section] view.textLabel?.textAlignment = section.footerTextAlignment ?? .left } } }
28b0732374a543fbba532300b9818770
29.444444
121
0.620438
false
false
false
false
szweier/SZMentionsSwift
refs/heads/master
Classes/Internal/String.swift
mit
1
// // String.swift // SZMentionsSwift // // Created by Steve Zweier on 2/1/16. // Copyright © 2016 Steven Zweier. All rights reserved. // import UIKit internal extension String { func range(of strings: [String], options: NSString.CompareOptions, range: NSRange? = nil) -> (range: NSRange, foundString: String) { let nsself = (self as NSString) var foundRange = NSRange(location: NSNotFound, length: 0) let string = strings.first { if let range = range { foundRange = nsself.range(of: $0, options: options, range: range) } else { foundRange = nsself.range(of: $0, options: options) } return foundRange.location != NSNotFound } ?? "" return (foundRange, string) } func isMentionEnabledAt(_ location: Int) -> (Bool, String) { guard location != 0 else { return (true, "") } let start = utf16.index(startIndex, offsetBy: location - 1) let end = utf16.index(start, offsetBy: 1) let textBeforeTrigger = String(utf16[start ..< end]) ?? "" return (textBeforeTrigger == " " || textBeforeTrigger == "\n", textBeforeTrigger) } }
57c0498905c53cea64984f6246ff3f15
30.710526
136
0.595851
false
false
false
false
andrea-prearo/SwiftExamples
refs/heads/master
TaskList/TaskList/TasksDataSource.swift
mit
1
// // TasksDataSource.swift // TaskList // // Created by Andrea Prearo on 5/1/17. // Copyright © 2017 Andrea Prearo. All rights reserved. // import UIKit struct TasksDataSource { var tasks: [Task]? = nil { didSet { if oldValue == nil { viewModels = initializeViewModels() } } } fileprivate var viewModels: [[TaskViewModel]] = [[]] fileprivate var headerViewModels: [TaskHeaderViewModel] = Priority.allValues().map { return TaskHeaderViewModel(sectionText: $0.asString) } public var isGrouped = false { didSet { viewModels = rearrangeTasks(isGrouped: isGrouped) } } // MARK: - Public Methods func numberOfSections() -> Int { return viewModels.count } func numberOfItems(inSection section: Int) -> Int { return viewModels[section].count } func header(for section: Int) -> TaskHeaderViewModel? { return headerViewModels[section] } func item(at indexPath: IndexPath) -> TaskViewModel? { return viewModels[indexPath.section][indexPath.row] } mutating func updateItem(at indexPath: IndexPath, checked: Bool) { guard let updateTask = updateTask(at: indexPath, checked: checked) else { return } updateTaskViewModel(at: indexPath, task: updateTask, checked: checked) } @discardableResult mutating func updateTask(at indexPath: IndexPath, checked: Bool) -> Task? { let viewModel = viewModels[indexPath.section][indexPath.row] let originalTask = viewModel.task let taskIndex: Int? if isGrouped { taskIndex = tasks?.firstIndex { return $0 == originalTask } } else { taskIndex = indexPath.row } guard let index = taskIndex else { return nil } let updatedTask = Task(name: originalTask.name, priority: originalTask.priority, completed: checked) tasks?[index] = updatedTask return updatedTask } @discardableResult mutating func updateTaskViewModel(at indexPath: IndexPath, task: Task, checked: Bool) -> TaskViewModel? { let updatedViewModel = TaskViewModel(task: task) viewModels[indexPath.section][indexPath.row] = updatedViewModel return updatedViewModel } } // MARK: - Private Methods fileprivate extension TasksDataSource { func initializeViewModels() -> [[TaskViewModel]] { guard let tasks = tasks else { return [[]] } return [tasks.map { return TaskViewModel(task: $0) }] } func rearrangeTasks(isGrouped: Bool) -> [[TaskViewModel]] { guard let tasks = tasks else { return [[]] } let viewModels: [[TaskViewModel]] if isGrouped { var unknownPriorities = [TaskViewModel]() var highPriorities = [TaskViewModel]() var mediumPriorities = [TaskViewModel]() var lowPriorities = [TaskViewModel]() for task in tasks { switch task.priority { case .unknown: unknownPriorities.append(TaskViewModel(task: task)) case .high: highPriorities.append(TaskViewModel(task: task)) case .medium: mediumPriorities.append(TaskViewModel(task: task)) case .low: lowPriorities.append(TaskViewModel(task: task)) } } viewModels = [ unknownPriorities, highPriorities, mediumPriorities, lowPriorities ] } else { viewModels = initializeViewModels() } return viewModels } }
3abca265e52b4264d80a87cb66eb1b19
29.456693
109
0.577818
false
false
false
false
jonreiling/Rockbox-Framework-Swift
refs/heads/master
Source/RockboxClient.swift
mit
1
// // RockboxClient.swift // Rockbox-Client-Swift // // Created by Jon Reiling on 12/25/15. // Copyright © 2015 AKQA. All rights reserved. // import Foundation import Socket_IO_Client_Swift import Alamofire import SwiftyJSON public struct RockboxEvent { public static let State = "kRockboxStateUpdate" public static let Volume = "kRockboxVolumeUpdate" public static let Queue = "kRockboxQueueUpdate" public static let PassthroughConnection = "kRockboxPassthroughConnectionUpdate" } public class RockboxClient : RockboxBase { public static let sharedInstance = RockboxClient() private var socket:SocketIOClient! override init() {} public func connect() { setupSockets() socket.connect() } public func disconnect() { socket.disconnect() } //MARK: - //MARK: Rockbox API functions override public func add(id:String) { if ( connected ) { self.socket.emit("add", id) } else { super.add(id) } } override public func togglePlayPause() { if ( connected ) { self.socket.emit("pause") } else { super.togglePlayPause() } } override public func skip() { if ( connected ) { self.socket.emit("skip") } else { super.skip() } } override public func setRadio(radioOn:Bool) { if ( connected ) { self.socket.emit("setRadio",radioOn) } else { super.setRadio(radioOn) } } override public func setVolume(vol:AnyObject) { if ( connected ) { self.socket.emit("setVolume",vol) } else { super.setVolume(vol) } } private func setupSockets() { socket = SocketIOClient(socketURL: server, options: [.Log(false),.Nsp("/rockbox-client"), .ForcePolling(true)]) socket.on("connect") {data, ack in print("socket connected") self.connected = true; } socket.on("disconnect") {data, ack in print("socket disconnected") self.connected = false; } socket.on("queueUpdate") {data, ack in let json:JSON = JSON(data[0]) var tracks:[RBTrack] = [] if let jsonTracks = json["queue"].array { for jsonTrack in jsonTracks { tracks.append( RBTrack(json:jsonTrack) ) } } self.queue = tracks NSNotificationCenter.defaultCenter().postNotificationName(RockboxEvent.Queue, object: nil); } socket.on("stateUpdate") {data, ack in let json:JSON = JSON(data[0]) if let isPlaying = json["playing"].bool { self.isPlaying = isPlaying } if let radioMode = json["radio"].bool { self.radioMode = radioMode } NSNotificationCenter.defaultCenter().postNotificationName(RockboxEvent.State, object: nil); } socket.on("volumeUpdate") {data, ack in let json:JSON = JSON(data[0]) if let volume = json["volume"].int { self.volume = volume } NSNotificationCenter.defaultCenter().postNotificationName(RockboxEvent.Volume, object: nil); } socket.on("passthroughConnectionUpdate") {data, ack in let json:JSON = JSON(data[0]) if let passthroughConnection = json["connected"].bool { self.passthroughConnection = passthroughConnection } NSNotificationCenter.defaultCenter().postNotificationName(RockboxEvent.PassthroughConnection, object: nil); } } }
83310eb385899261f3cdeef478e23d80
24.462025
119
0.53456
false
false
false
false
Ezimetzhan/Design-Patterns-In-Swift
refs/heads/master
source/behavioral/command.swift
gpl-3.0
26
/*: 👫 Command ---------- The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use. ### Example: */ protocol DoorCommand { func execute() -> String } class OpenCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Opened \(doors)" } } class CloseCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Closed \(doors)" } } class HAL9000DoorsOperations { let openCommand: DoorCommand let closeCommand: DoorCommand init(doors: String) { self.openCommand = OpenCommand(doors:doors) self.closeCommand = CloseCommand(doors:doors) } func close() -> String { return closeCommand.execute() } func open() -> String { return openCommand.execute() } } /*: ### Usage: */ let podBayDoors = "Pod Bay Doors" let doorModule = HAL9000DoorsOperations(doors:podBayDoors) doorModule.open() doorModule.close()
9025116880495f207dd7e2a44cb75597
19.557377
204
0.633174
false
false
false
false
AlwaysRightInstitute/mustache
refs/heads/main
Sources/Mustache/MustacheNode.swift
apache-2.0
1
// // MustacheNode.swift // Noze.io // // Created by Helge Heß on 6/1/16. // Copyright © 2016-2021 ZeeZide GmbH. All rights reserved. // /// One node of the Mustache template. A template is parsed into a tree of the /// various nodes. public enum MustacheNode: Equatable { case empty /// Represents the top-level node of a Mustache template, contains the list /// of nodes. case global([ MustacheNode]) /// Regular CDATA in the template case text(String) /// A section, can be either a repetition (if the value evaluates to a /// Sequence) or a conditional (if the value resolves to true/false). /// If the value is false or an empty list, the contained nodes won't be /// rendered. /// If the value is a Sequence, the contained items will be rendered n-times, /// once for each member. The rendering context is changed to the item before /// rendering. /// If the value is not a Sequence, but considered 'true', the contained nodes /// will get rendered once. /// /// A Mustache section is introduced with a "{{#" tag and ends with a "{{/" /// tag. /// Example: /// /// {{#addresses}} /// Has address in: {{city}} /// {{/addresses}} /// case section(String, [ MustacheNode ]) /// An inverted section either displays its contents or not, it never repeats. /// /// If the value is 'false' or an empty list, the contained nodes will get /// rendered. /// If it is 'true' or a non-empty list, it won't get rendered. /// /// An inverted section is introduced with a "{{^" tag and ends with a "{{/" /// tag. /// Example: /// /// {{^addresses}} /// The person has no addresses assigned. /// {{/addresses}} /// case invertedSection(String, [ MustacheNode ]) /// A Mustache Variable. Will try to lookup the given string as a name in the /// current context. If the current context doesn't have the name, the lookup /// is supposed to continue at the parent contexts. /// /// The resulting value will be HTML escaped. /// /// Example: /// /// {{city}} /// case tag(String) /// This is the same like Tag, but the value won't be HTML escaped. /// /// Use triple braces for unescaped variables: /// /// {{{htmlToEmbed}}} /// /// Or use an ampersand, like so: /// /// {{^ htmlToEmbed}} /// case unescapedTag(String) /// A partial. How this is looked up depends on the rendering context /// implementation. /// /// Partials are included via "{{>", like so: /// /// {{#names}} /// {{> user}} /// {{/names}} /// case partial(String) } // MARK: - Convert parsed nodes back to a String template public extension MustacheNode { @inlinable var asMustacheString : String { var s = String() self.append(toString: &s) return s } } public extension MustacheNode { @inlinable func append(toString s : inout String) { switch self { case .empty: return case .text(let text): s += text case .global(let nodes): nodes.forEach { $0.append(toString: &s) } case .section(let key, let nodes): s += "{{#\(key)}}" nodes.forEach { $0.append(toString: &s) } s += "{{/\(key)}}" case .invertedSection(let key, let nodes): s += "{{^\(key)}}" nodes.forEach { $0.append(toString: &s) } s += "{{/\(key)}}" case .tag(let key): s += "{{\(key)}}" case .unescapedTag(let key): s += "{{{\(key)}}}" case .partial(let key): s += "{{> \(key)}}" } } } public extension Sequence where Iterator.Element == MustacheNode { @inlinable var asMustacheString : String { var s = String() forEach { $0.append(toString: &s) } return s } } // MARK: - Template Reflection public extension MustacheNode { @inlinable var hasKeys: Bool { switch self { case .empty, .text: return false case .section, .invertedSection, .tag, .unescapedTag: return true case .global(let nodes): return nodes.firstIndex(where: { $0.hasKeys }) != nil case .partial: return true } } @usableFromInline internal func addKeys(to set: inout Set<String>) { switch self { case .empty, .text: return case .global(let nodes): nodes.forEach { $0.addKeys(to: &set) } case .section(let key, let nodes), .invertedSection(let key, let nodes): set.insert(key) nodes.forEach { $0.addKeys(to: &set) } case .tag(let key), .unescapedTag(let key): set.insert(key) case .partial: return } } @inlinable var keys : Set<String> { var set = Set<String>() addKeys(to: &set) return set } } public extension Sequence where Element == MustacheNode { @inlinable var keys : Set<String> { var set = Set<String>() forEach { $0.addKeys(to: &set) } return set } } public extension Collection where Element == MustacheNode { @inlinable var keys : Set<String> { var set = Set<String>() forEach { $0.addKeys(to: &set) } return set } }
dc88bde24939a5a3c061243530590a81
23.779904
80
0.587565
false
false
false
false
Pyroh/Fluor
refs/heads/main
Fluor/Controllers/ViewControllers/RunningAppsViewController.swift
mit
1
// // RunningAppsViewController.swift // // Fluor // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // 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 Cocoa class RunningAppsViewController: NSViewController, NSTableViewDelegate { @IBOutlet weak var tableView: NSTableView! @IBOutlet var itemsArrayController: NSArrayController! @objc dynamic var runningAppsArray = [RunningApp]() @objc dynamic var showAll: Bool = AppManager.default.showAllRunningProcesses { didSet { self.reloadData() } } @objc dynamic var searchPredicate: NSPredicate? @objc dynamic var sortDescriptors: [NSSortDescriptor] = [.init(key: "name", ascending: true, selector: #selector(NSString.caseInsensitiveCompare(_:)))] private var tableContentAnimator: TableViewContentAnimator<RunningApp>! override func viewDidLoad() { super.viewDidLoad() self.tableContentAnimator = TableViewContentAnimator(tableView: tableView, arrayController: itemsArrayController) self.tableContentAnimator.performUnanimated { self.reloadData() } self.applyAsObserver() } deinit { NSWorkspace.shared.notificationCenter.removeObserver(self) } /// Called whenever an application is launched by the system or the user. /// /// - parameter notification: The notification. @objc private func appDidLaunch(notification: Notification) { guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication, let id = app.bundleIdentifier ?? app.executableURL?.lastPathComponent, let url = app.bundleURL ?? app.executableURL else { return } let isApp = app.activationPolicy == .regular guard self.showAll || isApp else { return } let behavior = AppManager.default.behaviorForApp(id: id) let item = RunningApp(id: id, url: url, behavior: behavior, pid: app.processIdentifier, isApp: isApp) self.runningAppsArray.append(item) } /// Called whenever an application is terminated by the system or the user. /// /// - parameter notification: The notification. @objc private func appDidTerminate(notification: Notification) { guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication, let item = runningAppsArray.first(where: { $0.pid == app.processIdentifier }), let index = runningAppsArray.firstIndex(of: item) else { return } self.runningAppsArray.remove(at: index) } /// Set `self` as an observer for *launch* and *terminate* notfications. private func applyAsObserver() { NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appDidLaunch(notification:)), name: NSWorkspace.didLaunchApplicationNotification, object: nil) NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appDidTerminate(notification:)), name: NSWorkspace.didTerminateApplicationNotification, object: nil) } /// Load all running applications and populate the table view with corresponding data. private func reloadData() { self.runningAppsArray = self.getRunningApps() } private func getRunningApps() -> [RunningApp] { return NSWorkspace.shared.runningApplications.compactMap { (app) -> RunningApp? in guard let id = app.bundleIdentifier ?? app.executableURL?.lastPathComponent, let url = app.bundleURL ?? app.executableURL else { return nil } let isApp = app.activationPolicy == .regular guard showAll || isApp else { return nil } let behavior = AppManager.default.behaviorForApp(id: id) let pid = app.processIdentifier return RunningApp(id: id, url: url, behavior: behavior, pid: pid, isApp: isApp) } } // MARK: - Table View Delegate func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { false } }
7183b342d66acf4af4021096ed18ac17
45.144144
184
0.700898
false
false
false
false
ccloveswift/CLSCommon
refs/heads/master
Classes/UI/extension_MTLTexture.swift
mit
1
// // UIImage.swift // Today // // Created by Alexey Globchastyy on 15/09/14. // Copyright (c) 2014 Alexey Globchastyy. All rights reserved. // import UIKit import MetalKit import MetalPerformanceShaders public extension MTLTexture { @available(iOS 13.0, *) func e_copyTexture(_ dest: MTLTexture) { guard let device = MTLCreateSystemDefaultDevice() else { return } guard let queue = device.makeCommandQueue() else { return } var from: MTLTexture = self if self.width != dest.width || self.height != dest.height { let scalex: Double = 1.0 * Double(dest.width) / Double(self.width) let scaley: Double = 1.0 * Double(dest.height) / Double(self.height) let scaleTransform: MPSScaleTransform = MPSScaleTransform(scaleX: scalex, scaleY: scaley, translateX: 0, translateY: 0) let imageLanczosScale: MPSImageLanczosScale = MPSImageLanczosScale(device: device) withUnsafePointer(to: scaleTransform) { ptr in imageLanczosScale.scaleTransform = ptr } let descriptor: MTLTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: self.pixelFormat, width: dest.width, height: dest.height, mipmapped: false) let usage = (MTLTextureUsage.shaderRead.rawValue | MTLTextureUsage.shaderWrite.rawValue | MTLTextureUsage.renderTarget.rawValue) descriptor.usage = MTLTextureUsage.init(rawValue: usage) guard let tempDest: MTLTexture = device.makeTexture(descriptor: descriptor) else { return } guard let tempCommandBuffer: MTLCommandBuffer = queue.makeCommandBuffer() else { return } imageLanczosScale.encode(commandBuffer: tempCommandBuffer, sourceTexture: self, destinationTexture: tempDest) tempCommandBuffer.commit() tempCommandBuffer.waitUntilCompleted() from = tempDest } guard let commandBuffer = queue.makeCommandBuffer() else { return } guard let commandEncoder: MTLBlitCommandEncoder = commandBuffer.makeBlitCommandEncoder() else { return } commandEncoder.copy(from: from, to: dest) commandEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() } }
c6929af68e6471e815f5783b13ae114b
46.571429
180
0.676534
false
false
false
false
mikaoj/BSImagePicker
refs/heads/master
Sources/Controller/ImagePickerController+ButtonActions.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2019 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension ImagePickerController { @objc func albumsButtonPressed(_ sender: UIButton) { albumsViewController.albums = albums // Setup presentation controller albumsViewController.transitioningDelegate = dropdownTransitionDelegate albumsViewController.modalPresentationStyle = .custom rotateButtonArrow() present(albumsViewController, animated: true) } @objc func doneButtonPressed(_ sender: UIBarButtonItem) { imagePickerDelegate?.imagePicker(self, didFinishWithAssets: assetStore.assets) if settings.dismiss.enabled { dismiss(animated: true) } } @objc func cancelButtonPressed(_ sender: UIBarButtonItem) { imagePickerDelegate?.imagePicker(self, didCancelWithAssets: assetStore.assets) if settings.dismiss.enabled { dismiss(animated: true) } } func rotateButtonArrow() { UIView.animate(withDuration: 0.3) { [weak self] in guard let imageView = self?.albumButton.imageView else { return } imageView.transform = imageView.transform.rotated(by: .pi) } } }
ce98f2f37c90050ca0b14a56c11756bd
38.728814
86
0.706911
false
false
false
false
nst/JSONTestSuite
refs/heads/master
Sources/JSONLib/Error.swift
mit
2
/* -------------------------------------------------------------------------------------------- * Copyright (c) Kiad Studios, LLC. All rights reserved. * Licensed under the MIT License. See License in the project root for license information. * ------------------------------------------------------------------------------------------ */ /// Represents error information for JSON parsing issues. public final class JsonParserError: Swift.Error { public typealias ErrorInfoDictionary = [String:String] /// The error code used to differentiate between various error states. public let code: Int /// A string that is used to group errors into related error buckets. public let domain: String /// A place to store any custom information that needs to be passed along with the error instance. public let userInfo: ErrorInfoDictionary? /// Initializes a new `Error` instance. public init(code: Int, domain: String, userInfo: ErrorInfoDictionary?) { self.code = code self.domain = domain self.userInfo = userInfo } } /// The standard keys used in `Error` and `userInfo`. public struct ErrorKeys { private init() {} public static let LocalizedDescription = "NSLocalizedDescription" public static let LocalizedFailureReason = "NSLocalizedFailureReason" public static let LocalizedRecoverySuggestion = "NSLocalizedRecoverySuggestion" public static let LocalizedRecoveryOptions = "NSLocalizedRecoveryOptions" public static let RecoveryAttempter = "NSRecoveryAttempter" public static let HelpAnchor = "NSHelpAnchor" public static let StringEncoding = "NSStringEncoding" public static let URL = "NSURL" public static let FilePath = "NSFilePath" } extension JsonParserError: CustomStringConvertible { public var description: String { return "Error code: \(self.code), domain: \(self.domain)\ninfo: \(String(describing: self.userInfo))" } }
39ad8e8070df3e500900c1ace9ad2391
44.104167
109
0.598152
false
false
false
false
csnu17/My-Swift-learning
refs/heads/master
BuildingListsAndNavigation/Landmarks/Landmarks/Models/Data.swift
mit
3
/* See LICENSE folder for this sample’s licensing information. Abstract: Helpers for loading images and data. */ import UIKit import SwiftUI import CoreLocation let landmarkData: [Landmark] = load("landmarkData.json") func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T { let data: Data guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find \(filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load \(filename) from main bundle:\n\(error)") } do { let decoder = JSONDecoder() return try decoder.decode(T.self, from: data) } catch { fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)") } } final class ImageStore { fileprivate typealias _ImageDictionary = [String: [Int: CGImage]] fileprivate var images: _ImageDictionary = [:] fileprivate static var originalSize = 250 fileprivate static var scale = 2 static var shared = ImageStore() func image(name: String, size: Int) -> Image { let index = _guaranteeInitialImage(name: name) let sizedImage = images.values[index][size] ?? _sizeImage(images.values[index][ImageStore.originalSize]!, to: size * ImageStore.scale) images.values[index][size] = sizedImage return Image(sizedImage, scale: Length(ImageStore.scale), label: Text(verbatim: name)) } fileprivate func _guaranteeInitialImage(name: String) -> _ImageDictionary.Index { if let index = images.index(forKey: name) { return index } guard let url = Bundle.main.url(forResource: name, withExtension: "jpg"), let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil), let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else { fatalError("Couldn't load image \(name).jpg from main bundle.") } images[name] = [ImageStore.originalSize: image] return images.index(forKey: name)! } fileprivate func _sizeImage(_ image: CGImage, to size: Int) -> CGImage { guard let colorSpace = image.colorSpace, let context = CGContext( data: nil, width: size, height: size, bitsPerComponent: image.bitsPerComponent, bytesPerRow: image.bytesPerRow, space: colorSpace, bitmapInfo: image.bitmapInfo.rawValue) else { fatalError("Couldn't create graphics context.") } context.interpolationQuality = .high context.draw(image, in: CGRect(x: 0, y: 0, width: size, height: size)) if let sizedImage = context.makeImage() { return sizedImage } else { fatalError("Couldn't resize image.") } } }
d81ffa677e2b6f61e6f53b54db8596e2
31.55914
102
0.598745
false
false
false
false
RyanTech/cannonball-ios
refs/heads/master
Cannonball/AboutViewController.swift
apache-2.0
3
// // Copyright (C) 2014 Twitter, Inc. and other contributors. // // 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 Crashlytics import TwitterKit class AboutViewController: UIViewController { // MARK: References @IBOutlet weak var signOutButton: UIButton! var logoView: UIImageView! // MARK: View Life Cycle override func viewDidLoad() { // Add the logo view to the top (not in the navigation bar title to have it bigger). logoView = UIImageView(frame: CGRectMake(0, 0, 40, 40)) logoView.image = UIImage(named: "Logo")?.imageWithRenderingMode(.AlwaysTemplate) logoView.tintColor = UIColor.cannonballGreenColor() logoView.frame.origin.x = (view.frame.size.width - logoView.frame.size.width) / 2 logoView.frame.origin.y = 8 // Add the logo view to the navigation controller and bring it to the front. navigationController?.view.addSubview(logoView) navigationController?.view.bringSubviewToFront(logoView) // Customize the navigation bar. let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.cannonballGreenColor()] navigationController?.navigationBar.titleTextAttributes = titleDict as [NSObject : AnyObject] navigationController?.navigationBar.tintColor = UIColor.cannonballGreenColor() navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) navigationController?.navigationBar.shadowImage = UIImage() // Log Answers Custom Event. Answers.logCustomEventWithName("Viewed About", customAttributes: nil) } // MARK: IBActions @IBAction func dismiss(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func learnMore(sender: AnyObject) { UIApplication.sharedApplication().openURL(NSURL(string: "http://t.co/cannonball")!) } @IBAction func signOut(sender: AnyObject) { // Remove any Twitter or Digits local sessions for this app. Twitter.sharedInstance().logOut() Digits.sharedInstance().logOut() // Remove user information for any upcoming crashes in Crashlytics. Crashlytics.sharedInstance().setUserIdentifier(nil) Crashlytics.sharedInstance().setUserName(nil) // Log Answers Custom Event. Answers.logCustomEventWithName("Signed Out", customAttributes: nil) // Present the Sign In again. let storyboard = UIStoryboard(name: "Main", bundle: nil) let signInViewController: UIViewController! = storyboard.instantiateViewControllerWithIdentifier("SignInViewController") as! UIViewController presentViewController(signInViewController, animated: true, completion: nil) } }
de8a07936e57e2e70ee9696116a18cee
39.268293
149
0.716233
false
false
false
false
crass45/PoGoApiAppleWatchExample
refs/heads/master
PoGoApiAppleWatchExample/PGoApi/SSConfig.swift
mit
1
// // SSConfig.swift // PGoApi // // Created by Jose Luis on 19/8/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import PGoApi import CoreLocation let NEW_POKEMONS_NOTIFICATION = "NEW_POKEMONS_NOTIFICATION" let UPDATE_LOCATION_NOTIFICATION = "UPDATE_LOCATION_NOTIFICATION" let UPDATE_LOG = "UPDATE_LOG" //var userLocation = CLLocationCoordinate2DMake(34.008064, -118.499052) var userLocation = CLLocationCoordinate2DMake(0, 0) var fechaUltimaComprobacion = NSDate() var textoLog = "" var pokesNotificados:[String] = [] var catchablePokes:[Pogoprotos.Map.Pokemon.MapPokemon] = [] var gimnasios:[Pogoprotos.Map.Fort.FortData] = [] var request = PGoApiRequest() var loginOK = false var user:String? { get{ let settings = NSUserDefaults.standardUserDefaults() return settings.stringForKey("user") } set(newVal){ let settings = NSUserDefaults.standardUserDefaults() settings.setObject(newVal, forKey: "user") settings.synchronize() } } var pass:String? { get{ let settings = NSUserDefaults.standardUserDefaults() return settings.stringForKey("pass") } set(newVal){ let settings = NSUserDefaults.standardUserDefaults() settings.setObject(newVal, forKey: "pass") settings.synchronize() } } var authType:Int? { get{ let settings = NSUserDefaults.standardUserDefaults() return settings.integerForKey("authType") } set(newVal){ let settings = NSUserDefaults.standardUserDefaults() settings.setInteger(newVal!, forKey: "authType") settings.synchronize() } }
43ce45d4861ecbe42e23f53b2cb94109
19.454545
71
0.727619
false
false
false
false
zColdWater/YPCache
refs/heads/master
YPCache/SyncViewController.swift
mit
1
// // SyncViewController.swift // YPCache // // Created by Yongpeng.Zhu on 2016/9/1. // Copyright © 2016年 Yongpeng.Zhu. All rights reserved. // import UIKit class SyncViewController: UIViewController { @IBOutlet weak var alertView: UIView! @IBOutlet weak var alertLabel: UILabel! @IBOutlet weak var startValue: UITextField! @IBOutlet weak var endValue: UITextField! @IBOutlet weak var startKey: UITextField! @IBOutlet weak var endKey: UITextField! @IBOutlet weak var objectCount: UILabel! var cache: YPCache? override func viewDidLoad() { super.viewDidLoad() self.title = "SyncViewController" alertView.alpha = 0 alertLabel.textColor = UIColor.whiteColor() alertLabel.numberOfLines = 0 objectCount.text = "Count:\(cache?.memoryCache.totalCount)" // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Sync Set @IBAction func cacheSetObjects(sender: UIButton) { cache = YPCache(cacheName: "SyncSetObject") guard startValue.text != "" && endValue.text != "" && startKey.text != "" && endKey.text != "" && NSInteger(startValue.text!) != nil && NSInteger(endValue.text!) != nil && NSInteger(startKey.text!) != nil && NSInteger(endKey.text!) != nil else { alert("Value and key must be full in textfield and must be an Int type", isSuccess: false) return } let valueCount = NSInteger(endValue.text!)! - NSInteger(startValue.text!)! let keyCount = NSInteger(endKey.text!)! - NSInteger(startKey.text!)! guard keyCount == valueCount else { alert("Keys count not equal valus count", isSuccess: false) return } var values: [Int] = [] for value in NSInteger(startValue.text!)!...NSInteger(endValue.text!)! { values.append(value) } var keys: [Int] = [] for key in NSInteger(startKey.text!)!...NSInteger(endKey.text!)! { keys.append(key) } // main thread is sync thread for index in 0...valueCount { cache?.setObject(values, forkey: "\(keys[index])", memoryCompletion: { [weak self] (isSuccess) in if self == nil { return } dispatch_async(dispatch_get_main_queue(), { self!.objectCount.text = "\(self!.cache?.memoryCache.totalCount)" }) }, diskComletion: { (isSuccess) in }) } } //Clearn @IBAction func clearnCache(sender: UIButton) { cache?.removeAllObject { [weak self] (isSuccess) in if self == nil { return } dispatch_async(dispatch_get_main_queue(), { if isSuccess { self!.alert("Clearn suceessed", isSuccess: true) self!.objectCount.text = "Count:0" self!.cache = nil return } self!.alert("Clearn failed", isSuccess: false) }) } } // MARK: - AlertView func alert(msg: String, isSuccess: Bool) { alertView.backgroundColor = isSuccess ? UIColor.greenColor() : UIColor.redColor() alertLabel.text = msg alertLabel.sizeToFit() UIView.animateWithDuration(3, animations: { self.alertView.alpha = 1 self.alertView.alpha = 0 }) } }
624c8af2947874a6926166fd62f3c7b9
33.733333
253
0.571429
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/View Controllers/SplitViewControllerDelegate.swift
mit
1
// // SplitViewControllerDelegate.swift // Freetime // // Created by Ryan Nystrom on 6/25/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit // add this shell protocol onto a view controller that should remain part of a tab's root nav VC when splitting out // detail VCs from primary on split VC expansion protocol PrimaryViewController {} final class SplitViewControllerDelegate: UISplitViewControllerDelegate { func splitViewController( _ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController ) -> Bool { if let tab = primaryViewController as? UITabBarController, let primaryNav = tab.selectedViewController as? UINavigationController, let secondaryNav = secondaryViewController as? UINavigationController { // remove any placeholder VCs from the stack primaryNav.viewControllers += secondaryNav.viewControllers.filter { $0.hidesBottomBarWhenPushed = true return ($0 is SplitPlaceholderViewController) == false } } return true } func splitViewController( _ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController ) -> UIViewController? { guard let tab = primaryViewController as? UITabBarController, let primaryNav = tab.selectedViewController as? UINavigationController else { return nil } var detailVCs = [UIViewController]() // for each tab VC that is a nav controller, pluck everything that isn't marked as a primary VC off of // the nav stack. if the nav is the currently selected tab VC, then move all non-primary VCs to for tabVC in tab.viewControllers ?? [] { // they should all be navs, but just in case guard let nav = tabVC as? UINavigationController else { continue } // pop until hitting a VC marked as "primary" while let top = nav.topViewController, top !== nav.viewControllers.first, (top is PrimaryViewController) == false { if nav === primaryNav { detailVCs.insert(top, at: 0) } nav.popViewController(animated: false) } } if detailVCs.count > 0 { // if there are active VCs, push them onto the new nav stack let nav = UINavigationController() nav.setViewControllers(detailVCs, animated: false) return nav } else { // otherwise use a placeholder VC return UINavigationController(rootViewController: SplitPlaceholderViewController()) } } func splitViewController( _ splitViewController: UISplitViewController, showDetail vc: UIViewController, sender: Any? ) -> Bool { guard let tab = splitViewController.viewControllers.first as? UITabBarController else { return false } if splitViewController.isCollapsed { if let nav = vc as? UINavigationController, let first = nav.viewControllers.first { tab.selectedViewController?.show(first, sender: sender) } else { tab.selectedViewController?.show(vc, sender: sender) } } else { splitViewController.viewControllers = [tab, vc] } return true } }
95a0d2fab85d83ae53b5d775c49c8aab
36.705263
115
0.636516
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/NotificationsCenterFilterView.swift
mit
1
import SwiftUI import WMF struct NotificationsCenterFilterItemView: View { @Environment (\.horizontalSizeClass) private var horizontalSizeClass @ObservedObject var itemViewModel: NotificationsCenterFiltersViewModel.ItemViewModel let theme: Theme var body: some View { Group { switch itemViewModel.selectionType { case .checkmark: Button(action: { itemViewModel.toggleSelectionForCheckmarkType() }) { HStack { Text(itemViewModel.title) .foregroundColor(Color(theme.colors.primaryText)) Spacer() if itemViewModel.isSelected { Image(systemName: "checkmark") .font(Font.body.weight(.semibold)) .foregroundColor(Color(theme.colors.link)) } } } case .toggle(let type): HStack { let iconColor = theme.colors.paperBackground let iconBackgroundColor = type.imageBackgroundColorWithTheme(theme) if let iconName = type.imageName { NotificationsCenterIconImage(iconName: iconName, iconColor: Color(iconColor), iconBackgroundColor: Color(iconBackgroundColor), padding: 0) } let customBinding = $itemViewModel.isSelected.didSet { (state) in itemViewModel.toggleSelectionForToggleType() } Toggle(isOn: customBinding) { customLabelForToggle(type: type) } .toggleStyle(SwitchToggleStyle(tint: Color(theme.colors.accent))) } case .toggleAll: Toggle(itemViewModel.title, isOn: $itemViewModel.isSelected.didSet { (state) in itemViewModel.toggleSelectionForAll() }) .foregroundColor(Color(theme.colors.primaryText)) .toggleStyle(SwitchToggleStyle(tint: Color(theme.colors.accent))) } } .padding(.horizontal, horizontalSizeClass == .regular ? (UIFont.preferredFont(forTextStyle: .body).pointSize) : 0) .listRowBackground(Color(theme.colors.paperBackground).edgesIgnoringSafeArea([.all])) } private func customLabelForToggle(type: RemoteNotificationFilterType) -> some View { Group { switch type { case .loginAttempts, // represents both known and unknown devices .loginSuccess: let subtitle = type == .loginAttempts ? WMFLocalizedString("notifications-center-type-title-login-attempts-subtitle", value: "Failed login attempts to your account", comment: "Subtitle of \"Login attempts\" notification type filter toggle. Represents failed logins from both a known and unknown device.") : CommonStrings.notificationsCenterLoginSuccessDescription VStack(alignment: .leading, spacing: 2) { Text(itemViewModel.title) .foregroundColor(Color(theme.colors.primaryText)) .font(.body) Text(subtitle) .foregroundColor(Color(theme.colors.secondaryText)) .font(.footnote) } default: Text(itemViewModel.title) .font(.body) .foregroundColor(Color(theme.colors.primaryText)) } } } } extension Binding { func didSet(execute: @escaping (Value) -> Void) -> Binding { return Binding( get: { self.wrappedValue }, set: { self.wrappedValue = $0 execute($0) } ) } } struct NotificationsCenterFilterView: View { let viewModel: NotificationsCenterFiltersViewModel let doneAction: () -> Void var body: some View { List { ForEach(viewModel.sections) { section in if let title = section.title { let header = Text(title).foregroundColor(Color(viewModel.theme.colors.secondaryText)) if let footer = section.footer { let footer = Text(footer) .foregroundColor(Color(viewModel.theme.colors.secondaryText)) Section(header: header, footer: footer) { ForEach(section.items) { item in NotificationsCenterFilterItemView(itemViewModel: item, theme: viewModel.theme) } } } else { Section(header: header) { ForEach(section.items) { item in NotificationsCenterFilterItemView(itemViewModel: item, theme: viewModel.theme) } } } } else { Section { ForEach(section.items) { item in NotificationsCenterFilterItemView(itemViewModel: item, theme: viewModel.theme) } } } } } .listStyle(GroupedListStyle()) .navigationBarItems( trailing: Button(action: { doneAction() }) { Text(CommonStrings.doneTitle) .fontWeight(Font.Weight.semibold) .foregroundColor(Color(viewModel.theme.colors.primaryText)) } ) .background(Color(viewModel.theme.colors.baseBackground).edgesIgnoringSafeArea(.all)) .navigationBarTitle(Text(WMFLocalizedString("notifications-center-filters-title", value: "Filters", comment: "Navigation bar title text for the filters view presented from notifications center. Allows for filtering by read status and notification type.")), displayMode: .inline) .onAppear(perform: { UITableView.appearance().backgroundColor = UIColor.clear }) .onDisappear(perform: { UITableView.appearance().backgroundColor = UIColor.systemGroupedBackground }) } }
ce1a53478d4848b86e07dae469d4124e
43.025641
320
0.506989
false
false
false
false
Mobilette/Zappy
refs/heads/develop
Zappy/Classes/Modules/Root/RootWireframe.swift
mit
1
// // RootWireframe.swift // Zappy // // Created by Issouf M'sa Benaly on 9/15/15. // Copyright (c) 2015 Mobilette. All rights reserved. // import UIKit class RootWireframe { // MARK: - Presentation func presentRootViewController(fromWindow window: UIWindow) { self.presentMediaPlayViewController(fromWindow: window) } private func presentMediaPlayViewController(fromWindow window: UIWindow) { let presenter = MediaPlayPresenter() let interactor = MediaPlayInteractor() // let networkController = MediaPlayNetworkController() let wireframe = MediaPlayWireframe() // interactor.networkController = networkController interactor.output = presenter presenter.interactor = interactor presenter.wireframe = wireframe wireframe.presenter = presenter wireframe.presentInterface(fromWindow: window) } }
61663d19836986de60784508b64550fe
26.382353
76
0.685285
false
false
false
false
xpurple/LocationDiary
refs/heads/master
RefineData.swift
gpl-3.0
1
// // refineData.swift // LocationDiary // // Created by 1002541 on 2016. 3. 14.. // Copyright © 2016년 1002541. All rights reserved. // import Foundation import CoreData enum VisitFrequency { //TODO // case Never // case AlmostNever // case OnceAMonth // case SeveralTimesAMonth // case OnceAWeek // case SeveralTimesAWeek // case OnceADay // case SeveralTimesADay case Never case FirstTime case LessThanFourTimes case LessThanTenTimes case GreaterThanTenTimes } class RefineData { private var list = [LDVisit]() var latitude: Double = 0.0 var longitude: Double = 0.0 var visitFrequecy: VisitFrequency { get { var frequecy = VisitFrequency.Never switch self.visitCount { case 0: frequecy = .Never case 1: frequecy = .FirstTime case 1..<4: frequecy = .LessThanFourTimes case 4..<10: frequecy = .LessThanTenTimes default: frequecy = .GreaterThanTenTimes } return frequecy } } var visitCount:Int { get { return self.list.count } } private let volume = 1000.0 init (data:LDVisit) { let dataLatitude = data.latitude let dataLongitude = data.longitude latitude = ceil(dataLatitude * volume) longitude = ceil(dataLongitude * volume) addData(data) } func inRegin(data:LDVisit) -> Bool { let dataLatitude = data.latitude let dataLongitude = data.longitude if latitude == ceil(dataLatitude * volume) && longitude == ceil(dataLongitude * volume) { return true } return false } func addData(data:LDVisit) { list.append(data) } func average()->(latitude:Double, longitude:Double, deviation:Double) { let count = list.count var sumLatidue: Double = 0 var sumLongitude: Double = 0 for item in list { sumLatidue += item.latitude sumLongitude += item.longitude } let averageLocationX = sumLatidue / Double(count) let averageLocationY = sumLongitude / Double(count) var varianceSum:Double = 0 for item in list { varianceSum = variance( averageLocationX, x2: item.latitude, y1: averageLocationY, y2: item.longitude ) } return (averageLocationX , averageLocationY, varianceSum / Double(count)) } func variance(x1:Double, x2:Double, y1:Double, y2:Double)->Double { return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) } }
cc00ee5f610cf36029a6432a0b34ed77
23.859649
115
0.556654
false
false
false
false
yoha/Thoughtless
refs/heads/master
Thoughtless/MarkdownHelper.swift
mit
1
// // MarkdownHelper.swift // Thoughtless // // ----- // // Markdown.swift // MarkdownEditor // https://github.com/kuyawa/MarkdownEditor/blob/master/MarkdownEditor/Markdown.swift // // Created by Mac Mini on 3/9/17. // Copyright © 2017 Armonia. All rights reserved. // import Foundation extension String { func trim() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } func removeCarriageReturn() -> String { return self.components(separatedBy: "\r\n").joined(separator: "\n") } func remove(_ pattern: String) -> String { guard self.characters.count > 0 else { return self } if let first = self.range(of: pattern, options: String.CompareOptions.regularExpression, range: nil, locale: nil) { return self.replacingCharacters(in: first, with: "") } return self } func prepend(_ text: String) -> String { guard !text.isEmpty else { return self } return text + self } func append(_ text: String) -> String { if text.isEmpty { return self } return self + text } func enclose(_ fence: (String, String)?) -> String { return (fence?.0 ?? " ") + self + (fence?.1 ?? " ") } func matches(_ pattern: String) -> Bool { guard self.characters.count > 0 else { return false } if let first = self.range(of: pattern, options: .regularExpression, range: nil, locale: nil) { let match = self.substring(with: first) return !match.isEmpty } return false } func matchAndReplace(_ rex: String, _ rep: String, options: NSRegularExpression.Options? = []) -> String { if let regex = try? NSRegularExpression(pattern: rex, options: options!) { let range = NSRange(location: 0, length: self.characters.count) let mutableString = NSMutableString(string: self) _ = regex.replaceMatches(in: mutableString, options: [], range: range, withTemplate: rep) return String(describing: mutableString) } else { print("Regex is not valid") } return self } } struct MarkdownHelper { func parse(_ text: String) -> String { var md = text.removeCarriageReturn() md = cleanHtml(md) md = parseHeaders(md) md = parseBold(md) md = parseItalic(md) md = parseDeleted(md) md = parseImages(md) md = parseLinks(md) md = parseCodeBlock(md) md = parseCodeInline(md) md = parseHorizontalRule(md) md = parseUnorderedListsTypeAsterix(md) md = parseUnorderedListsTypeDash(md) md = parseOrderedListsWithFullStop(md) md = parseOrderedListsWithRightBracket(md) md = parseCheckbox(md) md = parseBlockquotes(md) md = parseYoutubeVideos(md) md = parseParagraphs(md) return md } func cleanHtml(_ md: String) -> String { return md.matchAndReplace("<.*?>", "") } func parseHeaders(_ md: String) -> String { var mx = md mx = mx.matchAndReplace("^###(.*)?", "<h3>$1</h3>", options: [.anchorsMatchLines]) mx = mx.matchAndReplace("^##(.*)?", "<h2>$1</h2>", options: [.anchorsMatchLines]) mx = mx.matchAndReplace("^#(.*)?", "<h1>$1</h1>", options: [.anchorsMatchLines]) return mx } func parseBold(_ md: String) -> String { var mx = md mx = mx.matchAndReplace("\\*\\*(.*?)\\*\\*", "<b>$1</b>") mx = mx.matchAndReplace("\\_\\_(.*?)\\_\\_", "<b>$1</b>") return mx } func parseItalic(_ md: String) -> String { var mx = md mx = mx.matchAndReplace("\\*(.*?)\\*", "<i>$1</i>") mx = mx.matchAndReplace("\\_(.*?)\\_", "<i>$1</i>") return mx } func parseDeleted(_ md: String) -> String { return md.matchAndReplace("~~(.*?)~~", "<s>$1</s>") } func parseImages(_ md: String) -> String { var mx = md mx = mx.matchAndReplace("!\\[(\\d+)x(\\d+)\\]\\((.*?)\\)", "<img src=\"$3\" width=\"$1\" height=\"$2\" />") mx = mx.matchAndReplace("!\\[(.*?)\\]\\((.*?)\\)", "<img alt=\"$1\" src=\"$2\" />") return mx } func parseLinks(_ md: String) -> String { var mx = md mx = mx.matchAndReplace("\\[(.*?)\\]\\((.*?)\\)", "<a href=\"$2\" style=\"color: #0088cc\">$1</a>") mx = mx.matchAndReplace("\\[http(.*?)\\]", "<a href=\"http$1\" style=\"color: #0088cc\">http$1</a>") mx = mx.matchAndReplace("(^|\\s)http(.*?)(\\s|\\.\\s|\\.$|,|$)", "$1<a href=\"http$2\" style=\"color: #0088cc\">http$2</a>$3 ", options: [.anchorsMatchLines]) return mx } func parseCodeBlock(_ md: String) -> String { return md.matchAndReplace("```(.*?)```", "<pre style=\"padding: 12px; background-color:#43423F;\">$1</pre>", options: [.dotMatchesLineSeparators]) // return parseBlock(md, format: "^\\s{4}", blockEnclose: ("<pre>", "</pre>")) } func parseCodeInline(_ md: String) -> String { return md.matchAndReplace("`(.*?)`", "<code style=\"padding: 12px; background-color:#43423F;\">$1</code>") } func parseHorizontalRule(_ md: String) -> String { return md.matchAndReplace("---", "<hr>") } func parseUnorderedListsTypeAsterix(_ md: String) -> String { return parseBlock(md, format: "^\\*", blockEnclose: ("<ul>", "</ul>"), lineEnclose: ("<li>", "</li>")) } func parseUnorderedListsTypeDash(_ md: String) -> String { return parseBlock(md, format: "^\\-\\s(?!\\[)", blockEnclose: ("<ul>", "</ul>"), lineEnclose: ("<li>", "</li>")) } func parseOrderedListsWithFullStop(_ md: String) -> String { return parseBlock(md, format: "^\\d+[\\.|-]", blockEnclose: ("<ol style=\"margin-left: 25px\">", "</ol>"), lineEnclose: ("<li>", "</li>")) } func parseOrderedListsWithRightBracket(_ md: String) -> String { return parseBlock(md, format: "^\\d+[\\)|-]", blockEnclose: ("<ol style=\"margin-left: 25px\">", "</ol>"), lineEnclose: ("<li>", "</li>")) } func parseCheckbox(_ md: String) -> String { return parseBlock(md, format: "^\\-\\s\\[\\s\\]", blockEnclose: ("<ul style=\"list-style: none;\">", "</ul>"), lineEnclose: ("<li><input type=\"checkbox\" style=\"zoom:2; margin-right: 8px; background-color: #43423F\">", "</li>")) } func parseBlockquotes(_ md: String) -> String { var mx = md mx = parseBlock(mx, format: "^>", blockEnclose: ("<blockquote style=\"color: #A7A2A9; border-left: 5px solid #A7A2A9; padding-left: 19px\"><b>", "</b></blockquote>")) mx = parseBlock(mx, format: "^:", blockEnclose: ("<blockquote style=\"color: #A7A2A9; border-left: 5px solid #A7A2A9; padding-left: 19px\"><b>", "</b></blockquote>")) return mx } func parseYoutubeVideos(_ md: String) -> String { return md.matchAndReplace("\\[youtube (.*?)\\]", "<p><a href=\"http://www.youtube.com/watch?v=$1\" target=\"_blank\"><img src=\"http://img.youtube.com/vi/$1/0.jpg\" alt=\"Youtube video\" width=\"240\" height=\"180\" /></a></p>") } func parseParagraphs(_ md: String) -> String { return md.matchAndReplace("\n\n([^\n]+)\n\n", "\n\n<p>$1</p>\n\n", options: [.dotMatchesLineSeparators]) } func parseBlock(_ md: String, format: String, blockEnclose: (String, String), lineEnclose: (String, String)? = nil) -> String { let lines = md.components(separatedBy: .newlines) var result = [String]() var isBlock = false var isFirst = true for line in lines { var text = line if text.matches(format) { isBlock = true if isFirst { result.append(blockEnclose.0); isFirst = false } text = text.remove(format) text = text.trim().enclose(lineEnclose) } else if isBlock { isBlock = false isFirst = true text = text.append(blockEnclose.1+"\n") } result.append(text) } if isBlock { result.append(blockEnclose.1) } // close open blocks let mx = result.joined(separator: "\n") return mx } }
d932d5500acef3f2fbd529d12f724201
37.047826
238
0.521426
false
false
false
false
ZackKingS/Tasks
refs/heads/master
Pods/SwiftTheme/Source/UIKit+Theme.swift
apache-2.0
1
// // UIKit+Theme.swift // SwiftTheme // // Created by Gesen on 16/1/22. // Copyright © 2016年 Gesen. All rights reserved. // import UIKit extension UIView { public var theme_alpha: ThemeCGFloatPicker? { get { return getThemePicker(self, "setAlpha:") as? ThemeCGFloatPicker } set { setThemePicker(self, "setAlpha:", newValue) } } public var theme_backgroundColor: ThemeColorPicker? { get { return getThemePicker(self, "setBackgroundColor:") as? ThemeColorPicker } set { setThemePicker(self, "setBackgroundColor:", newValue) } } public var theme_tintColor: ThemeColorPicker? { get { return getThemePicker(self, "setTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setTintColor:", newValue) } } } extension UIApplication { public func theme_setStatusBarStyle(_ picker: ThemeStatusBarStylePicker, animated: Bool) { picker.animated = animated setThemePicker(self, "setStatusBarStyle:animated:", picker) } } extension UIBarButtonItem { public var theme_tintColor: ThemeColorPicker? { get { return getThemePicker(self, "setTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setTintColor:", newValue) } } } extension UILabel { public var theme_font: ThemeFontPicker? { get { return getThemePicker(self, "setFont:") as? ThemeFontPicker } set { setThemePicker(self, "setFont:", newValue) } } public var theme_textColor: ThemeColorPicker? { get { return getThemePicker(self, "setTextColor:") as? ThemeColorPicker } set { setThemePicker(self, "setTextColor:", newValue) } } public var theme_highlightedTextColor: ThemeColorPicker? { get { return getThemePicker(self, "setHighlightedTextColor:") as? ThemeColorPicker } set { setThemePicker(self, "setHighlightedTextColor:", newValue) } } public var theme_shadowColor: ThemeColorPicker? { get { return getThemePicker(self, "setShadowColor:") as? ThemeColorPicker } set { setThemePicker(self, "setShadowColor:", newValue) } } } extension UINavigationBar { public var theme_barStyle: ThemeBarStylePicker? { get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker } set { setThemePicker(self, "setBarStyle:", newValue) } } public var theme_barTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setBarTintColor:", newValue) } } public var theme_titleTextAttributes: ThemeDictionaryPicker? { get { return getThemePicker(self, "setTitleTextAttributes:") as? ThemeDictionaryPicker } set { setThemePicker(self, "setTitleTextAttributes:", newValue) } } } extension UITabBar { public var theme_barStyle: ThemeBarStylePicker? { get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker } set { setThemePicker(self, "setBarStyle:", newValue) } } public var theme_barTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setBarTintColor:", newValue) } } } extension UITableView { public var theme_separatorColor: ThemeColorPicker? { get { return getThemePicker(self, "setSeparatorColor:") as? ThemeColorPicker } set { setThemePicker(self, "setSeparatorColor:", newValue) } } } extension UITextField { public var theme_font: ThemeFontPicker? { get { return getThemePicker(self, "setFont:") as? ThemeFontPicker } set { setThemePicker(self, "setFont:", newValue) } } public var theme_keyboardAppearance: ThemeKeyboardAppearancePicker? { get { return getThemePicker(self, "setKeyboardAppearance:") as? ThemeKeyboardAppearancePicker } set { setThemePicker(self, "setKeyboardAppearance:", newValue) } } public var theme_textColor: ThemeColorPicker? { get { return getThemePicker(self, "setTextColor:") as? ThemeColorPicker } set { setThemePicker(self, "setTextColor:", newValue) } } } extension UITextView { public var theme_font: ThemeFontPicker? { get { return getThemePicker(self, "setFont:") as? ThemeFontPicker } set { setThemePicker(self, "setFont:", newValue) } } public var theme_textColor: ThemeColorPicker? { get { return getThemePicker(self, "setTextColor:") as? ThemeColorPicker } set { setThemePicker(self, "setTextColor:", newValue) } } } extension UIToolbar { public var theme_barStyle: ThemeBarStylePicker? { get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker } set { setThemePicker(self, "setBarStyle:", newValue) } } public var theme_barTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setBarTintColor:", newValue) } } } extension UISwitch { public var theme_onTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setOnTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setOnTintColor:", newValue) } } public var theme_thumbTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setThumbTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setThumbTintColor:", newValue) } } } extension UISlider { public var theme_thumbTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setThumbTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setThumbTintColor:", newValue) } } public var theme_minimumTrackTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setMinimumTrackTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setMinimumTrackTintColor:", newValue) } } public var theme_maximumTrackTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setMaximumTrackTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setMaximumTrackTintColor:", newValue) } } } extension UISearchBar { public var theme_barStyle: ThemeBarStylePicker? { get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker } set { setThemePicker(self, "setBarStyle:", newValue) } } public var theme_barTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setBarTintColor:", newValue) } } } extension UIProgressView { public var theme_progressTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setProgressTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setProgressTintColor:", newValue) } } public var theme_trackTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setTrackTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setTrackTintColor:", newValue) } } } extension UIPageControl { public var theme_pageIndicatorTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setPageIndicatorTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setPageIndicatorTintColor:", newValue) } } public var theme_currentPageIndicatorTintColor: ThemeColorPicker? { get { return getThemePicker(self, "setCurrentPageIndicatorTintColor:") as? ThemeColorPicker } set { setThemePicker(self, "setCurrentPageIndicatorTintColor:", newValue) } } } extension UIImageView { public var theme_image: ThemeImagePicker? { get { return getThemePicker(self, "setImage:") as? ThemeImagePicker } set { setThemePicker(self, "setImage:", newValue) } } } extension UIActivityIndicatorView { public var theme_activityIndicatorViewStyle: ThemeActivityIndicatorViewStylePicker? { get { return getThemePicker(self, "setActivityIndicatorViewStyle:") as? ThemeActivityIndicatorViewStylePicker } set { setThemePicker(self, "setActivityIndicatorViewStyle:", newValue) } } } extension UIButton { public func theme_setImage(_ picker: ThemeImagePicker?, forState state: UIControlState) { let statePicker = makeStatePicker(self, "setImage:forState:", picker, state) setThemePicker(self, "setImage:forState:", statePicker) } public func theme_setBackgroundImage(_ picker: ThemeImagePicker?, forState state: UIControlState) { let statePicker = makeStatePicker(self, "setBackgroundImage:forState:", picker, state) setThemePicker(self, "setBackgroundImage:forState:", statePicker) } public func theme_setTitleColor(_ picker: ThemeColorPicker?, forState state: UIControlState) { let statePicker = makeStatePicker(self, "setTitleColor:forState:", picker, state) setThemePicker(self, "setTitleColor:forState:", statePicker) } } extension CALayer { public var theme_backgroundColor: ThemeCGColorPicker? { get { return getThemePicker(self, "setBackgroundColor:") as? ThemeCGColorPicker} set { setThemePicker(self, "setBackgroundColor:", newValue) } } public var theme_borderWidth: ThemeCGFloatPicker? { get { return getThemePicker(self, "setBorderWidth:") as? ThemeCGFloatPicker } set { setThemePicker(self, "setBorderWidth:", newValue) } } public var theme_borderColor: ThemeCGColorPicker? { get { return getThemePicker(self, "setBorderColor:") as? ThemeCGColorPicker } set { setThemePicker(self, "setBorderColor:", newValue) } } public var theme_shadowColor: ThemeCGColorPicker? { get { return getThemePicker(self, "setShadowColor:") as? ThemeCGColorPicker } set { setThemePicker(self, "setShadowColor:", newValue) } } } private func getThemePicker( _ object : NSObject, _ selector : String ) -> ThemePicker? { return object.themePickers[selector] } private func setThemePicker( _ object : NSObject, _ selector : String, _ picker : ThemePicker? ) { object.themePickers[selector] = picker object.performThemePicker(selector: selector, picker: picker) } private func makeStatePicker( _ object : NSObject, _ selector : String, _ picker : ThemePicker?, _ state : UIControlState ) -> ThemePicker? { var picker = picker if let statePicker = object.themePickers[selector] as? ThemeStatePicker { picker = statePicker.setPicker(picker, forState: state) } else { picker = ThemeStatePicker(picker: picker, withState: state) } return picker }
05e9f6cbbc7e13c3de393ad3a1af9e21
39.014925
119
0.696382
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
Examples/iOS/AnalogSynthX/AnalogSynthX/SynthVC+UIHelpers.swift
mit
1
// // SynthViewController+UIHelpers.swift // AnalogSynthX // // Created by Matthew Fecher on 1/15/16. // Copyright © 2016 AudioKit. All rights reserved. // import UIKit extension SynthViewController { //***************************************************************** // MARK: - Synth UI Helpers //***************************************************************** override func prefersStatusBarHidden() -> Bool { return true } func openURL(url: String) { guard let url = NSURL(string: url) else { return } UIApplication.sharedApplication().openURL(url) } func cutoffFreqFromValue(value: Double) -> Double { // Logarithmic scale: knobvalue to frequency let scaledValue = Double.scaleRangeLog(value, rangeMin: 30, rangeMax: 7000) return scaledValue * 4 } //***************************************************************** // MARK: - SegmentViews //***************************************************************** func createWaveFormSegmentViews() { setupOscSegmentView(8, y: 75.0, width: 195, height: 46.0, tag: ControlTag.Vco1Waveform.rawValue, type: 0) setupOscSegmentView(212, y: 75.0, width: 226, height: 46.0, tag: ControlTag.Vco2Waveform.rawValue, type: 0) setupOscSegmentView(10, y: 377, width: 255, height: 46.0, tag: ControlTag.LfoWaveform.rawValue, type: 1) } func setupOscSegmentView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, tag: Int, type: Int) { let segmentFrame = CGRect(x: x, y: y, width: width, height: height) let segmentView = WaveformSegmentedView(frame: segmentFrame) segmentView.setOscColors() if type == 0 { segmentView.addOscWaveforms() } else { segmentView.addLfoWaveforms() } segmentView.delegate = self segmentView.tag = tag // Set segment with index 0 as selected by default segmentView.selectSegmentAtIndex(0) self.view.addSubview(segmentView) } }
f7893c7fb21bde7746672af1336d8c6f
32.063492
115
0.553794
false
false
false
false
brentsimmons/Frontier
refs/heads/master
BeforeTheRename/UserTalk/UserTalk/Node/TryNode.swift
gpl-2.0
1
// // TryNode.swift // UserTalk // // Created by Brent Simmons on 5/7/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation import FrontierData // try // TryNode // some.thing() // BlockNode // else // BlockNode // other.thing() final class TryNode: CodeTreeNode { let operation = .bundleOp let textPosition: TextPosition let blockNode: BlockNode let elseNode: BlockNode? init(_ textPosition: TextPosition, _ blockNode: BlockNode, _ elseNode: BlockNode?) { self.textPosition = textPosition self.blockNode = blockNode self.elseNode = elseNode } func evaluate(_ stack: Stack, _ breakOperation: inout CodeTreeOperation) throws -> Value { do { stack.push(self) defer { stack.pop() } return try blockNode.evaluate(stack, &tempBreakOperation) } catch { } // There was an error. do { stack.push(self) defer { stack.pop() } breakOperation = .noOp // Possible that it was set above, so it should be reset try return blockNode.evaluate(stack, breakOperation) } catch { throw error } } }
fe5436bea7c99ec6453c3d63aa15c968
18.854545
91
0.679487
false
false
false
false
CrowdShelf/ios
refs/heads/master
CrowdShelf/CrowdShelfTests/ColorPalette.swift
mit
1
// // ColorPalette.swift // CrowdShelf // // Created by Maren Parnas Gulnes on 30.10.15. // Copyright © 2015 Øyvind Grimnes. All rights reserved. // import Foundation import UIKit extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } } class ColorPalette: UIColor{ static let primaryColor = UIColor(netHex:0x03A9F4) static let darkPrimaryColor = UIColor(netHex:0x0288D1) static let lightPrimaryColor = UIColor(netHex:0xB3E5FC) static let textColor = UIColor(netHex:0xFFFFFF) static let secondTextColor = UIColor(netHex:0x727272) static let dividerColor = UIColor(netHex:0xB6B6B6) static let primaryTextColor = UIColor(netHex:0x212121) static let dangerColor = UIColor(netHex:0xC7262C) static let randomColors = [ UIColor(netHex: 0xf16364), UIColor(netHex: 0xf58559), UIColor(netHex: 0xe4c62e), UIColor(netHex: 0x67bf74), UIColor(netHex: 0x59a2be), UIColor(netHex: 0x2093cd), UIColor(netHex: 0xad62a7) ] class func colorForString(string: String) -> UIColor { let hashValue = string.hashValue let index = abs( hashValue % self.randomColors.count ) return randomColors[index] } }
9895a49d3dbe1bd5b3a3007b343bdddc
33.096154
116
0.63149
false
false
false
false
netguru/inbbbox-ios
refs/heads/develop
Unit Tests/ManagedBucketsRequesterSpec.swift
gpl-3.0
1
// // ManagedBucketsRequesterSpec.swift // Inbbbox // // Copyright © 2017 Netguru Sp. z o.o. All rights reserved. // import Foundation import Quick import Nimble import CoreData import PromiseKit @testable import Inbbbox class ManagedBucketsRequesterSpec: QuickSpec { override func spec() { var sut: ManagedBucketsRequester! var inMemoryManagedObjectContext: NSManagedObjectContext! beforeEach { inMemoryManagedObjectContext = setUpInMemoryManagedObjectContext() sut = ManagedBucketsRequester(managedObjectContext: inMemoryManagedObjectContext) } afterEach { inMemoryManagedObjectContext = nil sut = nil } it("should have managed object context") { expect(sut.managedObjectContext).toNot(beNil()) } describe("create buckets") { var createdBucket: ManagedBucket? context("bucket should be created properly") { afterEach { createdBucket = nil } it("with description") { let description = NSAttributedString(string: "fixture") _ = firstly { sut.addBucket("fixture", description: description) }.then { bucket in createdBucket = bucket as? ManagedBucket } expect(createdBucket).toEventuallyNot(beNil()) expect(createdBucket!.name).toEventually(equal("fixture")) expect(createdBucket!.attributedDescription!).toEventually(equal(description)) } it("without description") { _ = firstly { sut.addBucket("fixture", description: nil) }.then { bucket in createdBucket = bucket as? ManagedBucket } expect(createdBucket).toEventuallyNot(beNil()) expect(createdBucket!.name).toEventually(equal("fixture")) expect(createdBucket!.attributedDescription).toEventually(beNil()) } } } describe("shots handling") { var bucket: ManagedBucket! var shot: ManagedShot! beforeEach() { let managedObjectsProvider = ManagedObjectsProvider(managedObjectContext: inMemoryManagedObjectContext) bucket = managedObjectsProvider.managedBucket(Bucket.fixtureBucket()) shot = managedObjectsProvider.managedShot(Shot.fixtureShot()) } afterEach { bucket = nil shot = nil } context("adding shots") { it("adding one shot") { _ = sut.addShot(shot, toBucket: bucket) expect(bucket.shots?.count).toEventuallyNot(equal(0)) } it("adding few different shots") { let managedObjectsProvider = ManagedObjectsProvider(managedObjectContext: inMemoryManagedObjectContext) let shot2 = managedObjectsProvider.managedShot(Shot.fixtureShotWithIdentifier("fixture.id.2")) let shot3 = managedObjectsProvider.managedShot(Shot.fixtureShotWithIdentifier("fixture.id.3")) _ = sut.addShot(shot, toBucket: bucket) _ = sut.addShot(shot2, toBucket: bucket) _ = sut.addShot(shot3, toBucket: bucket) expect(bucket.shots?.count).toEventually(equal(3)) } it("adding few times the same shots") { _ = sut.addShot(shot, toBucket: bucket) _ = sut.addShot(shot, toBucket: bucket) _ = sut.addShot(shot, toBucket: bucket) expect(bucket.shots?.count).toEventually(equal(1)) expect(bucket.shots?.count).toEventuallyNot(equal(3)) } } context("removing shots") { it("removing only shot") { bucket.shots = [shot] _ = sut.removeShot(shot, fromBucket: bucket) expect(bucket.shots?.count).toEventually(equal(0)) } it("removing few shots") { let managedObjectsProvider = ManagedObjectsProvider(managedObjectContext: inMemoryManagedObjectContext) let shot2 = managedObjectsProvider.managedShot(Shot.fixtureShotWithIdentifier("fixture.id.2")) let shot3 = managedObjectsProvider.managedShot(Shot.fixtureShotWithIdentifier("fixture.id.3")) bucket.shots = [shot, shot2, shot3] _ = sut.removeShot(shot, fromBucket: bucket) _ = sut.removeShot(shot2, fromBucket: bucket) expect(bucket.shots?.count).toEventually(equal(1)) } } } } }
29c89a4bdffe8ae51e6107ca38a287e2
37.834532
123
0.515191
false
false
false
false
mindbody/Conduit
refs/heads/main
Sources/Conduit/Auth/Models/DataConvertible.swift
apache-2.0
1
// // DataConvertible.swift // Conduit // // Created by John Hammerlund on 8/17/17. // Copyright © 2017 MINDBODY. All rights reserved. // import Foundation /// A type that can be serialized and deserialized with arbitrary encoding public protocol DataConvertible { /// Serializes the structure with arbitrary encoding func serialized() throws -> Data /// Deserializes the structure with encoding defined by `serialized()` /// - Parameters: /// - serializedData: The data to deserialize init(serializedData: Data) throws } public enum DataConversionError: Error { case invalidArchive } extension DataConvertible where Self: Encodable { public func serialized() throws -> Data { let encoder = JSONEncoder() return try encoder.encode(self) } } extension DataConvertible where Self: Decodable { public init(serializedData: Data) throws { let decoder = JSONDecoder() self = try decoder.decode(Self.self, from: serializedData) } } extension DataConvertible where Self: NSCoding { public func serialized() throws -> Data { return NSKeyedArchiver.archivedData(withRootObject: self) } public init(serializedData: Data) throws { guard let deserialized = NSKeyedUnarchiver.unarchiveObject(with: serializedData) as? Self else { throw DataConversionError.invalidArchive } self = deserialized } }
e3aad157e307ead7fbef9f322965c170
24.696429
104
0.693537
false
false
false
false
xzhangyueqian/JinJiangZhiChuang
refs/heads/master
JJZC/JJZC/Classes/Module/Main/Controller/SLTableViewController.swift
apache-2.0
1
// // SLTableViewController.swift // JJZC // // Created by YueQian.Zhang on 6/14/16. // Copyright © 2016 TianXing. All rights reserved. // import UIKit class SLTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.clipsToBounds = false // 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 viewWillAppear(animated: Bool) { super.viewWillAppear(animated) view.backgroundColor = .randomColor() } 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. } */ }
b521fdfb8917f991e7600a94bc45c4cc
32.920792
157
0.683304
false
false
false
false
belkevich/DTModelStorage
refs/heads/master
DTModelStorage/Core/BaseStorage.swift
mit
1
// // BaseStorage.swift // DTModelStorageTests // // Created by Denys Telezhkin on 06.07.15. // Copyright (c) 2015 Denys Telezhkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit /// Suggested supplementary kind for UITableView header public let DTTableViewElementSectionHeader = "DTTableViewElementSectionHeader" /// Suggested supplementary kind for UITableView footer public let DTTableViewElementSectionFooter = "DTTableViewElementSectionFooter" /// Base class for MemoryStorage and CoreDataStorage public class BaseStorage : NSObject { /// Supplementary kind for header in current storage public var supplementaryHeaderKind : String? /// Supplementary kind for footer in current storage public var supplementaryFooterKind : String? /// Current update internal var currentUpdate: StorageUpdate? /// Delegate for storage updates public weak var delegate : StorageUpdating? } extension BaseStorage { func startUpdate(){ self.currentUpdate = StorageUpdate() } func finishUpdate() { defer { self.currentUpdate = nil } if self.currentUpdate != nil { if self.currentUpdate!.isEmpty() { return } self.delegate?.storageDidPerformUpdate(self.currentUpdate!) } } /// This method will configure storage for using with UITableView public func configureForTableViewUsage() { self.supplementaryHeaderKind = DTTableViewElementSectionHeader self.supplementaryFooterKind = DTTableViewElementSectionFooter } /// This method will configure storage for using with UICollectionViewFlowLayout public func configureForCollectionViewFlowLayoutUsage() { self.supplementaryHeaderKind = UICollectionElementKindSectionHeader self.supplementaryFooterKind = UICollectionElementKindSectionFooter } }
a54615cbd9231663be6a32c590135620
35.670732
84
0.7332
false
false
false
false
reza-ryte-club/firefox-ios
refs/heads/autocomplete-highlight
Utils/Extensions/NSURLExtensions.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 UIKit private struct ETLDEntry: CustomStringConvertible { let entry: String var isNormal: Bool { return isWild || !isException } var isWild: Bool = false var isException: Bool = false init(entry: String) { self.entry = entry self.isWild = entry.hasPrefix("*") self.isException = entry.hasPrefix("!") } private var description: String { return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }" } } private typealias TLDEntryMap = [String:ETLDEntry] private func loadEntriesFromDisk() -> TLDEntryMap? { if let data = NSString.contentsOfFileWithResourceName("effective_tld_names", ofType: "dat", fromBundle: NSBundle(identifier: "org.mozilla.Shared")!, encoding: NSUTF8StringEncoding, error: nil) { let lines = data.componentsSeparatedByString("\n") let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" } var entries = TLDEntryMap() for line in trimmedLines { let entry = ETLDEntry(entry: line) let key: String if entry.isWild { // Trim off the '*.' part of the line key = line.substringFromIndex(line.startIndex.advancedBy(2)) } else if entry.isException { // Trim off the '!' part of the line key = line.substringFromIndex(line.startIndex.advancedBy(1)) } else { key = line } entries[key] = entry } return entries } return nil } private var etldEntries: TLDEntryMap? = { return loadEntriesFromDisk() }() extension NSURL { public func withQueryParams(params: [NSURLQueryItem]) -> NSURL { let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)! var items = (components.queryItems ?? []) for param in params { items.append(param) } components.queryItems = items return components.URL! } public func withQueryParam(name: String, value: String) -> NSURL { let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)! let item = NSURLQueryItem(name: name, value: value) components.queryItems = (components.queryItems ?? []) + [item] return components.URL! } public func getQuery() -> [String: String] { var results = [String: String]() let keyValues = self.query?.componentsSeparatedByString("&") if keyValues?.count > 0 { for pair in keyValues! { let kv = pair.componentsSeparatedByString("=") if kv.count > 1 { results[kv[0]] = kv[1] } } } return results } public var hostPort: String? { if let host = self.host { if let port = self.port?.intValue { return "\(host):\(port)" } return host } return nil } public func normalizedHostAndPath() -> String? { if let normalizedHost = self.normalizedHost() { return normalizedHost + (self.path ?? "/") } return nil } public func absoluteDisplayString() -> String? { var urlString = self.absoluteString // For http URLs, get rid of the trailing slash if the path is empty or '/' if (self.scheme == "http" || self.scheme == "https") && (self.path == "/" || self.path == nil) && urlString.endsWith("/") { urlString = urlString.substringToIndex(urlString.endIndex.advancedBy(-1)) } // If it's basic http, strip out the string but leave anything else in if urlString.hasPrefix("http://") ?? false { return urlString.substringFromIndex(urlString.startIndex.advancedBy(7)) } else { return urlString } } /** Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc). :returns: The base domain string for the given host name. */ public func baseDomain() -> String? { if let host = self.host { // If this is just a hostname and not a FQDN, use the entire hostname. if !host.contains(".") { return host } return publicSuffixFromHost(host, withAdditionalParts: 1) } else { return nil } } /** * Returns just the domain, but with the same scheme, and a trailing '/'. * * E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/ * * Any failure? Return this URL. */ public func domainURL() -> NSURL { if let normalized = self.normalizedHost() { return NSURL(scheme: self.scheme, host: normalized, path: "/") ?? self } return self } public func normalizedHost() -> String? { if var host = self.host { if let range = host.rangeOfString("^(www|mobile|m)\\.", options: .RegularExpressionSearch) { host.replaceRange(range, with: "") } return host } return nil } /** Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/. For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk. :returns: The public suffix for within the given hostname. */ public func publicSuffix() -> String? { if let host = self.host { return publicSuffixFromHost(host, withAdditionalParts: 0) } else { return nil } } } //MARK: Private Helpers private extension NSURL { private func publicSuffixFromHost( host: String, withAdditionalParts additionalPartCount: Int) -> String? { if host.isEmpty { return nil } // Check edge case where the host is either a single or double '.'. if host.isEmpty || NSString(string: host).lastPathComponent == "." { return "" } /** * The following algorithm breaks apart the domain and checks each sub domain against the effective TLD * entries from the effective_tld_names.dat file. It works like this: * * Example Domain: test.bbc.co.uk * TLD Entry: bbc * * 1. Start off by checking the current domain (test.bbc.co.uk) * 2. Also store the domain after the next dot (bbc.co.uk) * 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks: * i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches * since it satisfies the wildcard requirement. * ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then * currentDomain is a valid TLD * iii. If the entry we matched is an exception case, then the base domain is the part after the next dot * * On the next run through the loop, we set the new domain to check as the part after the next dot, * update the next dot reference to be the string after the new next dot, and check the TLD entries again. * If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the * top domain level so we use it by default. */ let tokens = host.componentsSeparatedByString(".") let tokenCount = tokens.count var suffix: String? var previousDomain: String? = nil var currentDomain: String = host for offset in 0..<tokenCount { // Store the offset for use outside of this scope so we can add additional parts if needed let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joinWithSeparator(".") : nil if let entry = etldEntries?[currentDomain] { if entry.isWild && (previousDomain != nil) { suffix = previousDomain break; } else if entry.isNormal || (nextDot == nil) { suffix = currentDomain break; } else if entry.isException { suffix = nextDot break; } } previousDomain = currentDomain if let nextDot = nextDot { currentDomain = nextDot } else { break } } var baseDomain: String? if additionalPartCount > 0 { if let suffix = suffix { // Take out the public suffixed and add in the additional parts we want. let literalFromEnd: NSStringCompareOptions = [NSStringCompareOptions.LiteralSearch, // Match the string exactly. NSStringCompareOptions.BackwardsSearch, // Search from the end. NSStringCompareOptions.AnchoredSearch] // Stick to the end. let suffixlessHost = host.stringByReplacingOccurrencesOfString(suffix, withString: "", options: literalFromEnd, range: nil) let suffixlessTokens = suffixlessHost.componentsSeparatedByString(".").filter { $0 != "" } let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount) let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count] let partsString = additionalParts.joinWithSeparator(".") baseDomain = [partsString, suffix].joinWithSeparator(".") } else { return nil } } else { baseDomain = suffix } return baseDomain } }
d33180345373044f90ebce08fa6d8b73
37.895131
198
0.584112
false
false
false
false
dduan/swift
refs/heads/master
test/Constraints/default_literals.swift
apache-2.0
2
// RUN: %target-parse-verify-swift func acceptInt(_ : inout Int) {} func acceptDouble(_ : inout Double) {} var i1 = 1 acceptInt(&i1) var i2 = 1 + 2.0 + 1 acceptDouble(&i2) func ternary<T>(cond: Bool, @autoclosure _ ifTrue: () -> T, @autoclosure _ ifFalse: () -> T) -> T {} ternary(false, 1, 2.5) ternary(false, 2.5, 1) // <rdar://problem/18447543> ternary(false, 1, 2 as Int32) ternary(false, 1, 2 as Float) func genericFloatingLiteral<T : FloatLiteralConvertible>(x: T) { var _ : T = 2.5 } var d = 3.5 genericFloatingLiteral(d) extension UInt32 { func asChar() -> UnicodeScalar { return UnicodeScalar(self) } } var ch = UInt32(65).asChar() // <rdar://problem/14634379> extension Int { func call0() {} typealias Signature = (a: String, b: String) func call(x: Signature) {} } 3.call((a: "foo", b: "bar")) var (div, mod) = (9 / 4, 9 % 4)
2a2f0a34ef7b071516efea82b5bcecc8
19.25
64
0.611672
false
false
false
false
Erudika/para-client-ios
refs/heads/master
Tests/ParaClientTests/ParaClientTests.swift
apache-2.0
1
// // ParaClientTests.swift // ParaClientTests // // Created by Alex on 5.04.16 г.. // Copyright © 2021 г. Erudika. All rights reserved. // import XCTest import ParaClient import SwiftyJSON import Alamofire @testable import ParaClient class ParaClientTests: XCTestCase { private static var c1: ParaClient? private static var c2: ParaClient? private let catsType = "cat" private let dogsType = "dog" private let APP_ID = "app:para" private let ALLOW_ALL = "*" private var _u: ParaObject? private var _u1: ParaObject? private var _u2: ParaObject? private var _t: ParaObject? private var _s1: ParaObject? private var _s2: ParaObject? private var _a1: ParaObject? private var _a2: ParaObject? private static var ranOnce = false private func pc() -> ParaClient { if (ParaClientTests.c1 == nil) { ParaClientTests.c1 = ParaClient(accessKey: "app:para", secretKey: "JperV7KrcqPK9PAWzZZz7YVDTRex19sQbFdeamsJifqXP+8EyvgPtA==") //c1!.setEndpoint("http://192.168.0.114:8080") ParaClientTests.c1!.setEndpoint("http://localhost:8080") } return ParaClientTests.c1! } private func pc2() -> ParaClient { if (ParaClientTests.c2 == nil) { ParaClientTests.c2 = ParaClient(accessKey: "app:para", secretKey: nil) ParaClientTests.c2!.setEndpoint(pc().endpoint) } return ParaClientTests.c2! } private func u() -> ParaObject { if (_u == nil) { _u = ParaObject(id: "111") _u!.name = "John Doe" _u!.timestamp = currentTimeMillis() _u!.tags = ["one", "two", "three"] } return _u! } private func u1() -> ParaObject { if (_u1 == nil) { _u1 = ParaObject(id: "222") _u1!.name = "Joe Black" _u1!.timestamp = currentTimeMillis() _u1!.tags = ["two", "four", "three"] } return _u1! } private func u2() -> ParaObject { if (_u2 == nil) { _u2 = ParaObject(id: "333") _u2!.name = "Ann Smith" _u2!.timestamp = currentTimeMillis() _u2!.tags = ["four", "five", "three"] } return _u2! } private func t() -> ParaObject { if (_t == nil) { _t = ParaObject(id: "tag:test") _t!.type = "tag" _t!.properties["tag"] = "test" _t!.properties["count"] = 3 _t!.timestamp = currentTimeMillis() } return _t! } private func a1() -> ParaObject { if (_a1 == nil) { _a1 = ParaObject(id: "adr1") _a1!.type = "address" _a1!.name = "Place 1" _a1!.properties["address"] = "NYC" _a1!.properties["country"] = "US" _a1!.properties["latlng"] = "40.67,-73.94" _a1!.parentid = u().id _a1!.creatorid = u().id } return _a1! } private func a2() -> ParaObject { if (_a2 == nil) { _a2 = ParaObject(id: "adr2") _a2!.type = "address" _a2!.name = "Place 2" _a2!.properties["address"] = "NYC" _a2!.properties["country"] = "US" _a2!.properties["latlng"] = "40.69,-73.95" _a2!.parentid = t().id _a2!.creatorid = t().id } return _a2! } private func s1() -> ParaObject { if (_s1 == nil) { _s1 = ParaObject(id: "s1") _s1!.properties["text"] = "This is a little test sentence. Testing, one, two, three." _s1!.timestamp = currentTimeMillis() } return _s1! } private func s2() -> ParaObject { if (_s2 == nil) { _s2 = ParaObject(id: "s2") _s2!.properties["text"] = "We are testing this thing. This sentence is a test. One, two." _s2!.timestamp = currentTimeMillis() } return _s2! } private func currentTimeMillis() -> NSNumber { return NSNumber(value: UInt64(NSDate().timeIntervalSince1970 * 1000)) } override func setUp() { super.setUp() if (!ParaClientTests.ranOnce) { ParaClientTests.ranOnce = true let _1 = self.expectation(description: "") pc().me(nil, { res in assert(res != nil, "Para server must be running before testing!") self.pc().createAll([self.u(), self.u1(), self.u2(), self.t(), self.s1(), self.s2(), self.a1(), self.a2()], callback: { res in print("\((res?.count)!) Objects created!") _1.fulfill() }) }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } sleep(1) } } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { let _1 = expectation(description: "1") pc().getTimestamp({ response in XCTAssertNotNil(response) XCTAssertTrue(response > 0) _1.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testCRUD() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") let _9 = self.expectation(description: "9") let _10 = self.expectation(description: "10") let _11 = self.expectation(description: "11") let _12 = self.expectation(description: "12") let _13 = self.expectation(description: "13") pc().read("", id: "", callback: { _ in assert(false) }, error: { _ in assert(true) _1.fulfill() }) pc().read(id: "", callback: { res in assert(false) }, error: { _ in assert(true) _2.fulfill() }) let t1 = ParaObject(id: "test1") t1.type = "tag" let ux = ParaObject(id: "u1") ux.type = "user" pc().create(t1, callback: { t1 in assert(t1 != nil) self.pc().read(id: t1!.id, callback: { trID in assert(trID != nil) XCTAssertNotNil(trID!.timestamp) XCTAssertEqual(t1!.id, trID!.id) _5.fulfill() }) self.pc().read(t1!.type, id: t1!.id, callback: { tr in assert(tr != nil) XCTAssertNotNil(tr!.timestamp) XCTAssertEqual(t1!.id, tr!.id) tr!.properties["count"] = 15 self.pc().update(tr!, callback: { tu in assert(tu != nil) XCTAssertEqual((tu!.properties["count"] as! Int), (tr!.properties["count"] as! Int)) XCTAssertNotNil(tu!.updated) _6.fulfill() self.pc().delete(t1!, callback: { res in XCTAssertNil(res) self.pc().read(id: t1!.id, callback: { rez in XCTAssertNil(rez) _3.fulfill() }) _13.fulfill() }) }) self.pc().update(ParaObject(id: "nil"), callback: { res in assert(res == nil, "update() should not 'upsert'") _7.fulfill() }) _8.fulfill() }) _4.fulfill() }) pc().create(ux, callback: { user in assert(false, "user should not be created") _9.fulfill() }, error: { _ in assert(true) _9.fulfill() }) let s = ParaObject() s.type = dogsType s.properties["foo"] = "bark!" pc().create(s, callback: { s in assert(s != nil) self.pc().read("sysprop", id: s!.id, callback: { dog in XCTAssertTrue((dog!.properties["foo"]) != nil) XCTAssertEqual("bark!", dog!.properties["foo"] as? String) self.pc().delete(dog!) _11.fulfill() }) self.pc().delete(s!, callback: { res in XCTAssertNil(res) _12.fulfill() }) _10.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testBatchCRUD() { var dogs = [ParaObject]() for _ in 0...2 { let s = ParaObject() s.type = dogsType s.properties["foo"] = "bark!" dogs.append(s) } let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") let _9 = self.expectation(description: "9") pc().createAll([], callback: { res in XCTAssertTrue((res?.count)! == 0) _1.fulfill() }) pc().createAll(dogs, callback: { l1 in assert(l1?.count == 3) assert(l1?[0].id != nil) let nl = [l1![0].id, l1![1].id, l1![2].id] self.pc().readAll(nl, callback: { l2 in assert(l2?.count == 3) XCTAssertEqual(l1?[0].id, l2?[0].id) XCTAssertEqual(l1?[1].id, l2?[1].id) XCTAssertTrue((l2?[0].properties.keys.contains("foo"))!) XCTAssertEqual("bark!", (l2?[0].properties["foo"])! as? String) _2.fulfill() }) let part1 = ParaObject(id: l1![0].id) let part2 = ParaObject(id: l1![1].id) let part3 = ParaObject(id: l1![2].id) part1.type = self.dogsType part2.type = self.dogsType part3.type = self.dogsType part1.properties["custom"] = "prop" part1.name = "NewName1" part2.name = "NewName2" part3.name = "NewName3" self.pc().updateAll([part1, part2, part3], callback: { l3 in XCTAssertTrue(l3![0].properties.keys.contains("custom")) XCTAssertEqual(self.dogsType, l3![0].type) XCTAssertEqual(self.dogsType, l3![1].type) XCTAssertEqual(self.dogsType, l3![2].type) XCTAssertEqual(part1.name, l3![0].name) XCTAssertEqual(part2.name, l3![1].name) XCTAssertEqual(part3.name, l3![2].name) self.pc().deleteAll(nl, callback: { _ in sleep(1) self.pc().list(self.dogsType, callback: { res in XCTAssertTrue(res!.count == 0) _3.fulfill() }) self.pc().me(nil, { res in let datatypes = res!.properties["datatypes"] as? [String: String] XCTAssertTrue(datatypes!.values.contains(self.dogsType)) _4.fulfill() }) _5.fulfill() }) _6.fulfill() }) _7.fulfill() }) pc().readAll([], callback: { res in XCTAssertTrue(res!.count == 0) _8.fulfill() }) pc().updateAll([], callback: { res in XCTAssertTrue(res!.count == 0) _9.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testList() { var cats = [ParaObject]() for i in 0...2 { let s = ParaObject(id: catsType + "\(i)") s.type = catsType cats.append(s) } let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") pc().list("", callback: { res in XCTAssertTrue((res?.count)! == 0) _1.fulfill() }) pc().createAll(cats, callback: { list in sleep(1) self.pc().list(self.catsType, callback: { list1 in XCTAssertFalse(list1?.count == 0) XCTAssertEqual(3, list1?.count) XCTAssertEqual(self.catsType, list1?[0].type) _2.fulfill() }) self.pc().list(self.catsType, pager: Pager(limit: 2), callback: { list2 in XCTAssertFalse(list2?.count == 0) XCTAssertEqual(2, list2?.count) let nl = [cats[0].id, cats[1].id, cats[2].id] self.pc().deleteAll(nl, callback: { _ in self.pc().me(nil, { res in let datatypes = res!.properties["datatypes"] as? [String: String] XCTAssertTrue(datatypes!.values.contains(self.catsType)) _3.fulfill() }) _4.fulfill() }) _5.fulfill() }) _6.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testSearch() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") let _9 = self.expectation(description: "9") let _10 = self.expectation(description: "10") let _11 = self.expectation(description: "11") let _12 = self.expectation(description: "12") let _13 = self.expectation(description: "13") let _14 = self.expectation(description: "14") let _15 = self.expectation(description: "15") let _16 = self.expectation(description: "16") let _17 = self.expectation(description: "17") let _18 = self.expectation(description: "18") let _19 = self.expectation(description: "19") let _20 = self.expectation(description: "20") let _21 = self.expectation(description: "21") let _22 = self.expectation(description: "22") let _23 = self.expectation(description: "23") let _24 = self.expectation(description: "24") let _25 = self.expectation(description: "25") let _26 = self.expectation(description: "26") let _27 = self.expectation(description: "27") let _28 = self.expectation(description: "28") let _29 = self.expectation(description: "29") let _30 = self.expectation(description: "30") let _31 = self.expectation(description: "31") let _32 = self.expectation(description: "32") let _33 = self.expectation(description: "33") let _34 = self.expectation(description: "34") let _35 = self.expectation(description: "35") let _36 = self.expectation(description: "36") let _37 = self.expectation(description: "37") let _38 = self.expectation(description: "38") let _39 = self.expectation(description: "39") let _40 = self.expectation(description: "40") let _41 = self.expectation(description: "41") let _42 = self.expectation(description: "42") let _43 = self.expectation(description: "43") let _44 = self.expectation(description: "44") let _45 = self.expectation(description: "45") let _46 = self.expectation(description: "46") let _47 = self.expectation(description: "47") let _48 = self.expectation(description: "48") let _49 = self.expectation(description: "49") let _50 = self.expectation(description: "50") pc().findById("", callback: { res in XCTAssertNil(res) _1.fulfill() }) pc().findById(u().id, callback: { res in XCTAssertNotNil(res) _2.fulfill() }) pc().findById(t().id, callback: { res in XCTAssertNotNil(res) _3.fulfill() }) pc().findByIds([], callback: { res in XCTAssertTrue((res?.count)! == 0) _4.fulfill() }) pc().findByIds([u().id, u1().id, u2().id], callback: { res in XCTAssertEqual(3, (res?.count)!) _5.fulfill() }) pc().findNearby("", query: "", radius: 100, lat: 1, lng: 1, callback: { res in XCTAssertTrue((res?.count)! == 0) _6.fulfill() }) pc().findNearby(u().type, query: "*", radius: 10, lat: 40.60, lng: -73.90, callback: { res in XCTAssertFalse((res?.count)! == 0) _7.fulfill() }) pc().findNearby(t().type, query: "*", radius: 20, lat: 40.62, lng: -73.91, callback: { res in XCTAssertFalse((res?.count)! == 0) _8.fulfill() }) pc().findPrefix("", field: "", prefix: "", callback: { res in XCTAssertTrue((res?.count)! == 0) _9.fulfill() }) pc().findPrefix("", field: "nil", prefix: "xx", callback: { res in XCTAssertTrue((res?.count)! == 0) _10.fulfill() }) pc().findPrefix(u().type, field: "name", prefix: "Ann", callback: { res in XCTAssertFalse((res?.count)! == 0) _11.fulfill() }) pc().findQuery("", query: "", callback: { res in XCTAssertFalse((res?.count)! > 0) _12.fulfill() }) pc().findQuery("", query: "*", callback: { res in XCTAssertFalse((res?.count)! == 0) _13.fulfill() }) pc().findQuery(a1().type, query: "country:US", callback: { res in XCTAssertEqual(2, (res?.count)!) _14.fulfill() }) pc().findQuery(u().type, query: "Ann*", callback: { res in XCTAssertFalse((res?.count)! == 0) _15.fulfill() }) pc().findQuery(u().type, query: "Ann*", callback: { res in XCTAssertFalse((res?.count)! == 0) _16.fulfill() }) pc().findQuery("", query: "*", callback: { res in XCTAssertTrue((res?.count)! > 4) _17.fulfill() }) let p = Pager() XCTAssertEqual(0, p.count) pc().findQuery(u().type, query: "*", pager: p, callback: { res in XCTAssertEqual(UInt(res!.count), p.count) XCTAssertTrue(p.count > 0) _18.fulfill() }) pc().findSimilar(t().type, filterKey: "", fields: nil, liketext: "", callback: { res in XCTAssertTrue((res?.count)! == 0) _19.fulfill() }) pc().findSimilar(t().type, filterKey: "", fields: [], liketext: "", callback: { res in XCTAssertTrue((res?.count)! == 0) _20.fulfill() }) pc().findSimilar(s1().type, filterKey: s1().id, fields: ["properties.text"], liketext: s1().properties["text"] as! String, callback: { res in assert((res?.count)! > 0) XCTAssertEqual(self.s2().id, res![0].id) XCTAssertEqual(self.s2().name, res![0].name) _21.fulfill() }) pc().findTagged(u().type, callback: { res in XCTAssertEqual(0, (res?.count)!) _22.fulfill() }) pc().findTagged(u().type, tags: ["two"], callback: { res in XCTAssertEqual(2, (res?.count)!) _23.fulfill() }) pc().findTagged(u().type, tags: ["one", "two"], callback: { res in XCTAssertEqual(1, (res?.count)!) _24.fulfill() }) pc().findTagged(u().type, tags: ["three"], callback: { res in XCTAssertEqual(3, (res?.count)!) _25.fulfill() }) pc().findTagged(u().type, tags: ["four", "three"], callback: { res in XCTAssertEqual(2, (res?.count)!) _26.fulfill() }) pc().findTagged(u().type, tags: ["five", "three"], callback: { res in XCTAssertEqual(1, (res?.count)!) _27.fulfill() }) pc().findTagged(t().type, tags: ["four", "three"], callback: { res in XCTAssertEqual(0, (res?.count)!) _28.fulfill() }) pc().findTags(callback: { res in XCTAssertFalse((res?.count)! == 0) _29.fulfill() }) pc().findTags("", callback: { res in XCTAssertFalse((res?.count)! == 0) _30.fulfill() }) pc().findTags("unknown", callback: { res in XCTAssertTrue((res?.count)! == 0) _31.fulfill() }) pc().findTags(t().properties["tag"] as? String, callback: { res in XCTAssertTrue((res?.count)! >= 1) _32.fulfill() }) pc().findTermInList(u().type, field: "id", terms: [u().id, u1().id, u2().id, "xxx", "yyy"], callback: { res in XCTAssertEqual(3, (res?.count)!) _33.fulfill() }) // many terms let terms = ["id": u().id] let terms1 = ["type": "", "id": " "] let terms2 = [" ": "bad", "": ""] pc().findTerms(u().type, terms: terms as [String : AnyObject], matchAll: true, callback: { res in XCTAssertEqual(1, (res?.count)!) _34.fulfill() }) pc().findTerms(u().type, terms: terms1 as [String : AnyObject], matchAll: true, callback: { res in XCTAssertTrue((res?.count)! == 0) _35.fulfill() }) pc().findTerms(u().type, terms: terms2 as [String : AnyObject], matchAll: true, callback: { res in XCTAssertTrue((res?.count)! == 0) _36.fulfill() }) // single term pc().findTerms("", terms: [:], matchAll: true, callback: { res in XCTAssertTrue((res?.count)! == 0) _37.fulfill() }) pc().findTerms(u().type, terms: ["": "" as AnyObject], matchAll: true, callback: { res in XCTAssertTrue((res?.count)! == 0) _38.fulfill() }) pc().findTerms(u().type, terms: ["term": "" as AnyObject], matchAll: true, callback: { res in XCTAssertTrue((res?.count)! == 0) _39.fulfill() }) pc().findTerms(u().type, terms: ["type": u().type as AnyObject], matchAll: true, callback: { res in XCTAssertTrue((res?.count)! >= 2) _40.fulfill() }) pc().findWildcard(u().type, field: "", wildcard: "", callback: { res in XCTAssertTrue((res?.count)! == 0) _41.fulfill() }) pc().findWildcard(u().type, field: "name", wildcard: "An*", callback: { res in XCTAssertFalse((res?.count)! == 0) _42.fulfill() }) pc().getCount("", callback: { res in XCTAssertTrue(res > 4) _43.fulfill() }) pc().getCount("", callback: { res in XCTAssertNotEqual(0, res) _44.fulfill() }) pc().getCount("test", callback: { res in XCTAssertEqual(0, res) _45.fulfill() }) pc().getCount(u().type, callback: { res in XCTAssertTrue(res >= 3) _46.fulfill() }) pc().getCount("", terms: [:], callback: { res in XCTAssertEqual(0, res) _47.fulfill() }) pc().getCount(u().type, terms: ["id": " " as AnyObject], callback: { res in XCTAssertEqual(0, res) _48.fulfill() }) pc().getCount(u().type, terms: ["id": u().id as AnyObject], callback: { res in XCTAssertEqual(1, res) _49.fulfill() }) pc().getCount("", terms: ["type": u().type as AnyObject], callback: { res in XCTAssertTrue(res > 1) _50.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testLinks() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") let _9 = self.expectation(description: "9") let _10 = self.expectation(description: "10") let _11 = self.expectation(description: "11") let _12 = self.expectation(description: "12") let _13 = self.expectation(description: "13") let _14 = self.expectation(description: "13") pc().link(u(), id2: t().id, callback: { res in XCTAssertNotNil(res) self.pc().link(self.u(), id2: self.u2().id, callback: { res in XCTAssertNotNil(res) sleep(1) self.pc().isLinked(self.u(), toObj: ParaObject(), callback: { res in XCTAssertFalse(res) _1.fulfill() }) self.pc().isLinked(self.u(), toObj: self.t(), callback: { res in XCTAssertTrue(res) _2.fulfill() }) self.pc().isLinked(self.u(), toObj: self.u2(), callback: { res in XCTAssertTrue(res) _3.fulfill() }) self.pc().getLinkedObjects(self.u(), type2: "tag", callback: { res in XCTAssertEqual(1, res.count) _4.fulfill() }) self.pc().getLinkedObjects(self.u(), type2: "sysprop", callback: { res in XCTAssertEqual(1, res.count) _5.fulfill() }) self.pc().countLinks(self.u(), type2: "", callback: { res in XCTAssertEqual(0, res) _6.fulfill() }) self.pc().countLinks(self.u(), type2: "tag", callback: { res in XCTAssertEqual(1, res) _7.fulfill() }) self.pc().countLinks(self.u(), type2: "sysprop", callback: { res in XCTAssertEqual(1, res) _8.fulfill() }) self.pc().countChildren(self.u(), type2: "address", callback: { res in XCTAssertEqual(2, res) _14.fulfill() }) self.pc().unlinkAll(self.u(), callback: { res in self.pc().isLinked(self.u(), toObj: self.t(), callback: { res in XCTAssertFalse(res) _9.fulfill() }) self.pc().isLinked(self.u(), toObj: self.u2(), callback: { res in XCTAssertFalse(res) _10.fulfill() }) _11.fulfill() }) _12.fulfill() }) _13.fulfill() }, error: { err in assert(false, "Link test failed.") }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testUtils() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") pc().newId({ id1 in self.pc().newId({ id2 in XCTAssertNotNil(id1) XCTAssertFalse(id1!.isEmpty) XCTAssertNotEqual(id1, id2) _1.fulfill() }) _2.fulfill() }) pc().getTimestamp({ ts in XCTAssertNotNil(ts) XCTAssertNotEqual(0, ts) _3.fulfill() }) pc().formatDate("MM dd yyyy", locale: "US", callback: { date1 in let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM dd yyyy" let date2 = dateFormatter.string(from: Date()) XCTAssertEqual(date1, date2) _4.fulfill() }) pc().noSpaces(" test 123 test ", replaceWith: "", callback: { ns1 in let ns2 = "test123test" XCTAssertEqual(ns1, ns2) _5.fulfill() }) pc().stripAndTrim(" %^&*( cool ) @!", callback: { st1 in let st2 = "cool" XCTAssertEqual(st1, st2) _6.fulfill() }) pc().markdownToHtml("### hello **test**", callback: { md1 in let md2 = "<h3>hello <strong>test</strong></h3>" XCTAssertEqual(md1?.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines), md2) _7.fulfill() }) pc().approximately(UInt(15000), callback: { ht1 in let ht2 = "15s" XCTAssertEqual(ht1, ht2) _8.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testMisc() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") pc().types({ types in XCTAssertTrue(types!.keys.contains("users")) _1.fulfill() }) pc().me(nil, { app in XCTAssertEqual(self.APP_ID, app?.id) _2.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testValidationConstraints() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") // Validations let kittenType = "kitten" pc().validationConstraints({ constraints in XCTAssertNotNil(constraints) XCTAssertFalse(constraints!.isEmpty) XCTAssertTrue(constraints!.keys.contains("app")) XCTAssertTrue(constraints!.keys.contains("user")) _1.fulfill() }) pc().validationConstraints("app", callback: { constraint in XCTAssertFalse(constraint!.isEmpty) XCTAssertTrue(constraint!.keys.contains("app")) XCTAssertEqual(1, constraint!.count) _2.fulfill() }) pc().addValidationConstraint(kittenType, field: "paws", constraint: Constraint.required(), callback: { _ in self.pc().validationConstraints(kittenType, callback: { constraint in assert(!constraint!.isEmpty) XCTAssertTrue((constraint![kittenType] as! [String: AnyObject]).keys.contains("paws")) let ct = ParaObject(id: "felix") ct.type = kittenType // validation fails self.pc().create(ct, callback: { res in assert(false) }, error: { err in assert(true) // fix ct.properties["paws"] = "4" self.pc().create(ct, callback: { res in XCTAssertNotNil(res) self.pc().delete(res!) self.pc().removeValidationConstraint(kittenType, field: "paws", constraintName: "required", callback: { _ in self.pc().validationConstraints(kittenType, callback: { constraint in XCTAssertFalse(constraint!.keys.contains(kittenType)) _3.fulfill() }) _4.fulfill() }) _5.fulfill() }) _6.fulfill() }) _7.fulfill() }) _8.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testResourcePermissions() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") let _9 = self.expectation(description: "9") let _10 = self.expectation(description: "10") // let _11 = self.expectation(description: "11") let _12 = self.expectation(description: "12") let _13 = self.expectation(description: "13") let _14 = self.expectation(description: "14") let _15 = self.expectation(description: "15") let _16 = self.expectation(description: "16") let _17 = self.expectation(description: "17") let _18 = self.expectation(description: "18") let _19 = self.expectation(description: "19") let _20 = self.expectation(description: "20") let _21 = self.expectation(description: "21") let _22 = self.expectation(description: "22") let _23 = self.expectation(description: "23") let _24 = self.expectation(description: "24") let _25 = self.expectation(description: "25") let _26 = self.expectation(description: "26") let _27 = self.expectation(description: "27") let _28 = self.expectation(description: "28") let _29 = self.expectation(description: "29") let _30 = self.expectation(description: "30") let _31 = self.expectation(description: "31") let _32 = self.expectation(description: "32") let _33 = self.expectation(description: "33") let _34 = self.expectation(description: "34") let _35 = self.expectation(description: "35") let _36 = self.expectation(description: "36") let _37 = self.expectation(description: "37") let _38 = self.expectation(description: "38") let _39 = self.expectation(description: "39") let _40 = self.expectation(description: "40") let _41 = self.expectation(description: "41") let _42 = self.expectation(description: "42") let _43 = self.expectation(description: "43") let _44 = self.expectation(description: "44") // Permissions pc().resourcePermissions({ res in XCTAssertNotNil(res) _1.fulfill() }) pc().grantResourcePermission("", resourcePath: dogsType, permission: [], callback: { res in XCTAssertTrue((res?.count)! == 0) _2.fulfill() }) pc().grantResourcePermission(" ", resourcePath: "", permission: [], callback: { res in XCTAssertTrue((res?.count)! == 0) _3.fulfill() }) pc().grantResourcePermission(u1().id, resourcePath: dogsType, permission: ["GET"], callback: { _ in self.pc().resourcePermissions(self.u1().id, callback: { permits in XCTAssertTrue(permits!.keys.contains(self.u1().id)) XCTAssertTrue((permits![self.u1().id] as! [String: AnyObject]).keys.contains(self.dogsType)) self.pc().isAllowedTo(self.u1().id, resourcePath: self.dogsType, httpMethod: "POST", callback: { res in XCTAssertFalse(res) self.pc().isAllowedTo(self.u1().id, resourcePath: self.dogsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) _4.fulfill() }) _5.fulfill() }) _6.fulfill() }) // anonymous permissions self.pc().isAllowedTo(self.ALLOW_ALL, resourcePath: "utils/timestamp", httpMethod: "GET", callback: { res in XCTAssertFalse(res) _7.fulfill() self.pc().grantResourcePermission(self.ALLOW_ALL, resourcePath: "utils/timestamp", permission: ["GET"], allowGuestAccess: true, callback: { res in XCTAssertNotNil(res) self.pc2().getTimestamp({ res in XCTAssertTrue(res > 0) _8.fulfill() }) self.pc().isAllowedTo(self.ALLOW_ALL, resourcePath: "utils/timestamp", httpMethod: "DELETE", callback: { res in XCTAssertFalse(res) sleep(1) self.pc().revokeResourcePermission(self.u1().id, resourcePath: self.dogsType, callback: { res in sleep(1) self.pc().resourcePermissions(self.u1().id, callback: { permits in XCTAssertFalse((permits![self.u1().id] as! [String: AnyObject]).keys.contains(self.dogsType)) self.pc().isAllowedTo(self.u1().id, resourcePath: self.dogsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) _12.fulfill() }) self.pc().isAllowedTo(self.u1().id, resourcePath: self.dogsType, httpMethod: "POST", callback: { res in XCTAssertFalse(res) _13.fulfill() }) _14.fulfill() }) _15.fulfill() }) self.pc().revokeResourcePermission(self.ALLOW_ALL, resourcePath: "utils/timestamp", callback: { _ in _44.fulfill() }) _9.fulfill() }) _10.fulfill() }) }) // self.pc().resourcePermissions({ permits in // XCTAssertTrue(permits!.keys.contains(self.u1().id)) // XCTAssertTrue((permits![self.u1().id] as! [String: AnyObject]).keys.contains(self.dogsType)) // _11.fulfill() // }) _16.fulfill() }) let WRITE = ["POST", "PUT", "PATCH", "DELETE"] pc().grantResourcePermission(self.u2().id, resourcePath: self.ALLOW_ALL, permission: WRITE, callback: { res in sleep(1) self.pc().isAllowedTo(self.u2().id, resourcePath: self.dogsType, httpMethod: "PUT", callback: { res in XCTAssertTrue(res) _17.fulfill() }) self.pc().isAllowedTo(self.u2().id, resourcePath: self.dogsType, httpMethod: "PATCH", callback: { res in XCTAssertTrue(res) _18.fulfill() }) self.pc().revokeAllResourcePermissions(self.u2().id, callback: { permits in sleep(1) self.pc().resourcePermissions({ res in self.pc().isAllowedTo(self.u2().id, resourcePath: self.dogsType, httpMethod: "PUT", callback: { res in XCTAssertFalse(res) _19.fulfill() }) XCTAssertTrue((permits![self.u2().id] as! [String: AnyObject]).isEmpty) _20.fulfill() }) _21.fulfill() }) _22.fulfill() }) pc().grantResourcePermission(u().id, resourcePath: dogsType, permission: WRITE, callback: { res in self.pc().grantResourcePermission(self.ALLOW_ALL, resourcePath: self.catsType, permission: WRITE, callback: { res in self.pc().grantResourcePermission(self.ALLOW_ALL, resourcePath: self.ALLOW_ALL, permission: ["GET"], callback: { res in // user-specific permissions are in effect self.pc().isAllowedTo(self.u().id, resourcePath: self.dogsType, httpMethod: "PUT", callback: { res in XCTAssertTrue(res) _23.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.dogsType, httpMethod: "GET", callback: { res in XCTAssertFalse(res) _24.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.catsType, httpMethod: "PUT", callback: { res in XCTAssertTrue(res) _25.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.catsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) _26.fulfill() }) self.pc().revokeAllResourcePermissions(self.u().id, callback: { res in // user-specific permissions not found so check wildcard self.pc().isAllowedTo(self.u().id, resourcePath: self.dogsType, httpMethod: "PUT", callback: { res in XCTAssertFalse(res) _27.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.dogsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) _28.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.catsType, httpMethod: "PUT", callback: { res in XCTAssertTrue(res) _29.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.catsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) self.pc().revokeResourcePermission(self.ALLOW_ALL, resourcePath: self.catsType, callback: { res in // resource-specific permissions not found so check wildcard self.pc().isAllowedTo(self.u().id, resourcePath: self.dogsType, httpMethod: "PUT", callback: { res in XCTAssertFalse(res) _30.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.catsType, httpMethod: "PUT", callback: { res in XCTAssertFalse(res) _31.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.dogsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) _32.fulfill() }) self.pc().isAllowedTo(self.u().id, resourcePath: self.catsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) _33.fulfill() }) self.pc().isAllowedTo(self.u2().id, resourcePath: self.dogsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) _34.fulfill() }) self.pc().isAllowedTo(self.u2().id, resourcePath: self.catsType, httpMethod: "GET", callback: { res in XCTAssertTrue(res) self.pc().revokeAllResourcePermissions(self.ALLOW_ALL, callback: { _ in _35.fulfill() }) self.pc().revokeAllResourcePermissions(self.u().id, callback: { _ in _36.fulfill() }) _37.fulfill() }) _38.fulfill() }) _39.fulfill() }) _40.fulfill() }) _41.fulfill() }) _42.fulfill() }) _43.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testAppSettings() { let _1 = self.expectation(description: "1") let _2 = self.expectation(description: "2") let _3 = self.expectation(description: "3") let _4 = self.expectation(description: "4") let _5 = self.expectation(description: "5") let _6 = self.expectation(description: "6") let _7 = self.expectation(description: "7") let _8 = self.expectation(description: "8") let _9 = self.expectation(description: "9") let _10 = self.expectation(description: "10") let _11 = self.expectation(description: "11") let _12 = self.expectation(description: "12") let _13 = self.expectation(description: "13") let _14 = self.expectation(description: "14") pc().appSettings(callback: { res in XCTAssertNotNil(res) XCTAssertTrue((res?.count)! == 0) self.pc().appSettings(" ", callback: { res in XCTAssertNotNil(res) XCTAssertTrue((res?.count)! == 0) _1.fulfill() }) self.pc().appSettings(nil, callback: { res in XCTAssertNotNil(res) XCTAssertTrue((res?.count)! == 0) _2.fulfill() }) self.pc().addAppSetting("prop1", value: 1 as AnyObject, callback: { res in self.pc().addAppSetting("prop2", value: true as AnyObject, callback: { res in self.pc().addAppSetting("prop3", value: "string" as AnyObject, callback: { res in self.pc().appSettings(callback: { res in XCTAssertNotNil(res) XCTAssertTrue((res?.count)! == 3) self.pc().appSettings("prop1", callback: { res in XCTAssertTrue((res?["value"])! as! NSNumber == 1) _3.fulfill() }) self.pc().appSettings("prop2", callback: { res in XCTAssertNotNil(res) XCTAssertTrue((res?["value"])! as! Bool) _4.fulfill() }) self.pc().appSettings("prop3", callback: { res in XCTAssertNotNil(res) XCTAssertTrue(((res?["value"])! as! NSObject) as! String == "string") self.pc().removeAppSetting("prop3", callback: { res in self.pc().removeAppSetting("prop2", callback: { res in self.pc().removeAppSetting("prop1", callback: { res in self.pc().appSettings(callback: { res in XCTAssertTrue((res?.count)! == 0) _5.fulfill() }) _6.fulfill() }) _7.fulfill() }) _8.fulfill() }) _9.fulfill() }) _10.fulfill() }) _11.fulfill() }) _12.fulfill() }) _13.fulfill() }) _14.fulfill() }) self.waitForExpectations(timeout: 10) { error in XCTAssertNil(error, "Test failed.") } } func testAccessTokens() { XCTAssertNil(pc().getAccessToken()) pc().signIn("facebook", providerToken: "test_token", callback: { res in XCTAssertNil(res) }) pc().signOut() pc().revokeAllTokens({ res in XCTAssertFalse(res) }) } }
461bf462b06f21ac2eb56acc6675ec13
29.344694
143
0.617715
false
false
false
false
artursDerkintis/Starfly
refs/heads/master
Starfly/SFHomeSwitcher.swift
mit
1
// // SFHomeSwitcher.swift // Starfly // // Created by Arturs Derkintis on 9/20/15. // Copyright © 2015 Starfly. All rights reserved. // import UIKit class SFHomeSwitcher: UIControl { var floater : SFView? var items = ["Bookmarks", "Home", "History"] var centers = [CGPoint]() var oldX : CGFloat = 0 var dragging = false var currentPage : Int = 1 var ImDoingSomething = false override init(frame: CGRect) { super.init(frame: frame) let count = CGFloat(items.count) backgroundColor = UIColor.lightGrayColor() let background = SFView(frame: bounds) background.alpha = 0.5 background.layer.cornerRadius = frame.height * 0.5 background.layer.masksToBounds = true addSubview(background) background.userInteractionEnabled = false layer.cornerRadius = frame.height * 0.5 layer.masksToBounds = false layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 2 layer.shadowOpacity = 1.0 layer.shouldRasterize = true layer.borderWidth = 0 layer.borderColor = UIColor.whiteColor().CGColor layer.rasterizationScale = UIScreen.mainScreen().scale floater = SFView(frame: CGRect(x: 0, y: 0, width: frame.width / count, height: frame.height)) floater?.layer.cornerRadius = floater!.frame.height * 0.5 floater?.layer.borderWidth = 0 floater?.layer.borderColor = UIColor.whiteColor().CGColor floater?.userInteractionEnabled = false addSubview(floater!) for item in items{ let label = UILabel(frame: CGRect(x: (frame.width / count) * CGFloat(items.indexOf(item)!), y: 0, width: frame.width / count, height: frame.height)) label.textColor = .whiteColor() label.font = UIFont.systemFontOfSize(14, weight: UIFontWeightRegular) label.layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor label.layer.shadowOffset = CGSize(width: 0, height: lineWidth()) label.layer.shadowRadius = 0 label.userInteractionEnabled = false label.layer.shadowOpacity = 1.0 label.layer.rasterizationScale = UIScreen.mainScreen().scale label.layer.shouldRasterize = true label.textAlignment = NSTextAlignment.Center label.text = item addSubview(label) centers.append(label.center) } } func liveScroll(point : CGPoint){ if !ImDoingSomething{ floater?.frame.origin = point } } func setPage(current : Int){ if !ImDoingSomething{ currentPage = current ImDoingSomething = true UIView.animateWithDuration(0.1, animations: { () -> Void in self.floater?.center = CGPoint(x: self.centers[current].x, y: self.floater!.center.y) }) { (done) -> Void in self.ImDoingSomething = false } } } override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { let loc = touch.locationInView(self) if CGRectContainsPoint(floater!.frame, loc){ oldX = touch.locationInView(floater!).x dragging = true return true } var closestX : CGFloat = CGFloat.infinity var point : CGPoint? for cente in centers{ let distance = cente.distanceToPoint(loc) if closestX >= distance{ closestX = distance point = cente currentPage = centers.indexOf(cente)! } } ImDoingSomething = true UIView.animateWithDuration(0.3, animations: { () -> Void in self.floater?.center = CGPoint(x: point!.x, y: self.floater!.center.y) }) { (done) -> Void in self.ImDoingSomething = false } sendActionsForControlEvents(UIControlEvents.TouchUpInside) return false } override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { let loc = touch.locationInView(self) if dragging{ if floater!.frame.origin.x >= 0 && floater!.frame.origin.x <= frame.width - floater!.frame.width{ floater?.frame = CGRect(x: loc.x - oldX, y: 0, width: floater!.frame.width, height: floater!.frame.height) } } sendActionsForControlEvents(UIControlEvents.ValueChanged) return true } override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { var closestX : CGFloat = CGFloat.infinity var point : CGPoint? for cente in centers{ let distance = cente.distanceToPoint(floater!.center) if closestX >= distance{ closestX = distance point = cente currentPage = centers.indexOf(cente)! } } ImDoingSomething = true UIView.animateWithDuration(0.3, animations: { () -> Void in self.floater?.center = CGPoint(x: point!.x, y: self.floater!.center.y) }) { (done) -> Void in self.ImDoingSomething = false } sendActionsForControlEvents(UIControlEvents.TouchUpInside) dragging = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
aa3d3f5c596a49e3b3e25bc63c4918e9
35.030303
160
0.594113
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/VCardContactController.swift
gpl-2.0
1
// // VCardContactController.swift // Telegram // // Created by Mikhail Filimonov on 19/07/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Postbox import Contacts import SwiftSignalKit // //private class VCardContactView : View { // let tableView: TableView = TableView(frame: NSZeroRect) // private let title: TextView = TextView() // private let separator : View = View() // required init(frame frameRect: NSRect) { // super.init(frame: frameRect) // addSubview(title) // addSubview(tableView) // addSubview(separator) // separator.backgroundColor = theme.colors.border // // self.title.update(TextViewLayout(.initialize(string: "Contact", color: theme.colors.text, font: .medium(.title)), maximumNumberOfLines: 1)) // needsLayout = true // } // // // // required init?(coder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // // override func layout() { // super.layout() // tableView.frame = NSMakeRect(0, 50, frame.width, frame.height - 50) // title.layout?.measure(width: frame.width - 60) // title.update(title.layout) // title.centerX(y: floorToScreenPixels(backingScaleFactor, (50 - title.frame.height) / 2)) // separator.frame = NSMakeRect(0, 49, frame.width, .borderSize) // } //} // //private final class VCardArguments { // let account: Account // init(account: Account) { // self.account = account // } //} // //private func vCardEntries(vCard: CNContact, contact: TelegramMediaContact, arguments: VCardArguments) -> [InputDataEntry] { // // var entries: [InputDataEntry] = [] // var sectionId:Int32 = 0 // var index: Int32 = 0 // // func getLabel(_ key: String) -> String { // // switch key { // case "_$!<HomePage>!$_": // return strings().contactInfoURLLabelHomepage // case "_$!<Home>!$_": // return strings().contactInfoPhoneLabelHome // case "_$!<Work>!$_": // return strings().contactInfoPhoneLabelWork // case "_$!<Mobile>!$_": // return strings().contactInfoPhoneLabelMobile // case "_$!<Main>!$_": // return strings().contactInfoPhoneLabelMain // case "_$!<HomeFax>!$_": // return strings().contactInfoPhoneLabelHomeFax // case "_$!<WorkFax>!$_": // return strings().contactInfoPhoneLabelWorkFax // case "_$!<Pager>!$_": // return strings().contactInfoPhoneLabelPager // case "_$!<Other>!$_": // return strings().contactInfoPhoneLabelOther // default: // return strings().contactInfoPhoneLabelOther // } // } // // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("header"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return VCardHeaderItem(initialSize, stableId: stableId, account: arguments.account, vCard: vCard, contact: contact) // })) // index += 1 // // for phoneNumber in vCard.phoneNumbers { // if let label = phoneNumber.label { // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("phone_\(phoneNumber.identifier)"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return TextAndLabelItem(initialSize, stableId: stableId, label: getLabel(label), text: phoneNumber.value.stringValue, account: arguments.account) // })) // } // index += 1 // } // // for email in vCard.emailAddresses { // if let label = email.label { // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("email_\(email.identifier)"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return TextAndLabelItem(initialSize, stableId: stableId, label: getLabel(label), text: email.value as String, account: arguments.account) // })) // } // index += 1 // } // // for address in vCard.urlAddresses { // if let label = address.label { // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("url_\(address.identifier)"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return TextAndLabelItem(initialSize, stableId: stableId, label: getLabel(label), text: address.value as String, account: arguments.account) // })) // } // index += 1 // } // // for address in vCard.postalAddresses { // if let label = address.label { // let text: String = address.value.street + "\n" + address.value.city + "\n" + address.value.country // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("url_\(address.identifier)"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return TextAndLabelItem(initialSize, stableId: stableId, label: getLabel(label), text: text, account: arguments.account) // })) // } // index += 1 // } // // if let birthday = vCard.birthday { // let date = Calendar.current.date(from: birthday)! // // let dateFormatter = DateFormatter() // dateFormatter.dateStyle = .long // // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("birthday"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return TextAndLabelItem(initialSize, stableId: stableId, label: strings().contactInfoBirthdayLabel, text: dateFormatter.string(from: date), account: arguments.account) // })) // index += 1 // } // // for social in vCard.socialProfiles { // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("social_\(social.identifier)"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return TextAndLabelItem(initialSize, stableId: stableId, label: social.value.service, text: social.value.urlString, account: arguments.account) // })) // } // // for social in vCard.instantMessageAddresses { // entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("instant_\(social.identifier)"), equatable: nil, comparable: nil, item: { initialSize, stableId -> TableRowItem in // return TextAndLabelItem(initialSize, stableId: stableId, label: social.value.service, text: social.value.username, account: arguments.account) // })) // } // // // return entries //} // // //final class VCardModalController : ModalViewController { // private let controller: NavigationViewController // init(_ account: Account, vCard: CNContact, contact: TelegramMediaContact) { // self.controller = VCardContactController(account, vCard: vCard, contact: contact) // super.init(frame: controller._frameRect) // } // // public override var handleEvents: Bool { // return true // } // // public override func firstResponder() -> NSResponder? { // return controller.controller.firstResponder() // } // // public override func returnKeyAction() -> KeyHandlerResult { // return controller.controller.returnKeyAction() // } // // public override var haveNextResponder: Bool { // return true // } // // public override func nextResponder() -> NSResponder? { // return controller.controller.nextResponder() // } // // var input: InputDataController { // return controller.controller as! InputDataController // } // // public override func viewDidLoad() { // super.viewDidLoad() // ready.set(controller.ready.get()) // } // // override var view: NSView { // if !controller.isLoaded() { // controller.loadViewIfNeeded() // viewDidLoad() // } // return controller.view // } // // override var modalInteractions: ModalInteractions? { // return ModalInteractions(acceptTitle: strings().modalOK) // } // // override func measure(size: NSSize) { // self.modal?.resize(with:NSMakeSize(380, min(size.height - 70, input.genericView.listHeight + 70)), animated: false) // } // // public func updateSize(_ animated: Bool) { // if let contentSize = self.modal?.window.contentView?.frame.size { // self.modal?.resize(with:NSMakeSize(380, min(contentSize.height - 70, input.genericView.listHeight + 70)), animated: animated) // } // } // override var dynamicSize: Bool { // return true // } // //} // //private class VCardContactController: NavigationViewController { // //// override func viewClass() -> AnyClass { //// return VCardContactView.self //// } // // fileprivate let context: AccountContext // fileprivate let vCard: CNContact // fileprivate let contact: TelegramMediaContact // fileprivate let input: InputDataController // fileprivate let values: Promise<[InputDataEntry]> = Promise() // init(_ account: Account, vCard: CNContact, contact: TelegramMediaContact) { // self.account = account // self.vCard = vCard // self.contact = contact // input = InputDataController(dataSignal: values.get() |> map {($0, true)}, title: strings().contactInfoContactInfo, hasDone: false) // super.init(input) // self._frameRect = NSMakeRect(0, 0, 380, 500) // } // // // // // override func viewDidLoad() { // super.viewDidLoad() // ready.set(input.ready.get()) // let arguments = VCardArguments(account: account) // let vCard = self.vCard // let contact = self.contact // // values.set(appearanceSignal |> deliverOnPrepareQueue |> map { _ in return vCardEntries(vCard: vCard, contact: contact, arguments: arguments)}) // } // //// private var genericView:VCardContactView { //// return self.view as! VCardContactView //// } // //}
68eb039447525e23ea3073efb14e58b3
40.317829
250
0.627486
false
false
false
false
Monnoroch/Cuckoo
refs/heads/master
Generator/Dependencies/FileKit/Sources/FilePermissions.swift
mit
1
// // FilePermissions.swift // FileKit // // The MIT License (MIT) // // Copyright (c) 2015-2016 Nikolai Vazquez // // 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 /// The permissions of a file. public struct FilePermissions: OptionSet, CustomStringConvertible { /// The file can be read from. public static let Read = FilePermissions(rawValue: 1) /// The file can be written to. public static let Write = FilePermissions(rawValue: 2) /// The file can be executed. public static let Execute = FilePermissions(rawValue: 4) /// The raw integer value of `self`. public let rawValue: Int /// A textual representation of `self`. public var description: String { var description = "" for permission in [.Read, .Write, .Execute] as [FilePermissions] { if self.contains(permission) { description += !description.isEmpty ? ", " : "" if permission == .Read { description += "Read" } else if permission == .Write { description += "Write" } else if permission == .Execute { description += "Execute" } } } return String(describing: type(of: self)) + "[" + description + "]" } /// Creates a set of file permissions. /// /// - Parameter rawValue: The raw value to initialize from. /// public init(rawValue: Int) { self.rawValue = rawValue } /// Creates a set of permissions for the file at `path`. /// /// - Parameter path: The path to the file to create a set of persmissions for. /// public init(forPath path: Path) { var permissions = FilePermissions(rawValue: 0) if path.isReadable { permissions.formUnion(.Read) } if path.isWritable { permissions.formUnion(.Write) } if path.isExecutable { permissions.formUnion(.Execute) } self = permissions } /// Creates a set of permissions for `file`. /// /// - Parameter file: The file to create a set of persmissions for. public init<Data: DataType>(forFile file: File<Data>) { self.init(forPath: file.path) } }
a96a98ddde2be6a964481a49a2e46fa4
35.455556
83
0.644621
false
false
false
false
hectr/swift-idioms
refs/heads/master
Tests/IdiomsTests/ArrayToOptionSetTests.swift
mit
1
// Copyright (c) 2020 Hèctor Marquès Ranea // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import XCTest import Idioms final class ArrayToOptionSetTests: XCTestCase { struct AnyOptionSet: OptionSet, Equatable { static var allCases: [AnyOptionSet] { [.a, .b, .c] } static let a = AnyOptionSet(rawValue: 1 << 0) static let b = AnyOptionSet(rawValue: 1 << 1) static let c = AnyOptionSet(rawValue: 1 << 2) let rawValue: Int init(rawValue: Int) { guard rawValue == 0 || rawValue & (1 << 0) == (1 << 0) || rawValue & (1 << 1) == (1 << 1) || rawValue & (1 << 2) == (1 << 2) else { fatalError() } self.rawValue = rawValue } } func testToOptionSet() { let array: [AnyOptionSet] = [.b, .c] let result = array.toOptionSet() let expected = AnyOptionSet.c.union(.b) XCTAssertEqual(expected, result) } static var allTests = [ ("testToOptionSet", testToOptionSet), ] }
1fc07752a82ccef01e5d208235e278aa
35.389831
80
0.646018
false
true
false
false
cdmx/MiniMancera
refs/heads/master
miniMancera/View/OptionWhistlesVsZombies/Board/VOptionWhistlesVsZombiesBoardCell.swift
mit
1
import UIKit class VOptionWhistlesVsZombiesBoardCell:UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private weak var model:MOptionWhistlesVsZombiesBoardItemProtocol? private weak var collectionView:VCollection! private weak var imageView:UIImageView! private weak var labelTitle:UILabel! private weak var labelPrice:UILabel! private let kAlphaSelected:CGFloat = 0.2 private let kAlphaNotAvailable:CGFloat = 0.6 private let kAlphaNotSelected:CGFloat = 1 private let kImageHeight:CGFloat = 125 private let kTitleHeight:CGFloat = 13 private let kTitleTop:CGFloat = -10 private let kCoinHeight:CGFloat = 50 private let kCoinRight:CGFloat = -55 private let kCoinWidth:CGFloat = 45 private let kPriceTop:CGFloat = -3 private let kPriceWidth:CGFloat = 80 private let kScoreCellHeight:CGFloat = 26 private let kBorderWidth:CGFloat = 1 private let kCornerRadius:CGFloat = 7 override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear layer.borderWidth = kBorderWidth layer.cornerRadius = kCornerRadius layer.borderColor = UIColor.white.cgColor let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center self.imageView = imageView let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.textAlignment = NSTextAlignment.center labelTitle.font = UIFont.game(size:6) labelTitle.textColor = UIColor.white self.labelTitle = labelTitle let imageCoin:UIImageView = UIImageView() imageCoin.isUserInteractionEnabled = false imageCoin.translatesAutoresizingMaskIntoConstraints = false imageCoin.clipsToBounds = true imageCoin.contentMode = UIViewContentMode.center imageCoin.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardPrice") let labelPrice:UILabel = UILabel() labelPrice.isUserInteractionEnabled = false labelPrice.translatesAutoresizingMaskIntoConstraints = false labelPrice.backgroundColor = UIColor.clear labelPrice.textAlignment = NSTextAlignment.right labelPrice.font = UIFont.game(size:17) self.labelPrice = labelPrice let collectionView:VCollection = VCollection() collectionView.isUserInteractionEnabled = false collectionView.isScrollEnabled = false collectionView.bounces = false collectionView.delegate = self collectionView.dataSource = self collectionView.registerCell(cell:VOptionWhistlesVsZombiesBoardCellScore.self) self.collectionView = collectionView if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { flow.itemSize = CGSize( width:frame.width, height:kScoreCellHeight) } addSubview(imageCoin) addSubview(imageView) addSubview(labelTitle) addSubview(labelPrice) addSubview(collectionView) NSLayoutConstraint.topToTop( view:imageView, toView:self) NSLayoutConstraint.height( view:imageView, constant:kImageHeight) NSLayoutConstraint.equalsHorizontal( view:imageView, toView:self) NSLayoutConstraint.topToBottom( view:labelTitle, toView:imageView, constant:kTitleTop) NSLayoutConstraint.height( view:labelTitle, constant:kTitleHeight) NSLayoutConstraint.equalsHorizontal( view:labelTitle, toView:self) NSLayoutConstraint.topToBottom( view:imageCoin, toView:labelTitle) NSLayoutConstraint.height( view:imageCoin, constant:kCoinHeight) NSLayoutConstraint.rightToRight( view:imageCoin, toView:self, constant:kCoinRight) NSLayoutConstraint.width( view:imageCoin, constant:kCoinWidth) NSLayoutConstraint.topToBottom( view:labelPrice, toView:labelTitle, constant:kPriceTop) NSLayoutConstraint.height( view:labelPrice, constant:kCoinHeight) NSLayoutConstraint.rightToLeft( view:labelPrice, toView:imageCoin) NSLayoutConstraint.width( view:labelPrice, constant:kPriceWidth) NSLayoutConstraint.topToBottom( view:collectionView, toView:imageCoin) NSLayoutConstraint.bottomToBottom( view:collectionView, toView:self) NSLayoutConstraint.equalsHorizontal( view:collectionView, toView:self) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hoverAvailable() { if isSelected || isHighlighted { alpha = kAlphaSelected } else { alpha = kAlphaNotSelected } labelPrice.textColor = UIColor( red:0.972549019607843, green:0.905882352941176, blue:0.109803921568627, alpha:1) } private func hoverNotAvailable() { alpha = kAlphaNotAvailable labelPrice.textColor = UIColor.red } private func hover() { guard let model:MOptionWhistlesVsZombiesBoardItemProtocol = self.model else { hoverNotAvailable() return } let available:Bool = model.available if available { hoverAvailable() } else { hoverNotAvailable() } } private func modelAtIndex(index:IndexPath) -> MOptionWhistlesVsZombiesBoardScoreItem { let item:MOptionWhistlesVsZombiesBoardScoreItem = model!.score.items[index.item] return item } //MARK: public func config(model:MOptionWhistlesVsZombiesBoardItemProtocol) { self.model = model imageView.image = model.image labelTitle.text = model.title labelPrice.text = "\(model.price)" hover() collectionView.reloadData() } //MARK: collectionView delegate func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { guard let count:Int = model?.score.items.count else { return 0 } return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MOptionWhistlesVsZombiesBoardScoreItem = modelAtIndex(index:indexPath) let cell:VOptionWhistlesVsZombiesBoardCellScore = collectionView.dequeueReusableCell( withReuseIdentifier: VOptionWhistlesVsZombiesBoardCellScore.reusableIdentifier, for:indexPath) as! VOptionWhistlesVsZombiesBoardCellScore cell.config(model:item) return cell } func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool { return false } func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool { return false } }
690851187732ee8f76e718d678345e95
29.124555
150
0.624217
false
false
false
false
Knoxantropicen/Focus-iOS
refs/heads/master
Focus/PopUpViewController.swift
mit
1
// // PopUpViewController.swift // Focus // // Created by TianKnox on 2017/5/27. // Copyright © 2017年 TianKnox. All rights reserved. // import UIKit class PopUpViewController: UIViewController { static var popingUp = false var rowNum: Int = 0 @IBOutlet weak var viewFrame: UIView! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var descriptionText: UITextView! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var editButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5) viewFrame.backgroundColor = Style.popBackgroundColor descriptionText.backgroundColor = Style.cellBackgroundColor let textColor = Style.mainTextColor descriptionLabel.textColor = textColor descriptionText.textColor = textColor closeButton.setTitleColor(textColor, for: .normal) editButton.setTitleColor(textColor, for: .normal) descriptionLabel.text = Language.description closeButton.setTitle(Language.close, for: .normal) editButton.setTitle(Language.edit, for: .normal) let tapGesture = UITapGestureRecognizer(target: self, action:#selector(hideKeyboard)) view.addGestureRecognizer(tapGesture) self.showAnimate() } func showAnimate() { PopUpViewController.popingUp = true descriptionText.text = DoneTableViewController.descriptions[rowNum] if descriptionText.text == Language.englishEditModel && !Language.EnglishLanguage { descriptionText.text = Language.chineseEditModel } else if descriptionText.text == Language.chineseEditModel && Language.EnglishLanguage { descriptionText.text = Language.englishEditModel } if descriptionText.text == Language.editModel { descriptionText.alpha = 0.3 } self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "disableSwipe"), object: nil) } func hideKeyboard() { if descriptionText.text == "" { descriptionText.text = Language.editModel descriptionText.alpha = 0.3 } view.endEditing(true) } @IBAction func EnableEdit(_ sender: UIButton) { descriptionText.backgroundColor = Style.editTextColor descriptionText.isEditable = true descriptionText.becomeFirstResponder() descriptionText.alpha = 1 if descriptionText.text == Language.editModel { descriptionText.selectedTextRange = descriptionText.textRange(from: descriptionText.beginningOfDocument, to: descriptionText.endOfDocument) } else { descriptionText.selectedRange = NSRange(location: descriptionText.text.lengthOfBytes(using: .utf8), length: 0) } } @IBAction func closePopUp(_ sender: UIButton) { descriptionText.isEditable = false DoneTableViewController.descriptions[rowNum] = descriptionText.text removeAnimate() } func removeAnimate() { UIView.animate(withDuration: 0.25, animations: { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 }, completion:{(finished : Bool) in if (finished) { self.view.removeFromSuperview() } self.descriptionText.backgroundColor = UIColor(colorLiteralRed: 245/255, green: 245/255, blue: 245/255, alpha: 1) }) NotificationCenter.default.post(name: NSNotification.Name(rawValue: "enableSwipe"), object: nil) PopUpViewController.popingUp = false } }
5aa8236917c86313a002db74388aad7d
35.972727
151
0.652324
false
false
false
false
CCRogerWang/ReactiveWeatherExample
refs/heads/master
10-combining-operators-in-practice/final/OurPlanet/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift
apache-2.0
11
// // Observable+Creation.swift // RxSwift // // Created by Krunoslav Zaher on 3/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation extension Observable { // MARK: create /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> { return AnonymousObservable(subscribe) } // MARK: empty /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence with no elements. */ public static func empty() -> Observable<E> { return Empty<E>() } // MARK: never /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence whose observers will never get called. */ public static func never() -> Observable<E> { return Never() } // MARK: just /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: E) -> Observable<E> { return Just(element: element) } /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - parameter: Scheduler to send the single element on. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable<E> { return JustScheduled(element: element, scheduler: scheduler) } // MARK: fail /** Returns an observable sequence that terminates with an `error`. - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: The observable sequence that terminates with specified error. */ public static func error(_ error: Swift.Error) -> Observable<E> { return Error(error: error) } // MARK: of /** This method creates a new Observable instance with a variable number of elements. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription. - returns: The observable sequence whose elements are pulled from the given arguments. */ public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> { return ObservableSequence(elements: elements, scheduler: scheduler) } // MARK: defer /** Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () throws -> Observable<E>) -> Observable<E> { return Deferred(observableFactory: observableFactory) } /** Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to run the loop send out observer messages. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter initialState: Initial state. - parameter condition: Condition to terminate generation (upon returning `false`). - parameter iterate: Iteration step function. - parameter scheduler: Scheduler on which to run the generator loop. - returns: The generated sequence. */ public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable<E> { return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) } /** Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) - parameter element: Element to repeat. - parameter scheduler: Scheduler to run the producer loop on. - returns: An observable sequence that repeats the given element infinitely. */ public static func repeatElement(_ element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> { return RepeatElement(element: element, scheduler: scheduler) } /** Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) - parameter resourceFactory: Factory function to obtain a resource object. - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ public static func using<R: Disposable>(_ resourceFactory: @escaping () throws -> R, observableFactory: @escaping (R) throws -> Observable<E>) -> Observable<E> { return Using(resourceFactory: resourceFactory, observableFactory: observableFactory) } } extension Observable where Element : SignedInteger { /** Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) - parameter start: The value of the first integer in the sequence. - parameter count: The number of sequential integers to generate. - parameter scheduler: Scheduler to run the generator loop on. - returns: An observable sequence that contains a range of sequential integral numbers. */ public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> { return RangeProducer<E>(start: start, count: count, scheduler: scheduler) } } extension Observable { /** Converts an array to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> { return ObservableSequence(elements: array, scheduler: scheduler) } /** Converts a sequence to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from<S: Sequence>(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> where S.Iterator.Element == E { return ObservableSequence(elements: sequence, scheduler: scheduler) } /** Converts a optional to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter optional: Optional element in the resulting observable sequence. - returns: An observable sequence containing the wrapped value or not from given optional. */ public static func from(_ optional: E?) -> Observable<E> { return ObservableOptional(optional: optional) } /** Converts a optional to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter optional: Optional element in the resulting observable sequence. - parameter: Scheduler to send the optional element on. - returns: An observable sequence containing the wrapped value or not from given optional. */ public static func from(_ optional: E?, scheduler: ImmediateSchedulerType) -> Observable<E> { return ObservableOptionalScheduled(optional: optional, scheduler: scheduler) } }
67fd3e3b8c45b88951abe16df43c82c9
42.54386
213
0.721293
false
false
false
false
MaartenBrijker/project
refs/heads/back
project/External/AudioKit-master/AudioKit/Common/Nodes/Effects/Filters/Low Shelf Parametric Equalizer Filter/AKLowShelfParametricEqualizerFilter.swift
apache-2.0
1
// // AKLowShelfParametricEqualizerFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This is an implementation of Zoelzer's parametric equalizer filter. /// /// - parameter input: Input node to process /// - parameter cornerFrequency: Corner frequency. /// - parameter gain: Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response. /// - parameter q: Q of the filter. sqrt(0.5) is no resonance. /// public class AKLowShelfParametricEqualizerFilter: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKLowShelfParametricEqualizerFilterAudioUnit? internal var token: AUParameterObserverToken? private var cornerFrequencyParameter: AUParameter? private var gainParameter: AUParameter? private var qParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet(newValue) { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Corner frequency. public var cornerFrequency: Double = 1000 { willSet(newValue) { if cornerFrequency != newValue { if internalAU!.isSetUp() { cornerFrequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.cornerFrequency = Float(newValue) } } } } /// Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response. public var gain: Double = 1.0 { willSet(newValue) { if gain != newValue { if internalAU!.isSetUp() { gainParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.gain = Float(newValue) } } } } /// Q of the filter. sqrt(0.5) is no resonance. public var q: Double = 0.707 { willSet(newValue) { if q != newValue { if internalAU!.isSetUp() { qParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.q = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this equalizer node /// /// - parameter input: Input node to process /// - parameter cornerFrequency: Corner frequency. /// - parameter gain: Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response. /// - parameter q: Q of the filter. sqrt(0.5) is no resonance. /// public init( _ input: AKNode, cornerFrequency: Double = 1000, gain: Double = 1.0, q: Double = 0.707) { self.cornerFrequency = cornerFrequency self.gain = gain self.q = q var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x70657131 /*'peq1'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKLowShelfParametricEqualizerFilterAudioUnit.self, asComponentDescription: description, name: "Local AKLowShelfParametricEqualizerFilter", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKLowShelfParametricEqualizerFilterAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } cornerFrequencyParameter = tree.valueForKey("cornerFrequency") as? AUParameter gainParameter = tree.valueForKey("gain") as? AUParameter qParameter = tree.valueForKey("q") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.cornerFrequencyParameter!.address { self.cornerFrequency = Double(value) } else if address == self.gainParameter!.address { self.gain = Double(value) } else if address == self.qParameter!.address { self.q = Double(value) } } } internalAU?.cornerFrequency = Float(cornerFrequency) internalAU?.gain = Float(gain) internalAU?.q = Float(q) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
05454a9de0d5b95afe0d4bd5c24fe7e6
34.52795
134
0.603147
false
false
false
false
richardpiazza/XCServerCoreData
refs/heads/master
Sources/StatsBreakdown.swift
mit
1
import Foundation import CoreData import CodeQuickKit import XCServerAPI public class StatsBreakdown: NSManagedObject { public func update(withStatsBreakdown breakdown: XCSStatsSummary) { self.sum = breakdown.sum as NSNumber? self.count = breakdown.count as NSNumber? self.min = breakdown.min as NSNumber? self.max = breakdown.max as NSNumber? self.avg = breakdown.avg as NSNumber? self.stdDev = breakdown.stdDev as NSNumber? } }
966454d07f65c1b4f2e2cbe2b612f647
29.75
71
0.705285
false
false
false
false
wangyuanou/Coastline
refs/heads/master
Coastline/Paint/BezierPath+Sharp.swift
mit
1
// // BezierPath+Sharp.swift // Coastline // // Created by 王渊鸥 on 2017/4/6. // Copyright © 2017年 王渊鸥. All rights reserved. // import UIKit public extension UIBezierPath { public enum Sharp { case triUp case triDown case triLeft case triRight case rect case diamond4 case diamond5 case cycle case pantagon case hexagonH case hexagonV case star4 case star5 case arrowUp case arrowDown case arrowLeft case arrowRight case directUp case directDown case directLeft case directRight } // public static func symbol(sharp:Sharp, inRect:CGRect, controlOffset:CGFloat?, controlWidth:CGFloat?) -> UIBezierPath { // switch sharp { // case .triUp: // let p = UIBezierPath() // p.move(inRect.left, inRect.bottom) // .line(inRect.centerH, inRect.top) // .line(inRect.right, inRect.bottom) // .close() // return p // case .triDown: // let p = UIBezierPath() // p.move(inRect.left, inRect.top) // .line(inRect.centerH, inRect.bottom) // .line(inRect.right, inRect.top) // .close() // return p // case .triLeft: // let p = UIBezierPath() // p.move(inRect.left, inRect.centerV) // .line(inRect.right, inRect.top) // .line(inRect.right, inRect.bottom) // .close() // return p // case .triRight: // let p = UIBezierPath() // p.move(inRect.left, inRect.top) // .line(inRect.right, inRect.centerV) // .line(inRect.left, inRect.bottom) // .close() // return p // case .rect: // return UIBezierPath(rect: inRect) // case .cycle: // return UIBezierPath(ovalIn: inRect) // case .diamond4: // let p = UIBezierPath() // p.move(inRect.centerH, inRect.top) // .line(inRect.right, inRect.centerV) // .line(inRect.centerH, inRect.bottom) // .line(inRect.left, inRect.centerV) // .close() // return p // } // } }
477a807a750dd41947b5d8317055c61a
21.775
121
0.648189
false
false
false
false
overtake/TelegramSwift
refs/heads/master
packages/GraphUI/Sources/Charts/views/RangeChartView.swift
gpl-2.0
1
// // RangeChartView.swift // Graph // // Created by Mikhail Filimonov on 24.02.2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import GraphCore private enum Constants { static let cropIndocatorLineWidth: CGFloat = 1 static let markerSelectionRange: CGFloat = 25 static let defaultMinimumRangeDistance: CGFloat = 0.05 static let titntAreaWidth: CGFloat = 10 static let horizontalContentMargin: CGFloat = 16 static let cornerRadius: CGFloat = 5 } class RangeChartView: Control { private enum Marker { case lower case upper case center } public var lowerBound: CGFloat = 0 { didSet { needsLayout = true } } public var upperBound: CGFloat = 1 { didSet { needsLayout = true } } public var selectionColor: NSColor = .blue public var defaultColor: NSColor = .lightGray public var minimumRangeDistance: CGFloat = Constants.defaultMinimumRangeDistance private let lowerBoundTintView = View() private let upperBoundTintView = View() private let cropFrameView = TransparentImageView() private var selectedMarker: Marker? private var selectedMarkerHorizontalOffet: CGFloat = 0 private var isBoundCropHighlighted: Bool = false private var isRangePagingEnabled: Bool = false public let chartView = ChartView(frame: NSZeroRect) var layoutMargins: NSEdgeInsets required init(frame: CGRect) { layoutMargins = NSEdgeInsets(top: Constants.cropIndocatorLineWidth, left: Constants.horizontalContentMargin, bottom: Constants.cropIndocatorLineWidth, right: Constants.horizontalContentMargin) super.init(frame: frame) self.setup() } func setup() { // isMultipleTouchEnabled = false chartView.chartInsets = .init() chartView.backgroundColor = .clear cropFrameView.wantsLayer = true addSubview(chartView) lowerBoundTintView.isEventLess = true upperBoundTintView.isEventLess = true addSubview(lowerBoundTintView) addSubview(upperBoundTintView) addSubview(cropFrameView) cropFrameView.isEnabled = false cropFrameView.imageScaling = .scaleAxesIndependently cropFrameView.layer?.contentsGravity = .resize //cropFrameView.isUserInteractionEnabled = false chartView.userInteractionEnabled = false chartView.isEventLess = true lowerBoundTintView.userInteractionEnabled = false upperBoundTintView.userInteractionEnabled = false chartView.layer?.cornerRadius = 5 upperBoundTintView.layer?.cornerRadius = 5 lowerBoundTintView.layer?.cornerRadius = 5 chartView.layer?.masksToBounds = true upperBoundTintView.layer?.masksToBounds = true lowerBoundTintView.layer?.masksToBounds = true layoutViews() } public var rangeDidChangeClosure: ((ClosedRange<CGFloat>) -> Void)? public var touchedOutsideClosure: (() -> Void)? required init?(coder aDecoder: NSCoder) { fatalError("not supported") } func setRangePaging(enabled: Bool, minimumSize: CGFloat) { isRangePagingEnabled = enabled minimumRangeDistance = minimumSize } func setRange(_ range: ClosedRange<CGFloat>, animated: Bool) { View.perform(animated: animated) { self.lowerBound = range.lowerBound self.upperBound = range.upperBound self.needsLayout = true } } override func layout() { super.layout() layoutViews() } override var isEnabled: Bool { get { return super.isEnabled } set { if newValue == false { selectedMarker = nil } super.isEnabled = newValue } } // MARK: - Touches override func mouseDown(with event: NSEvent) { super.mouseDown(with: event) guard isEnabled else { return } let point = self.convert(event.locationInWindow, from: nil) if abs(locationInView(for: upperBound) - point.x + Constants.markerSelectionRange / 2) < Constants.markerSelectionRange { selectedMarker = .upper selectedMarkerHorizontalOffet = point.x - locationInView(for: upperBound) isBoundCropHighlighted = true } else if abs(locationInView(for: lowerBound) - point.x - Constants.markerSelectionRange / 2) < Constants.markerSelectionRange { selectedMarker = .lower selectedMarkerHorizontalOffet = point.x - locationInView(for: lowerBound) isBoundCropHighlighted = true } else if point.x > locationInView(for: lowerBound) && point.x < locationInView(for: upperBound) { selectedMarker = .center selectedMarkerHorizontalOffet = point.x - locationInView(for: lowerBound) isBoundCropHighlighted = true } else { selectedMarker = nil return } // sendActions(for: .touchDown) } override func mouseDragged(with event: NSEvent) { super.mouseDragged(with: event) guard let selectedMarker = selectedMarker else { return } let point = self.convert(event.locationInWindow, from: nil) let horizontalPosition = point.x - selectedMarkerHorizontalOffet let fraction = fractionFor(offsetX: horizontalPosition) updateMarkerOffset(selectedMarker, fraction: fraction) } override func mouseUp(with event: NSEvent) { super.mouseUp(with: event) guard isEnabled else { return } guard let selectedMarker = selectedMarker else { touchedOutsideClosure?() return } let point = self.convert(event.locationInWindow, from: nil) let horizontalPosition = point.x - selectedMarkerHorizontalOffet let fraction = fractionFor(offsetX: horizontalPosition) updateMarkerOffset(selectedMarker, fraction: fraction) self.selectedMarker = nil self.isBoundCropHighlighted = false rangeDidChangeClosure?(lowerBound...upperBound) } } private extension RangeChartView { var contentFrame: CGRect { return CGRect(x: layoutMargins.right, y: layoutMargins.top, width: (bounds.width - layoutMargins.right - layoutMargins.left), height: bounds.height - layoutMargins.top - layoutMargins.bottom) } func locationInView(for fraction: CGFloat) -> CGFloat { return contentFrame.minX + contentFrame.width * fraction } func locationInView(for fraction: Double) -> CGFloat { return locationInView(for: CGFloat(fraction)) } func fractionFor(offsetX: CGFloat) -> CGFloat { guard contentFrame.width > 0 else { return 0 } return crop(0, CGFloat((offsetX - contentFrame.minX ) / contentFrame.width), 1) } private func updateMarkerOffset(_ marker: Marker, fraction: CGFloat, notifyDelegate: Bool = true) { let fractionToCount: CGFloat if isRangePagingEnabled { guard let minValue = stride(from: CGFloat(0.0), through: CGFloat(1.0), by: minimumRangeDistance).min(by: { abs($0 - fraction) < abs($1 - fraction) }) else { return } fractionToCount = minValue } else { fractionToCount = fraction } switch marker { case .lower: lowerBound = min(fractionToCount, upperBound - minimumRangeDistance) case .upper: upperBound = max(fractionToCount, lowerBound + minimumRangeDistance) case .center: let distance = upperBound - lowerBound lowerBound = max(0, min(fractionToCount, 1 - distance)) upperBound = lowerBound + distance } if notifyDelegate { rangeDidChangeClosure?(lowerBound...upperBound) } self.layoutIfNeeded(animated: true) } // MARK: - Layout func layoutViews() { cropFrameView.frame = CGRect(x: locationInView(for: lowerBound), y: contentFrame.minY - Constants.cropIndocatorLineWidth, width: locationInView(for: upperBound) - locationInView(for: lowerBound), height: contentFrame.height + Constants.cropIndocatorLineWidth * 2) if chartView.frame != contentFrame { chartView.frame = contentFrame } lowerBoundTintView.frame = CGRect(x: contentFrame.minX, y: contentFrame.minY, width: max(0, locationInView(for: lowerBound) - contentFrame.minX + Constants.titntAreaWidth), height: contentFrame.height) upperBoundTintView.frame = CGRect(x: locationInView(for: upperBound) - Constants.titntAreaWidth, y: contentFrame.minY, width: max(0, contentFrame.maxX - locationInView(for: upperBound) + Constants.titntAreaWidth), height: contentFrame.height) } } extension RangeChartView: ChartThemeContainer { func apply(theme: ChartTheme, strings: ChartStrings, animated: Bool) { let closure = { self.lowerBoundTintView.backgroundColor = theme.rangeViewTintColor self.upperBoundTintView.backgroundColor = theme.rangeViewTintColor } let rangeCropImage = theme.rangeCropImage rangeCropImage?.resizingMode = .stretch rangeCropImage?.capInsets = NSEdgeInsets(top: 15, left: 15, bottom: 15, right: 15) self.cropFrameView.setImage(rangeCropImage, animated: animated) // self.chartView.apply(theme: theme, animated: animated) if animated { View.perform(animated: true, animations: closure) } else { closure() } } }
359269ea7b13da67b3c5420e98e9e984
34.268456
177
0.611227
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
refs/heads/master
BridgeAppSDK/SBAWebViewController.swift
bsd-3-clause
1
// // SBAWebViewController.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit open class SBAWebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! open var url: URL? open var html: String? fileprivate var _webviewLoaded = false open override func viewDidLoad() { super.viewDidLoad() if (webView == nil) { self.view.backgroundColor = UIColor.white let subview = UIWebView(frame: self.view.bounds) self.view.addSubview(subview) subview.constrainToFillSuperview() subview.delegate = self subview.dataDetectorTypes = .all subview.backgroundColor = UIColor.white self.webView = subview } } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if (!_webviewLoaded) { _webviewLoaded = true if let url = self.url { let request = URLRequest(url: url) webView.loadRequest(request) } else if let html = self.html { webView.loadHTMLString(html, baseURL: nil) } } } open func dismissViewController() { self.dismiss(animated: true, completion: nil) } // MARK: - UIWebViewDelegate open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.url , (navigationType == .linkClicked) { UIApplication.shared.openURL(url) return false } else { return true } } }
d19306a6fb3308eddc744e58641fe4a7
36.516484
135
0.67604
false
false
false
false
WeHUD/app
refs/heads/master
weHub-ios/Gzone_App/Gzone_App/GlobalAlerts.swift
bsd-3-clause
1
// // GlobalAlerts.swift // Gzone_App // // Created by Tracy Sablon on 03/07/2017. // Copyright © 2017 Tracy Sablon. All rights reserved. // import UIKit extension UIViewController { func locationServiceDisabledAlert (title: String, message: String ) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } func networkServiceDisabledAlert () { let alertController = UIAlertController(title: "No network", message: "Please check your network.", preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } func emptyFields (title: String, message: String ) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } func followUserAlert (user: User ) { let alertController = UIAlertController(title: "Want to know more about \(user.username) ?", message: "", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "View Profile", style: UIAlertActionStyle.default, handler: { _ in let VC = self.storyboard?.instantiateViewController(withIdentifier: "ProfilUser") as! ProfilUserViewController //alertController.user = self.connectedUser VC.user = user self.navigationController?.pushViewController(VC, animated: true) })) alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } func httpErrorStatusAlert (status: Int, errorType: String){ var title : String = "" var message : String = "" switch status { case 400: // Bad Request if errorType == "invalid_client" { title = "Login failed" message = "Please provide username and password." } else if errorType == "invalid_grant"{ title = "Login failed" message = "Please check your credentials." } else { title = "Error" message = "The request could not be permormed." } break case 500: // Internal Server Error title = "Error" message = "Sorry we've had a server error.Please try again." break default: break } let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } }
025101ecc480a982f8e55251a25daeb4
36.053191
137
0.602354
false
false
false
false
soapyigu/Swift30Projects
refs/heads/master
Project 08 - SimpleRSSReader/SimpleRSSReader/NewsTableViewController.swift
apache-2.0
1
// // NewsTableViewController.swift // SimpleRSSReader // // Copyright (c) 2015 AppCoda. All rights reserved. // import UIKit class NewsTableViewController: UITableViewController { fileprivate let feedParser = FeedParser() fileprivate let feedURL = "http://www.apple.com/main/rss/hotnews/hotnews.rss" fileprivate var rssItems: [(title: String, description: String, pubDate: String)]? fileprivate var cellStates: [CellState]? override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 140 tableView.rowHeight = UITableView.automaticDimension tableView.separatorStyle = UITableViewCell.SeparatorStyle.singleLine feedParser.parseFeed(feedURL: feedURL) { [weak self] rssItems in self?.rssItems = rssItems self?.cellStates = Array(repeating: .collapsed, count: rssItems.count) DispatchQueue.main.async { self?.tableView.reloadSections(IndexSet(integer: 0), with: .none) } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let rssItems = rssItems else { return 0 } return rssItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NewsTableViewCell if let item = rssItems?[indexPath.row] { (cell.titleLabel.text, cell.descriptionLabel.text, cell.dateLabel.text) = (item.title, item.description, item.pubDate) if let cellState = cellStates?[indexPath.row] { cell.descriptionLabel.numberOfLines = cellState == .expanded ? 0: 4 } } return cell } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath) as! NewsTableViewCell tableView.beginUpdates() cell.descriptionLabel.numberOfLines = cell.descriptionLabel.numberOfLines == 4 ? 0 : 4 cellStates?[indexPath.row] = cell.descriptionLabel.numberOfLines == 4 ? .collapsed : .expanded tableView.endUpdates() } }
abae68370af28f227e28b5e95ad7c9a4
31.472973
124
0.701623
false
false
false
false
Oscareli98/Moya
refs/heads/master
Demo/Pods/RxSwift/RxSwift/RxSwift/Schedulers/DispatchQueueScheduler.swift
mit
2
// // DispatchQueueScheduler.swift // Rx // // Created by Krunoslav Zaher on 2/8/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation public enum DispatchQueueSchedulerPriority { case High case Default case Low } // This is a scheduler that wraps dispatch queue. // It can wrap both serial and concurrent dispatch queues. // // It is extemely important that this scheduler is serial, because // certain operator perform optimizations that rely on that property. // // Because there is no way of detecting is passed dispatch queue serial or // concurrent, for every queue that is being passed, worst case (concurrent) // will be assumed, and internal serial proxy dispatch queue will be created. // // This scheduler can also be used with internal serial queue alone. // In case some customization need to be made on it before usage, // internal serial queue can be customized using `serialQueueConfiguration` // callback. // public class DispatchQueueScheduler: Scheduler, PeriodicScheduler { public typealias TimeInterval = NSTimeInterval public typealias Time = NSDate private let serialQueue : dispatch_queue_t public var now : NSDate { get { return NSDate() } } // leeway for scheduling timers var leeway: Int64 = 0 init(serialQueue: dispatch_queue_t) { self.serialQueue = serialQueue } // Creates new serial queue named `name` for internal scheduler usage public convenience init(internalSerialQueueName: String) { self.init(internalSerialQueueName: internalSerialQueueName, serialQueueConfiguration: { _ -> Void in }) } // Creates new serial queue named `name` for internal scheduler usage public convenience init(internalSerialQueueName: String, serialQueueConfiguration: (dispatch_queue_t) -> Void) { let queue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) serialQueueConfiguration(queue) self.init(serialQueue: queue) } public convenience init(queue: dispatch_queue_t, internalSerialQueueName: String) { let serialQueue = dispatch_queue_create(internalSerialQueueName, DISPATCH_QUEUE_SERIAL) dispatch_set_target_queue(serialQueue, queue) self.init(serialQueue: serialQueue) } // Convenience init for scheduler that wraps one of the global concurrent dispatch queues. // // DISPATCH_QUEUE_PRIORITY_DEFAULT // DISPATCH_QUEUE_PRIORITY_HIGH // DISPATCH_QUEUE_PRIORITY_LOW public convenience init(globalConcurrentQueuePriority: DispatchQueueSchedulerPriority) { self.init(globalConcurrentQueuePriority: globalConcurrentQueuePriority, internalSerialQueueName: "rx.global_dispatch_queue.serial.\(globalConcurrentQueuePriority)") } public convenience init(globalConcurrentQueuePriority: DispatchQueueSchedulerPriority, internalSerialQueueName: String) { var priority: Int = 0 switch globalConcurrentQueuePriority { case .High: priority = DISPATCH_QUEUE_PRIORITY_HIGH case .Default: priority = DISPATCH_QUEUE_PRIORITY_DEFAULT case .Low: priority = DISPATCH_QUEUE_PRIORITY_LOW } self.init(queue: dispatch_get_global_queue(priority, UInt(0)), internalSerialQueueName: internalSerialQueueName) } class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 { return Int64(timeInterval * Double(NSEC_PER_SEC)) } class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t { return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval)) } public final func schedule<StateType>(state: StateType, action: (/*ImmediateScheduler,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> { return self.scheduleInternal(state, action: action) } func scheduleInternal<StateType>(state: StateType, action: (/*ImmediateScheduler,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> { let cancel = SingleAssignmentDisposable() dispatch_async(self.serialQueue) { if cancel.disposed { return } _ = ensureScheduledSuccessfully(action(/*self,*/ state).map { disposable in cancel.disposable = disposable }) } return success(cancel) } public final func scheduleRelative<StateType>(state: StateType, dueTime: NSTimeInterval, action: (/*Scheduler<NSTimeInterval, NSDate>,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> { let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.serialQueue) let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime) let compositeDisposable = CompositeDisposable() dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0) dispatch_source_set_event_handler(timer, { if compositeDisposable.disposed { return } ensureScheduledSuccessfully(action(/*self,*/ state).map { disposable in compositeDisposable.addDisposable(disposable) }) }) dispatch_resume(timer) compositeDisposable.addDisposable(AnonymousDisposable { dispatch_source_cancel(timer) }) return success(compositeDisposable) } public func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> RxResult<Disposable> { let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.serialQueue) let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter) let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period) var timerState = state let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval) dispatch_source_set_timer(timer, initial, validDispatchInterval, 0) let cancel = AnonymousDisposable { dispatch_source_cancel(timer) } dispatch_source_set_event_handler(timer, { if cancel.disposed { return } timerState = action(timerState) }) dispatch_resume(timer) return success(cancel) } }
f30a5a95b6b4b9fe08a2372fda6e3ca9
38.619048
202
0.680391
false
false
false
false
JornWu/ZhiBo_Swift
refs/heads/master
ZhiBo_Swift/Class/Home/ViewController/LoveView.swift
mit
1
// // LoveView.swift // ZhiBo_Swift // // Created by JornWu on 2017/3/2. // Copyright © 2017年 Jorn.Wu([email protected]). All rights reserved. // import UIKit class LoveView: UIView { private var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) self.setupImageView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupImageView() { imageView = UIImageView() //imageView.backgroundColor = UIColor.gray imageView.image = #imageLiteral(resourceName: "no_follow_250x247") self.addSubview(imageView) imageView.snp.makeConstraints { (make) in //make.top.left.equalTo(100) make.size.equalTo(CGSize(width: 300, height: 350)) make.centerX.equalToSuperview() make.top.equalTo(40) } let tipsLB = UILabel() tipsLB.text = "你关注的主播还没有开播" tipsLB.textColor = UIColor.gray tipsLB.textAlignment = .center tipsLB.font = UIFont.systemFont(ofSize: 20) self.addSubview(tipsLB) tipsLB.snp.makeConstraints { (make) in make.top.equalTo(imageView.snp.bottom) make.left.equalTo(30) make.right.equalTo(-30) make.height.equalTo(50) } let toWatchHotLiveBtn = UIButton() self.addSubview(toWatchHotLiveBtn) toWatchHotLiveBtn.snp.makeConstraints { (make) in make.top.equalTo(tipsLB.snp.bottom).offset(10) make.left.equalTo(40) make.right.equalTo(-40) make.height.equalTo(50) } toWatchHotLiveBtn.setTitle("去看看当前热门的直播", for: .normal) toWatchHotLiveBtn.setTitleColor(THEME_COLOR, for: .normal) toWatchHotLiveBtn.layer.cornerRadius = 25 ///height = 50 toWatchHotLiveBtn.layer.borderWidth = 2 toWatchHotLiveBtn.layer.borderColor = THEME_COLOR.cgColor } }
c52f86f1fa90d246cafcb48247ef1538
30.640625
74
0.613827
false
false
false
false
jeevanRao7/Swift_Playgrounds
refs/heads/master
Swift Playgrounds/Data Structures/Single LinkedList.playground/Contents.swift
mit
1
/* * Singly linked list (Generic) implementation. * Actions : Head & Trail, Print, isEmpty, Total, Append, * References : //https://www.journaldev.com/20995/swift-linked-list //https://itnext.io/linkedlist-in-swift-code-a-linkedlist-data-structure-in-swift-playgrounds-97fe2ed9b8f1 */ class Node { var value:Int? var next:Node? //Note: do not consider 'weak' reference init(value:Int) { self.value = value } } class LinkedList { var head:Node? // head is nil when list is empty public var isEmpty:Bool { return head == nil } public var first:Node? { return head } public var last: Node? { guard var node = head else { return nil } while let next = node.next { node = next } return node } public var count: Int { guard var node = head else { return 0 } var count = 1 while let next = node.next { node = next count += 1 } return count } public func node(atIndex index: Int) -> Node { if index == 0 { return head! } else { var node = head!.next for _ in 1..<index { node = node?.next if node == nil { // break } } return node! } } //MARK:- Print nodes public func printList() { var current:Node? = first while current != nil { print("\t \(String(describing: current!.value!)) \t") current = current?.next } } //MARK:- Insert node //To add a new Node to the END of the list public func append(value:Int) { let newNode = Node(value: value) //When the next reference of h is nil, it means we are at the end of the LinkedList. if let lastNode = last { lastNode.next = newNode } else{ head = newNode } } //To insert Node at a POSTION public func insert(value:Int, at pos:Int){ let newNode = Node(value: value) if pos == 0 { newNode.next = head head = newNode } else { var previous = head var current = head //travel until position found for _ in 0..<pos { previous = current current = current?.next } newNode.next = previous?.next previous?.next = newNode } } //MARK:- Delete nodes public func remove(at index: Int) { if (head == nil) { return } var temp = head // if head to be removed if index == 0{ head = temp?.next return } // Find previous node of the node to be deleted for _ in 0..<index-1 { temp = temp?.next } // If position is more than number of nodes if temp == nil || temp?.next == nil { return } // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted let next = temp?.next?.next temp?.next = next } } let ll = LinkedList() ll.append(value: 3) ll.append(value: 4) ll.append(value: 5) ll.insert(value: 1, at: 0) ll.insert(value: 2, at: 1) ll.printList() debugPrint("Total nodes \(ll.count)") ll.remove(at: 2) ll.printList() debugPrint("Total nodes \(ll.count)")
5119cdbb4393e660922035a8069cc528
22.61039
107
0.494224
false
false
false
false
timd/MactsAsBeacon
refs/heads/master
ActsAsBeacon/CreateBeacopnViewControllerVM.swift
mit
1
// // CreateBeacopnViewControllerVM.swift // MactsAsBeacon // // Created by Philipp Weiß on 10/03/2017. // import Foundation import CoreBluetooth import IOBluetooth protocol CreateBeaconViewControllerVMProtocol: class { var major: String { get set } var power: String { get set } var uuid: String { get set } var minor: String { get set } var isActive: Bool { get } func pressedAdvertiseButton() } class CreateBeaconViewControllerVM: NSObject, CreateBeaconViewControllerVMProtocol { private var beacon: IBeacon private var peripheralManager: CBPeripheralManager? private let userDefaults: UserDefaults var isActive: Bool = false init(with beacon: IBeacon) { self.beacon = beacon self.userDefaults = UserDefaults() super.init() peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } var major: String { get { return beacon.major } set { userDefaults.major = newValue beacon.major = newValue } } var power: String { get { return beacon.power } set { userDefaults.power = newValue beacon.power = newValue } } var uuid: String { get { return beacon.uuid } set { userDefaults.uuid = newValue beacon.uuid = newValue } } var minor: String { get { return beacon.minor } set { userDefaults.minor = newValue beacon.minor = newValue } } func pressedAdvertiseButton() { isActive = !isActive if isActive { let advertisement2 = advertisementData(beacon: beacon) peripheralManager?.startAdvertising(advertisement2) } else { peripheralManager?.stopAdvertising() } } private func advertisementData(beacon: IBeacon) -> [String: Data] { var result: [String: Data] = [:] var advertisementBytes = [CUnsignedChar](repeating: 0, count: 21) NSUUID(uuidString: beacon.uuid)!.getBytes(&advertisementBytes) advertisementBytes[16] = CUnsignedChar(UInt16(beacon.major)! >> 8) advertisementBytes[17] = CUnsignedChar(UInt16(beacon.major)! & 255) advertisementBytes[18] = CUnsignedChar(UInt16(beacon.minor)! >> 8) advertisementBytes[19] = CUnsignedChar(UInt16(beacon.minor)! & 255) advertisementBytes[20] = CUnsignedChar(bitPattern: Int8(beacon.power)!) let data = Data(bytes: advertisementBytes, count: 21) result[IBeacon.advertisementKey] = data return result } } extension CreateBeaconViewControllerVM: CBPeripheralManagerDelegate { func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { } }
006d3e892d4e65466d9b8c9f8f5f246e
23.567797
84
0.61573
false
false
false
false
duliodenis/hoodz
refs/heads/master
Hoodz/Hoodz/DataService.swift
mit
1
// // DataService.swift // Hoodz // // Created by Dulio Denis on 11/21/15. // Copyright © 2015 Dulio Denis. All rights reserved. // import Foundation import UIKit class DataService { static let instance = DataService() let KEY_POSTS = "posts" private var _loadedPosts = [Post]() var loadedPosts: [Post] { return _loadedPosts } func savePosts() { let postsData = NSKeyedArchiver.archivedDataWithRootObject(_loadedPosts) NSUserDefaults.standardUserDefaults().setObject(postsData, forKey: KEY_POSTS) NSUserDefaults.standardUserDefaults().synchronize() } func loadPosts() { if let postsData = NSUserDefaults.standardUserDefaults().objectForKey(KEY_POSTS) as? NSData { if let postsArray = NSKeyedUnarchiver.unarchiveObjectWithData(postsData) as? [Post] { _loadedPosts = postsArray } } NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: "postsLoaded", object: nil)) } func saveImageAndCreatePath(image: UIImage) -> String { let imageData = UIImagePNGRepresentation(image) let imagePath = "image\(NSDate.timeIntervalSinceReferenceDate()).png" let fullPath = documentsPathForFilename(imagePath) imageData?.writeToFile(fullPath, atomically: true) return imagePath } func imageForPath(path: String) -> UIImage? { let fullPath = documentsPathForFilename(path) let image = UIImage(named: fullPath) return image } func addPost(post: Post) { _loadedPosts.append(post) savePosts() loadPosts() } func documentsPathForFilename(name: String) -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let fullPath = paths[0] as NSString return fullPath.stringByAppendingPathComponent(name) } }
46e9f32c7ea1466717bbb8230d49a715
28.895522
111
0.648352
false
false
false
false
JGiola/swift
refs/heads/main
test/Concurrency/unavailable_from_async.swift
apache-2.0
5
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -emit-module-path %t/UnavailableFunction.swiftmodule -module-name UnavailableFunction -warn-concurrency %S/Inputs/UnavailableFunction.swift // RUN: %target-swift-frontend -typecheck -verify -I %t %s // REQUIRES: concurrency import UnavailableFunction @available(SwiftStdlib 5.1, *) func okay() {} // expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}} @_unavailableFromAsync @available(SwiftStdlib 5.1, *) struct Foo { } // expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}} @_unavailableFromAsync @available(SwiftStdlib 5.1, *) extension Foo { } // expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}} @_unavailableFromAsync @available(SwiftStdlib 5.1, *) class Bar { // expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}} @_unavailableFromAsync deinit { } } // expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}} @_unavailableFromAsync @available(SwiftStdlib 5.1, *) actor Baz { } @available(SwiftStdlib 5.1, *) struct Bop { @_unavailableFromAsync(message: "Use Bop(a: Int) instead") init() {} // expected-note 4 {{'init()' declared here}} init(a: Int) { } } @available(SwiftStdlib 5.1, *) extension Bop { @_unavailableFromAsync func foo() {} // expected-note 4 {{'foo()' declared here}} @_unavailableFromAsync mutating func muppet() { } // expected-note 4 {{'muppet()' declared here}} } @_unavailableFromAsync @available(SwiftStdlib 5.1, *) func foo() {} // expected-note 4 {{'foo()' declared here}} @available(SwiftStdlib 5.1, *) func makeAsyncClosuresSynchronously(bop: inout Bop) -> (() async -> Void) { return { () async -> Void in // Unavailable methods _ = Bop() // expected-warning@:9{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}} _ = Bop(a: 32) bop.foo() // expected-warning@:9{{'foo' is unavailable from asynchronous contexts}} bop.muppet() // expected-warning@:9{{'muppet' is unavailable from asynchronous contexts}} unavailableFunction() // expected-warning@:5{{'unavailableFunction' is unavailable from asynchronous contexts}} noasyncFunction() // expected-warning@:5{{'noasyncFunction' is unavailable from asynchronous contexts}} // Can use them from synchronous closures _ = { Bop() }() _ = { bop.foo() }() _ = { bop.muppet() }() _ = { noasyncFunction() }() // Unavailable global function foo() // expected-warning{{'foo' is unavailable from asynchronous contexts}} // Okay function okay() } } @available(SwiftStdlib 5.1, *) @_unavailableFromAsync func asyncFunc() async { // expected-error{{asynchronous global function 'asyncFunc()' must be available from asynchronous contexts}} var bop = Bop(a: 32) _ = Bop() // expected-warning@:7{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}} bop.foo() // expected-warning@:7{{'foo' is unavailable from asynchronous contexts}} bop.muppet() // expected-warning@:7{{'muppet' is unavailable from asynchronous contexts}} unavailableFunction() // expected-warning@:3{{'unavailableFunction' is unavailable from asynchronous contexts}} noasyncFunction() // expected-warning@:3{{'noasyncFunction' is unavailable from asynchronous contexts}} // Unavailable global function foo() // expected-warning{{'foo' is unavailable from asynchronous contexts}} // Available function okay() _ = { () -> Void in // Check unavailable things inside of a nested synchronous closure _ = Bop() foo() bop.foo() bop.muppet() unavailableFunction() noasyncFunction() _ = { () async -> Void in // Check Unavailable things inside of a nested async closure foo() // expected-warning@:7{{'foo' is unavailable from asynchronous contexts}} bop.foo() // expected-warning@:11{{'foo' is unavailable from asynchronous contexts}} bop.muppet() // expected-warning@:11{{'muppet' is unavailable from asynchronous contexts}} _ = Bop() // expected-warning@:11{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}} unavailableFunction() // expected-warning@:7{{'unavailableFunction' is unavailable from asynchronous contexts}} noasyncFunction() // expected-warning@:7{{'noasyncFunction' is unavailable from asynchronous contexts}} } } _ = { () async -> Void in _ = Bop() // expected-warning@:9{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}} foo() // expected-warning@:5{{'foo' is unavailable from asynchronous contexts}} bop.foo() // expected-warning@:9{{'foo' is unavailable from asynchronous contexts}} bop.muppet() // expected-warning@:9{{'muppet' is unavailable from asynchronous contexts}} unavailableFunction() // expected-warning@:5{{'unavailableFunction' is unavailable from asynchronous contexts}} noasyncFunction() // expected-warning@:5{{'noasyncFunction' is unavailable from asynchronous contexts}} _ = { foo() bop.foo() _ = Bop() unavailableFunction() } } } // Parsing tests // expected-error@+2 {{expected declaration}} // expected-error@+1:24{{unknown option 'nope' for attribute '_unavailableFromAsync'}} @_unavailableFromAsync(nope: "almost right, but not quite") func blarp1() {} // expected-error@+2 {{expected declaration}} // expected-error@+1 {{expected ':' after label 'message'}} @_unavailableFromAsync(message; "almost right, but not quite") func blarp2() {} // expected-error@+1:31 {{'=' has been replaced with ':' in attribute arguments}}{{31-32=: }} @_unavailableFromAsync(message="almost right, but not quite") func blarp3() {} // expected-error@+2 {{expected declaration}} // expected-error@+1 {{expected string literal in '_unavailableFromAsync' attribute}} @_unavailableFromAsync(message: 32) func blarp4() {} // expected-error@+2 {{expected declaration}} // expected-error@+1 {{message cannot be an interpolated string}} @_unavailableFromAsync(message: "blarppy blarp \(31 + 10)") func blarp5() {} // expected-error@+1:48 {{expected ')' in '_unavailableFromAsync' attribute}}{{48-48=)}} @_unavailableFromAsync(message: "blarppy blarp" func blarp6() {}
2d906eec4e4ff064bc29a1205070daa4
38.114458
183
0.684583
false
false
false
false
wireapp/wire-ios-data-model
refs/heads/develop
Tests/Source/Model/Messages/ZMClientMessageTests+Location.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import CoreLocation @testable import WireDataModel class ClientMessageTests_Location: BaseZMMessageTests { func testThatItReturnsLocationMessageDataWhenPresent() throws { // given let (latitude, longitude): (Float, Float) = (48.53775, 9.041169) let (name, zoom) = ("Tuebingen, Deutschland", Int32(3)) let location = Location.with { $0.latitude = latitude $0.longitude = longitude $0.name = name $0.zoom = zoom } let message = GenericMessage(content: location) // when let clientMessage = ZMClientMessage(nonce: UUID(), managedObjectContext: uiMOC) try clientMessage.setUnderlyingMessage(message) // then let locationMessageData = clientMessage.locationMessageData XCTAssertNotNil(locationMessageData) XCTAssertEqual(locationMessageData?.latitude, latitude) XCTAssertEqual(locationMessageData?.longitude, longitude) XCTAssertEqual(locationMessageData?.name, name) XCTAssertEqual(locationMessageData?.zoomLevel, zoom) } func testThatItDoesNotReturnLocationMessageDataWhenNotPresent() { // given let clientMessage = ZMClientMessage(nonce: UUID(), managedObjectContext: uiMOC) // then XCTAssertNil(clientMessage.locationMessageData) } }
2e03292529d11a285fecedee20b33ed7
34.948276
87
0.697842
false
true
false
false
manavgabhawala/MGDocIt
refs/heads/master
MGDocIt/ObjectiveCNameAndInheritedType.swift
mit
1
// // ObjectiveCNameAndInheritedType.swift // MGDocIt // // Created by Manav Gabhawala on 18/08/15. // Copyright © 2015 Manav Gabhawala. All rights reserved. // import Foundation protocol ObjectiveCNameAndInheritedType : NameAndInheritedType, CXDocumentType { init(name: String, inheritedTypes: [String]) } extension ObjectiveCNameAndInheritedType { init(cursor: CXCursor, tokens: [MGCXToken], translationUnit tu: CXTranslationUnit) { var endOffset: UInt32 = 0 clang_getSpellingLocation(clang_getRangeEnd(clang_getCursorExtent(cursor)), nil, nil , nil, &endOffset) clang_visitChildrenWithBlock(cursor) { child, _ in guard [CXCursor_ObjCProtocolRef.rawValue, CXCursor_ObjCSuperClassRef.rawValue, CXCursor_ObjCClassRef.rawValue].indexOf(clang_getCursorKind(child).rawValue) == nil else { return CXChildVisit_Continue } clang_getSpellingLocation(clang_getRangeStart(clang_getCursorExtent(child)), nil, nil , nil, &endOffset) return CXChildVisit_Break } let name = String(clang_getCursorSpelling(cursor)) ?? "" var encounteredColon = false var encounteredOpenAngle = false var inherited = [String]() for t in tokens { var tokenStart: UInt32 = 0 clang_getSpellingLocation(clang_getTokenLocation(tu, t.token), nil, nil, nil, &tokenStart) guard tokenStart < endOffset else { break } guard let tokenName = String(clang_getTokenSpelling(tu, t.token)) where encounteredColon || encounteredOpenAngle || clang_getTokenKind(t.token) == CXToken_Punctuation else { continue } if tokenName == ":" { encounteredColon = true continue } if tokenName == "<" { encounteredOpenAngle = true continue } if tokenName == ">" { encounteredOpenAngle = false continue } if encounteredColon { inherited.append(tokenName) encounteredColon = false continue } if encounteredOpenAngle && clang_getTokenKind(t.token) != CXToken_Punctuation { inherited.append(tokenName) } } self.init(name: name, inheritedTypes: inherited) print(name) print(inheritedTypes) } }
d838ac3f0d69019e25b8932321f16510
24.53012
169
0.712465
false
false
false
false
opinionated/ios_client
refs/heads/master
Opinionated/TagPicker.swift
mit
1
// // TagPicker.swift // Opinionated // // Created by Theodore Rice on 4/24/16. // Copyright © 2016 opinionated. All rights reserved. // import UIKit class TagPicker: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func 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. } */ }
226bc9a743422f070091c7aa096bfa5f
32.863158
157
0.685421
false
false
false
false
peaks-cc/iOS11_samplecode
refs/heads/master
chapter_02/common/ARPlaneAnchor+Visualize.swift
mit
1
// // ARPlaneAnchor+Visualize.swift // // Created by Shuichi Tsutsumi on 2017/08/29. // Copyright © 2017 Shuichi Tsutsumi. All rights reserved. // import Foundation import ARKit extension ARPlaneAnchor { func addPlaneNode(on node: SCNNode, color: UIColor) { // 平面ジオメトリを作成 let geometry = SCNPlane(width: CGFloat(extent.x), height: CGFloat(extent.z)) geometry.materials.first?.diffuse.contents = color // 平面ジオメトリを持つノードを作成 let planeNode = SCNNode(geometry: geometry) planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1, 0, 0) DispatchQueue.main.async(execute: { node.addChildNode(planeNode) }) } func updatePlaneNode(on node: SCNNode) { DispatchQueue.main.async(execute: { for childNode in node.childNodes { guard let plane = childNode.geometry as? SCNPlane else {continue} guard !PlaneSizeEqualToExtent(plane: plane, extent: self.extent) else {continue} // 平面ジオメトリのサイズを更新 print("current plane size: (\(plane.width), \(plane.height))") plane.width = CGFloat(self.extent.x) plane.height = CGFloat(self.extent.z) print("updated plane size: (\(plane.width), \(plane.height))") break } }) } } fileprivate func PlaneSizeEqualToExtent(plane: SCNPlane, extent: vector_float3) -> Bool { if plane.width != CGFloat(extent.x) || plane.height != CGFloat(extent.z) { return false } else { return true } }
4bab66f8528185c2ece239e176643674
30.150943
96
0.591763
false
false
false
false
devincoughlin/swift
refs/heads/master
test/attr/attr_inlinable.swift
apache-2.0
7
// RUN: %target-typecheck-verify-swift -swift-version 5 // RUN: %target-typecheck-verify-swift -swift-version 5 -enable-testing // RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution // RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -enable-testing @inlinable struct TestInlinableStruct {} // expected-error@-1 {{'@inlinable' attribute cannot be applied to this declaration}} @inlinable @usableFromInline func redundantAttribute() {} // expected-warning@-1 {{'@inlinable' declaration is already '@usableFromInline'}} private func privateFunction() {} // expected-note@-1{{global function 'privateFunction()' is not '@usableFromInline' or public}} fileprivate func fileprivateFunction() {} // expected-note@-1{{global function 'fileprivateFunction()' is not '@usableFromInline' or public}} func internalFunction() {} // expected-note@-1{{global function 'internalFunction()' is not '@usableFromInline' or public}} @usableFromInline func versionedFunction() {} public func publicFunction() {} private struct PrivateStruct {} // expected-note@-1 3{{struct 'PrivateStruct' is not '@usableFromInline' or public}} struct InternalStruct {} // expected-note@-1 3{{struct 'InternalStruct' is not '@usableFromInline' or public}} @usableFromInline struct VersionedStruct { @usableFromInline init() {} } public struct PublicStruct { public init() {} @inlinable public var storedProperty: Int // expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}} @inlinable public lazy var lazyProperty: Int = 0 // expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}} } public struct Struct { @_transparent public func publicTransparentMethod() { struct Nested {} // expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}} publicFunction() // OK versionedFunction() // OK internalFunction() // expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a '@_transparent' function}} fileprivateFunction() // expected-error@-1 {{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a '@_transparent' function}} privateFunction() // expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a '@_transparent' function}} } @inlinable public func publicInlinableMethod() { struct Nested {} // expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}} let _: PublicStruct let _: VersionedStruct let _: InternalStruct // expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}} let _: PrivateStruct // expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}} let _ = PublicStruct.self let _ = VersionedStruct.self let _ = InternalStruct.self // expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}} let _ = PrivateStruct.self // expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}} let _ = PublicStruct() let _ = VersionedStruct() let _ = InternalStruct() // expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}} let _ = PrivateStruct() // expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}} } private func privateMethod() {} // expected-note@-1 {{instance method 'privateMethod()' is not '@usableFromInline' or public}} @_transparent @usableFromInline func versionedTransparentMethod() { struct Nested {} // expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}} privateMethod() // expected-error@-1 {{instance method 'privateMethod()' is private and cannot be referenced from a '@_transparent' function}} } @inlinable func internalInlinableMethod() { struct Nested {} // expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}} } @_transparent func internalTransparentMethod() { struct Nested {} // OK } @inlinable private func privateInlinableMethod() { // expected-error@-2 {{'@inlinable' attribute can only be applied to public declarations, but 'privateInlinableMethod' is private}} struct Nested {} // OK } @inline(__always) func internalInlineAlwaysMethod() { struct Nested {} // OK } } // Make sure protocol extension members can reference protocol requirements // (which do not inherit the @usableFromInline attribute). @usableFromInline protocol VersionedProtocol { associatedtype T func requirement() -> T } extension VersionedProtocol { func internalMethod() {} // expected-note@-1 {{instance method 'internalMethod()' is not '@usableFromInline' or public}} @inlinable func versionedMethod() -> T { internalMethod() // expected-error@-1 {{instance method 'internalMethod()' is internal and cannot be referenced from an '@inlinable' function}} return requirement() } } enum InternalEnum { // expected-note@-1 2{{enum 'InternalEnum' is not '@usableFromInline' or public}} // expected-note@-2 {{type declared here}} case apple case orange } @inlinable public func usesInternalEnum() { _ = InternalEnum.apple // expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}} let _: InternalEnum = .orange // expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}} } @usableFromInline enum VersionedEnum { case apple case orange case pear(InternalEnum) // expected-error@-1 {{type of enum case in '@usableFromInline' enum must be '@usableFromInline' or public}} case persimmon(String) } @inlinable public func usesVersionedEnum() { _ = VersionedEnum.apple let _: VersionedEnum = .orange _ = VersionedEnum.persimmon } // Inherited initializers - <rdar://problem/34398148> @usableFromInline @_fixed_layout class Base { @usableFromInline init(x: Int) {} } @usableFromInline @_fixed_layout class Middle : Base {} @usableFromInline @_fixed_layout class Derived : Middle { @inlinable init(y: Int) { super.init(x: y) } } // More inherited initializers @_fixed_layout public class Base2 { @inlinable public init(x: Int) {} } @_fixed_layout @usableFromInline class Middle2 : Base2 {} @_fixed_layout @usableFromInline class Derived2 : Middle2 { @inlinable init(y: Int) { super.init(x: y) } } // Even more inherited initializers - https://bugs.swift.org/browse/SR-10940 @_fixed_layout public class Base3 {} // expected-note@-1 {{initializer 'init()' is not '@usableFromInline' or public}} @_fixed_layout public class Derived3 : Base3 { @inlinable public init(_: Int) {} // expected-error@-1 {{initializer 'init()' is internal and cannot be referenced from an '@inlinable' function}} } @_fixed_layout public class Base4 {} @_fixed_layout @usableFromInline class Middle4 : Base4 {} // expected-note@-1 {{initializer 'init()' is not '@usableFromInline' or public}} @_fixed_layout @usableFromInline class Derived4 : Middle4 { @inlinable public init(_: Int) {} // expected-error@-1 {{initializer 'init()' is internal and cannot be referenced from an '@inlinable' function}} } // Stored property initializer expressions. // // Note the behavior here does not depend on the state of the -enable-library-evolution // flag; the test runs with both the flag on and off. Only the explicit // presence of a '@_fixed_layout' attribute determines the behavior here. let internalGlobal = 0 // expected-note@-1 {{let 'internalGlobal' is not '@usableFromInline' or public}} public let publicGlobal = 0 struct InternalStructWithInit { var x = internalGlobal // OK var y = publicGlobal // OK } public struct PublicResilientStructWithInit { var x = internalGlobal // OK var y = publicGlobal // OK } private func privateIntReturningFunc() -> Int { return 0 } internal func internalIntReturningFunc() -> Int { return 0 } @frozen public struct PublicFixedStructWithInit { var x = internalGlobal // expected-error {{let 'internalGlobal' is internal and cannot be referenced from a property initializer in a '@frozen' type}} var y = publicGlobal // OK static var z = privateIntReturningFunc() // OK static var a = internalIntReturningFunc() // OK } public struct KeypathStruct { var x: Int // expected-note@-1 {{property 'x' is not '@usableFromInline' or public}} @inlinable public func usesKeypath() { _ = \KeypathStruct.x // expected-error@-1 {{property 'x' is internal and cannot be referenced from an '@inlinable' function}} } } public struct HasInternalSetProperty { public internal(set) var x: Int // expected-note {{setter for 'x' is not '@usableFromInline' or public}} @inlinable public mutating func setsX() { x = 10 // expected-error {{setter for 'x' is internal and cannot be referenced from an '@inlinable' function}} } } @usableFromInline protocol P { typealias T = Int } extension P { @inlinable func f() { _ = T.self // ok, typealias inherits @usableFromInline from P } }
96389c244e2c526132171253024eec66
30.431894
152
0.712398
false
false
false
false
Thomvis/BrightFutures
refs/heads/master
Example/Pods/BrightFutures/Sources/BrightFutures/SequenceType+BrightFutures.swift
mit
2
// The MIT License (MIT) // // Copyright (c) 2014 Thomas Visser // // 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 Sequence { /// Turns a sequence of T's into an array of `Future<U>`'s by calling the given closure for each element in the sequence. /// If no context is provided, the given closure is executed on `Queue.global` public func traverse<U, E, A: AsyncType>(_ context: @escaping ExecutionContext = DispatchQueue.global().context, f: (Iterator.Element) -> A) -> Future<[U], E> where A.Value: ResultProtocol, A.Value.Value == U, A.Value.Error == E { return map(f).fold(context, zero: [U]()) { (list: [U], elem: U) -> [U] in return list + [elem] } } } extension Sequence where Iterator.Element: AsyncType { /// Returns a future that returns with the first future from the given sequence that completes /// (regardless of whether that future succeeds or fails) public func firstCompleted() -> Iterator.Element { let res = Async<Iterator.Element.Value>() for fut in self { fut.onComplete(DispatchQueue.global().context) { res.tryComplete($0) } } return Iterator.Element(other: res) } } extension Sequence where Iterator.Element: AsyncType, Iterator.Element.Value: ResultProtocol { //// The free functions in this file operate on sequences of Futures /// Performs the fold operation over a sequence of futures. The folding is performed /// on `Queue.global`. /// (The Swift compiler does not allow a context parameter with a default value /// so we define some functions twice) public func fold<R>(_ zero: R, f: @escaping (R, Iterator.Element.Value.Value) -> R) -> Future<R, Iterator.Element.Value.Error> { return fold(DispatchQueue.global().context, zero: zero, f: f) } /// Performs the fold operation over a sequence of futures. The folding is performed /// in the given context. public func fold<R>(_ context: @escaping ExecutionContext, zero: R, f: @escaping (R, Iterator.Element.Value.Value) -> R) -> Future<R, Iterator.Element.Value.Error> { return reduce(Future<R, Iterator.Element.Value.Error>(value: zero)) { zero, elem in return zero.flatMap(maxStackDepthExecutionContext) { zeroVal in elem.map(context) { elemVal in return f(zeroVal, elemVal) } } } } /// Turns a sequence of `Future<T>`'s into a future with an array of T's (Future<[T]>) /// If one of the futures in the given sequence fails, the returned future will fail /// with the error of the first future that comes first in the list. public func sequence() -> Future<[Iterator.Element.Value.Value], Iterator.Element.Value.Error> { return traverse(immediateExecutionContext) { return $0 } } /// See `find<S: SequenceType, T where S.Iterator.Element == Future<T>>(seq: S, context c: ExecutionContext, p: T -> Bool) -> Future<T>` public func find(_ p: @escaping (Iterator.Element.Value.Value) -> Bool) -> Future<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> { return find(DispatchQueue.global().context, p: p) } /// Returns a future that succeeds with the value from the first future in the given /// sequence that passes the test `p`. /// If any of the futures in the given sequence fail, the returned future fails with the /// error of the first failed future in the sequence. /// If no futures in the sequence pass the test, a future with an error with NoSuchElement is returned. public func find(_ context: @escaping ExecutionContext, p: @escaping (Iterator.Element.Value.Value) -> Bool) -> Future<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> { return sequence().mapError(immediateExecutionContext) { error in return BrightFuturesError(external: error) }.flatMap(context) { val -> Result<Iterator.Element.Value.Value, BrightFuturesError<Iterator.Element.Value.Error>> in for elem in val { if (p(elem)) { return .success(elem) } } return .failure(.noSuchElement) } } } extension Sequence where Iterator.Element: ResultProtocol { /// Turns a sequence of `Result<T>`'s into a Result with an array of T's (`Result<[T]>`) /// If one of the results in the given sequence is a .failure, the returned result is a .failure with the /// error from the first failed result from the sequence. public func sequence() -> Result<[Iterator.Element.Value], Iterator.Element.Error> { return reduce(.success([])) { (res, elem) -> Result<[Iterator.Element.Value], Iterator.Element.Error> in switch res { case .success(let resultSequence): return elem.analysis(ifSuccess: { let newSeq = resultSequence + [$0] return .success(newSeq) }, ifFailure: { return .failure($0) }) case .failure(_): return res } } } }
ccf85abbc381123bdc07cc3ee2175c3c
49.576
234
0.655805
false
false
false
false
slicedev/slice-ios
refs/heads/master
SliceSDK/Framework/Source/Public/NSDate+Formatting.swift
mit
1
// // NSDate+Extensions.swift // SliceSDK // import Foundation class DateHelper { static var dateFormatters = [String: NSDateFormatter]() } public extension NSDate { class func dateFormatterWithFormat(format: String) -> NSDateFormatter { var dateFormatter = DateHelper.dateFormatters[format] if dateFormatter == nil { dateFormatter = NSDateFormatter() dateFormatter!.dateFormat = format DateHelper.dateFormatters[format] = dateFormatter! } return dateFormatter! } // String public convenience init(string: String, format: String) { if let date = NSDate.dateFormatterWithFormat(format).dateFromString(string) { self.init(timeIntervalSince1970: date.timeIntervalSince1970) } else { assertionFailure("Invalid date string: \(string), format: \(format)") self.init() } } public func stringValue(format: String) -> String { return NSDate.dateFormatterWithFormat(format).stringFromDate(self) } // Milliseconds public convenience init(millisecondsSince1970 milliseconds: Int64) { let interval = Double(milliseconds) / 1000.0 self.init(timeIntervalSince1970: interval) } public var millisecondsSince1970: Int64 { return Int64(timeIntervalSince1970 * 1000.0) } // ISO Date Time public static var ISODateTimeFormat: String { return "yyyy-MM-dd'T'HH:mm:ss" } public convenience init?(ISODateTimeString string: String) { self.init(string: string, format: NSDate.ISODateTimeFormat) } public var ISODateTimeString: String { return stringValue(NSDate.ISODateTimeFormat) } // ISO Date public static var ISODateFormat: String { return "yyyy-MM-dd" } public convenience init?(ISODateString string: String) { self.init(string: string, format: NSDate.ISODateFormat) } public var ISODateString: String { return stringValue(NSDate.ISODateFormat) } }
35c3fe121593f4bfd12c774f13ee93ee
27.808219
85
0.647646
false
false
false
false
producthunt/producthunt-osx
refs/heads/master
Source/PHAPIOperation.swift
mit
1
// // File.swift // Product Hunt // // Created by Vlado on 5/4/16. // Copyright © 2016 ProductHunt. All rights reserved. // import Foundation import ReSwift class PHAPIOperation { class func perform(_ store: Store<PHAppState>, api: PHAPI, operation: @escaping PHAPIOperationClosure) { withToken(store, api: api) { (token, error) in operation(api, { (error) in if NSError.parseError(error) == NSError.unauthorizedError() { let token = PHToken(accessToken: "") store.dispatch( PHTokenGetAction(token: token) ) } withToken(store, api: api, callback: { (token, error) in operation(api, { (error) in //TODO : Dispatch errror }) }) }) } } fileprivate class func withToken(_ store: Store<PHAppState>, api: PHAPI, callback: @escaping PHAPITokenCompletion) { if store.state.token.isValid { callback(store.state.token, nil) return } api.getToken { (token, error) in if let token = token { // TODO: Other mechanism to update token api.endpoint = PHAPIEndpoint(token: token) store.dispatch( PHTokenGetAction(token: token) ) } callback(token, error) } } }
62f3d889d3e3e3a1babd161fa53e796a
28.5625
120
0.536293
false
false
false
false
rafaelcpalmeida/UFP-iOS
refs/heads/master
UFP/UFP/LoginViewController.swift
mit
1
// // ViewController.swift // UFP // // Created by Rafael Almeida on 13/03/17. // Copyright © 2017 Rafael Almeida. All rights reserved. // import UIKit import LocalAuthentication class LoginViewController: UIViewController { @IBOutlet weak var logo: UIImageView! @IBOutlet weak var touch: UIImageView! @IBOutlet weak var userNumber: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var bgActivity: UIActivityIndicatorView! let apiController = APIController() let context = LAContext() override func viewDidLoad() { super.viewDidLoad() if (!hasBiometricAuth() || KeychainService.loadUserNumber() == nil || KeychainService.loadUserPassword() == nil) { self.touch.isHidden = true } if(KeychainService.loadUserNumber() != nil) { self.userNumber.text = KeychainService.loadUserNumber() as String? } let tapOutside: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard)) view.addGestureRecognizer(tapOutside) if(hasBiometricAuth()) { let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(loginWithTouchID(tapGestureRecognizer:))) touch.isUserInteractionEnabled = true touch.addGestureRecognizer(tapGestureRecognizer) } NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0 { self.logo.isHidden = true self.touch.isHidden = true self.view.frame.origin.y -= keyboardSize.height } } } @objc func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0 { self.logo.isHidden = false if (context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)) { self.touch.isHidden = false } self.view.frame.origin.y += keyboardSize.height } } } @objc func loginWithTouchID (tapGestureRecognizer: UITapGestureRecognizer) { context.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Coloque o dedo para entrar") { (isSucessful, hasError) in if isSucessful { DispatchQueue.main.asyncAfter(deadline: .now()) { self.userNumber.isHidden = true self.password.isHidden = true self.loginButton.isHidden = true self.touch.isHidden = true self.bgActivity.startAnimating() } let userNumber = KeychainService.loadUserNumber(), userPassword = KeychainService.loadUserPassword() self.apiController.attemptLogin(userNumber! as String, userPassword: userPassword! as String) { (json, error) in self.bgActivity.stopAnimating() if(error == nil) { if(json["status"] == "Ok") { APICredentials.sharedInstance.apiToken = json["message"].string APICredentials.sharedInstance.userNumber = KeychainService.loadUserNumber() as String? self.performSegue(withIdentifier: "loginSegue", sender: nil) } else { self.userNumber.isHidden = false self.password.isHidden = false self.loginButton.isHidden = false self.touch.isHidden = false let alert = UIAlertController(title: "Erro!", message: "Por favor verifique as suas credenciais de acesso.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } else { let alert = UIAlertController(title: "Erro!", message: "Ocorreu um erro, por favor tente novamente.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) self.userNumber.isHidden = false self.password.isHidden = false self.loginButton.isHidden = false self.touch.isHidden = false } } } else { let alert = UIAlertController(title: "Erro!", message: "Por favor verifique as suas credenciais de acesso.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } @IBAction func attemptLogin(_ sender: Any) { if (!(userNumber.text?.isEmpty)! && !(password.text?.isEmpty)!) { bgActivity.startAnimating() self.view.endEditing(true) self.userNumber.isHidden = true self.password.isHidden = true self.loginButton.isHidden = true self.touch.isHidden = true apiController.attemptLogin(self.userNumber.text!, userPassword: self.password.text!) { (json, error) in self.bgActivity.stopAnimating() if(error == nil) { if(json["status"] == "Ok") { APICredentials.sharedInstance.apiToken = json["message"].string APICredentials.sharedInstance.userNumber = self.userNumber.text! if(self.hasBiometricAuth()) { let touchIDAlert = UIAlertController(title: "Autenticação com TouchID", message: "Pretende activar o TouchID para entrar na aplicação?", preferredStyle: UIAlertControllerStyle.alert) touchIDAlert.addAction(UIAlertAction(title: "Sim", style: .default, handler: { (action: UIAlertAction!) in KeychainService.saveUserNumber(self.userNumber.text! as NSString) KeychainService.saveUserPassword(self.password.text! as NSString) self.performSegue(withIdentifier: "loginSegue", sender: nil) })) touchIDAlert.addAction(UIAlertAction(title: "Não", style: .cancel, handler: { (action: UIAlertAction!) in self.performSegue(withIdentifier: "loginSegue", sender: nil) })) self.present(touchIDAlert, animated: true, completion: nil) } else { self.performSegue(withIdentifier: "loginSegue", sender: nil) } } else { self.userNumber.isHidden = false self.password.isHidden = false self.loginButton.isHidden = false self.touch.isHidden = false let alert = UIAlertController(title: "Erro!", message: "Por favor verifique as suas credenciais de acesso.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } } private func hasBiometricAuth() -> Bool { return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } }
e6ff4a2a5a29c08fb0d70b24fd2808ef
50.173184
210
0.579476
false
false
false
false
xcodeswift/xcproj
refs/heads/master
Sources/XcodeProj/Objects/Project/PBXProject.swift
mit
1
import Foundation import PathKit public final class PBXProject: PBXObject { // MARK: - Attributes /// Project name public var name: String /// Build configuration list reference. var buildConfigurationListReference: PBXObjectReference /// Build configuration list. public var buildConfigurationList: XCConfigurationList! { set { buildConfigurationListReference = newValue.reference } get { buildConfigurationListReference.getObject() } } /// A string representation of the XcodeCompatibilityVersion. public var compatibilityVersion: String /// The region of development. public var developmentRegion: String? /// Whether file encodings have been scanned. public var hasScannedForEncodings: Int /// The known regions for localized files. public var knownRegions: [String] /// The object is a reference to a PBXGroup element. var mainGroupReference: PBXObjectReference /// Project main group. public var mainGroup: PBXGroup! { set { mainGroupReference = newValue.reference } get { mainGroupReference.getObject() } } /// The object is a reference to a PBXGroup element. var productsGroupReference: PBXObjectReference? /// Products group. public var productsGroup: PBXGroup? { set { productsGroupReference = newValue?.reference } get { productsGroupReference?.getObject() } } /// The relative path of the project. public var projectDirPath: String /// Project references. var projectReferences: [[String: PBXObjectReference]] /// Project projects. // { // ProductGroup = B900DB69213936CC004AEC3E /* Products group reference */; // ProjectRef = B900DB68213936CC004AEC3E /* Project file reference */; // }, public var projects: [[String: PBXFileElement]] { set { projectReferences = newValue.map { project in project.mapValues { $0.reference } } } get { projectReferences.map { project in project.mapValues { $0.getObject()! } } } } private static let targetAttributesKey = "TargetAttributes" /// The relative root paths of the project. public var projectRoots: [String] /// The objects are a reference to a PBXTarget element. var targetReferences: [PBXObjectReference] /// Project targets. public var targets: [PBXTarget] { set { targetReferences = newValue.references() } get { targetReferences.objects() } } /// Project attributes. /// Target attributes will be merged into this public var attributes: [String: Any] /// Target attribute references. var targetAttributeReferences: [PBXObjectReference: [String: Any]] /// Target attributes. public var targetAttributes: [PBXTarget: [String: Any]] { set { targetAttributeReferences = [:] newValue.forEach { targetAttributeReferences[$0.key.reference] = $0.value } } get { var attributes: [PBXTarget: [String: Any]] = [:] targetAttributeReferences.forEach { if let object: PBXTarget = $0.key.getObject() { attributes[object] = $0.value } } return attributes } } /// Package references. var packageReferences: [PBXObjectReference]? /// Swift packages. public var packages: [XCRemoteSwiftPackageReference] { set { packageReferences = newValue.references() } get { packageReferences?.objects() ?? [] } } /// Sets the attributes for the given target. /// /// - Parameters: /// - attributes: attributes that will be set. /// - target: target. public func setTargetAttributes(_ attributes: [String: Any], target: PBXTarget) { targetAttributeReferences[target.reference] = attributes } /// Removes the attributes for the given target. /// /// - Parameter target: target whose attributes will be removed. public func removeTargetAttributes(target: PBXTarget) { targetAttributeReferences.removeValue(forKey: target.reference) } /// Removes the all the target attributes public func clearAllTargetAttributes() { targetAttributeReferences.removeAll() } /// Returns the attributes of a given target. /// /// - Parameter for: target whose attributes will be returned. /// - Returns: target attributes. public func attributes(for target: PBXTarget) -> [String: Any]? { targetAttributeReferences[target.reference] } /// Adds a remote swift package /// /// - Parameters: /// - repositoryURL: URL in String pointing to the location of remote Swift package /// - productName: The product to depend on without the extension /// - versionRequirement: Describes the rules of the version to use /// - targetName: Target's name to link package product to public func addSwiftPackage(repositoryURL: String, productName: String, versionRequirement: XCRemoteSwiftPackageReference.VersionRequirement, targetName: String) throws -> XCRemoteSwiftPackageReference { let objects = try self.objects() guard let target = targets.first(where: { $0.name == targetName }) else { throw PBXProjError.targetNotFound(targetName: targetName) } // Reference let reference = try addSwiftPackageReference(repositoryURL: repositoryURL, productName: productName, versionRequirement: versionRequirement) // Product let productDependency = try addSwiftPackageProduct(reference: reference, productName: productName, target: target) // Build file let buildFile = PBXBuildFile(product: productDependency) objects.add(object: buildFile) // Link the product guard let frameworksBuildPhase = try target.frameworksBuildPhase() else { throw PBXProjError.frameworksBuildPhaseNotFound(targetName: targetName) } frameworksBuildPhase.files?.append(buildFile) return reference } /// Adds a local swift package /// /// - Parameters: /// - path: Relative path to the swift package (throws an error if the path is absolute) /// - productName: The product to depend on without the extension /// - targetName: Target's name to link package product to /// - addFileReference: Include a file reference to the package (defaults to main group) public func addLocalSwiftPackage(path: Path, productName: String, targetName: String, addFileReference: Bool = true) throws -> XCSwiftPackageProductDependency { guard path.isRelative else { throw PBXProjError.pathIsAbsolute(path) } let objects = try self.objects() guard let target = targets.first(where: { $0.name == targetName }) else { throw PBXProjError.targetNotFound(targetName: targetName) } // Product let productDependency = try addLocalSwiftPackageProduct(path: path, productName: productName, target: target) // Build file let buildFile = PBXBuildFile(product: productDependency) objects.add(object: buildFile) // Link the product guard let frameworksBuildPhase = try target.frameworksBuildPhase() else { throw PBXProjError.frameworksBuildPhaseNotFound(targetName: targetName) } frameworksBuildPhase.files?.append(buildFile) // File reference // The user might want to control adding the file's reference (to be exact when the reference is added) // to achieve desired hierarchy of the group's children if addFileReference { let reference = PBXFileReference(sourceTree: .group, name: productName, lastKnownFileType: "folder", path: path.string) objects.add(object: reference) mainGroup.children.append(reference) } return productDependency } // MARK: - Init /// Initializes the project with its attributes /// /// - Parameters: /// - name: xcodeproj's name. /// - buildConfigurationList: project build configuration list. /// - compatibilityVersion: project compatibility version. /// - mainGroup: project main group. /// - developmentRegion: project has development region. /// - hasScannedForEncodings: project has scanned for encodings. /// - knownRegions: project known regions. /// - productsGroup: products group. /// - projectDirPath: project dir path. /// - projects: projects. /// - projectRoots: project roots. /// - targets: project targets. public init(name: String, buildConfigurationList: XCConfigurationList, compatibilityVersion: String, mainGroup: PBXGroup, developmentRegion: String? = nil, hasScannedForEncodings: Int = 0, knownRegions: [String] = [], productsGroup: PBXGroup? = nil, projectDirPath: String = "", projects: [[String: PBXFileElement]] = [], projectRoots: [String] = [], targets: [PBXTarget] = [], packages: [XCRemoteSwiftPackageReference] = [], attributes: [String: Any] = [:], targetAttributes: [PBXTarget: [String: Any]] = [:]) { self.name = name buildConfigurationListReference = buildConfigurationList.reference self.compatibilityVersion = compatibilityVersion mainGroupReference = mainGroup.reference self.developmentRegion = developmentRegion self.hasScannedForEncodings = hasScannedForEncodings self.knownRegions = knownRegions productsGroupReference = productsGroup?.reference self.projectDirPath = projectDirPath projectReferences = projects.map { project in project.mapValues { $0.reference } } self.projectRoots = projectRoots targetReferences = targets.references() packageReferences = packages.references() self.attributes = attributes targetAttributeReferences = [:] super.init() self.targetAttributes = targetAttributes } // MARK: - Decodable fileprivate enum CodingKeys: String, CodingKey { case name case buildConfigurationList case compatibilityVersion case developmentRegion case hasScannedForEncodings case knownRegions case mainGroup case productRefGroup case projectDirPath case projectReferences case projectRoot case projectRoots case targets case attributes case packageReferences } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let referenceRepository = decoder.context.objectReferenceRepository let objects = decoder.context.objects name = (try container.decodeIfPresent(.name)) ?? "" let buildConfigurationListReference: String = try container.decode(.buildConfigurationList) self.buildConfigurationListReference = referenceRepository.getOrCreate(reference: buildConfigurationListReference, objects: objects) compatibilityVersion = try container.decode(.compatibilityVersion) developmentRegion = try container.decodeIfPresent(.developmentRegion) let hasScannedForEncodingsString: String? = try container.decodeIfPresent(.hasScannedForEncodings) hasScannedForEncodings = hasScannedForEncodingsString.flatMap { Int($0) } ?? 0 knownRegions = (try container.decodeIfPresent(.knownRegions)) ?? [] let mainGroupReference: String = try container.decode(.mainGroup) self.mainGroupReference = referenceRepository.getOrCreate(reference: mainGroupReference, objects: objects) if let productRefGroupReference: String = try container.decodeIfPresent(.productRefGroup) { productsGroupReference = referenceRepository.getOrCreate(reference: productRefGroupReference, objects: objects) } else { productsGroupReference = nil } projectDirPath = try container.decodeIfPresent(.projectDirPath) ?? "" let projectReferences: [[String: String]] = (try container.decodeIfPresent(.projectReferences)) ?? [] self.projectReferences = projectReferences.map { references in references.mapValues { referenceRepository.getOrCreate(reference: $0, objects: objects) } } if let projectRoots: [String] = try container.decodeIfPresent(.projectRoots) { self.projectRoots = projectRoots } else if let projectRoot: String = try container.decodeIfPresent(.projectRoot) { projectRoots = [projectRoot] } else { projectRoots = [] } let targetReferences: [String] = (try container.decodeIfPresent(.targets)) ?? [] self.targetReferences = targetReferences.map { referenceRepository.getOrCreate(reference: $0, objects: objects) } let packageRefeferenceStrings: [String] = try container.decodeIfPresent(.packageReferences) ?? [] packageReferences = packageRefeferenceStrings.map { referenceRepository.getOrCreate(reference: $0, objects: objects) } var attributes = (try container.decodeIfPresent([String: Any].self, forKey: .attributes) ?? [:]) var targetAttributeReferences: [PBXObjectReference: [String: Any]] = [:] if let targetAttributes = attributes[PBXProject.targetAttributesKey] as? [String: [String: Any]] { targetAttributes.forEach { targetAttributeReferences[referenceRepository.getOrCreate(reference: $0.key, objects: objects)] = $0.value } attributes[PBXProject.targetAttributesKey] = nil } self.attributes = attributes self.targetAttributeReferences = targetAttributeReferences try super.init(from: decoder) } } // MARK: - Helpers extension PBXProject { /// Adds reference for remote Swift package private func addSwiftPackageReference(repositoryURL: String, productName: String, versionRequirement: XCRemoteSwiftPackageReference.VersionRequirement) throws -> XCRemoteSwiftPackageReference { let reference: XCRemoteSwiftPackageReference if let package = packages.first(where: { $0.repositoryURL == repositoryURL }) { guard package.versionRequirement == versionRequirement else { throw PBXProjError.multipleRemotePackages(productName: productName) } reference = package } else { reference = XCRemoteSwiftPackageReference(repositoryURL: repositoryURL, versionRequirement: versionRequirement) try objects().add(object: reference) packages.append(reference) } return reference } /// Adds package product for remote Swift package private func addSwiftPackageProduct(reference: XCRemoteSwiftPackageReference, productName: String, target: PBXTarget) throws -> XCSwiftPackageProductDependency { let objects = try self.objects() let productDependency: XCSwiftPackageProductDependency // Avoid duplication if let product = objects.swiftPackageProductDependencies.first(where: { $0.value.package == reference })?.value { productDependency = product } else { productDependency = XCSwiftPackageProductDependency(productName: productName, package: reference) objects.add(object: productDependency) } target.packageProductDependencies.append(productDependency) return productDependency } /// Adds package product for local Swift package private func addLocalSwiftPackageProduct(path: Path, productName: String, target: PBXTarget) throws -> XCSwiftPackageProductDependency { let objects = try self.objects() let productDependency: XCSwiftPackageProductDependency // Avoid duplication if let product = objects.swiftPackageProductDependencies.first(where: { $0.value.productName == productName }) { guard objects.fileReferences.first(where: { $0.value.name == productName })?.value.path == path.string else { throw PBXProjError.multipleLocalPackages(productName: productName) } productDependency = product.value } else { productDependency = XCSwiftPackageProductDependency(productName: productName) objects.add(object: productDependency) } target.packageProductDependencies.append(productDependency) return productDependency } } // MARK: - PlistSerializable extension PBXProject: PlistSerializable { // swiftlint:disable:next function_body_length func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = [:] dictionary["isa"] = .string(CommentedString(PBXProject.isa)) let buildConfigurationListComment = "Build configuration list for PBXProject \"\(name)\"" let buildConfigurationListCommentedString = CommentedString(buildConfigurationListReference.value, comment: buildConfigurationListComment) dictionary["buildConfigurationList"] = .string(buildConfigurationListCommentedString) dictionary["compatibilityVersion"] = .string(CommentedString(compatibilityVersion)) if let developmentRegion = developmentRegion { dictionary["developmentRegion"] = .string(CommentedString(developmentRegion)) } dictionary["hasScannedForEncodings"] = .string(CommentedString("\(hasScannedForEncodings)")) if !knownRegions.isEmpty { dictionary["knownRegions"] = PlistValue.array(knownRegions .map { .string(CommentedString("\($0)")) }) } let mainGroupObject: PBXGroup? = mainGroupReference.getObject() dictionary["mainGroup"] = .string(CommentedString(mainGroupReference.value, comment: mainGroupObject?.fileName())) if let productsGroupReference = productsGroupReference { let productRefGroupObject: PBXGroup? = productsGroupReference.getObject() dictionary["productRefGroup"] = .string(CommentedString(productsGroupReference.value, comment: productRefGroupObject?.fileName())) } dictionary["projectDirPath"] = .string(CommentedString(projectDirPath)) if projectRoots.count > 1 { dictionary["projectRoots"] = projectRoots.plist() } else { dictionary["projectRoot"] = .string(CommentedString(projectRoots.first ?? "")) } if let projectReferences = try projectReferencesPlistValue(proj: proj) { dictionary["projectReferences"] = projectReferences } dictionary["targets"] = PlistValue.array(targetReferences .map { targetReference in let target: PBXTarget? = targetReference.getObject() return .string(CommentedString(targetReference.value, comment: target?.name)) }) if !packages.isEmpty { dictionary["packageReferences"] = PlistValue.array(packages.map { .string(CommentedString($0.reference.value, comment: "XCRemoteSwiftPackageReference \"\($0.name ?? "")\"")) }) } var plistAttributes: [String: Any] = attributes // merge target attributes var plistTargetAttributes: [String: Any] = [:] for (reference, value) in targetAttributeReferences { plistTargetAttributes[reference.value] = value.mapValues { value in (value as? PBXObject)?.reference.value ?? value } } plistAttributes[PBXProject.targetAttributesKey] = plistTargetAttributes dictionary["attributes"] = plistAttributes.plist() return (key: CommentedString(reference, comment: "Project object"), value: .dictionary(dictionary)) } private func projectReferencesPlistValue(proj _: PBXProj) throws -> PlistValue? { guard !projectReferences.isEmpty else { return nil } return .array(projectReferences.compactMap { reference in guard let productGroupReference = reference[Xcode.ProjectReference.productGroupKey], let projectRef = reference[Xcode.ProjectReference.projectReferenceKey] else { return nil } let producGroup: PBXGroup? = productGroupReference.getObject() let groupName = producGroup?.fileName() let project: PBXFileElement? = projectRef.getObject() let fileRefName = project?.fileName() return [ CommentedString(Xcode.ProjectReference.productGroupKey): PlistValue.string(CommentedString(productGroupReference.value, comment: groupName)), CommentedString(Xcode.ProjectReference.projectReferenceKey): PlistValue.string(CommentedString(projectRef.value, comment: fileRefName)), ] }) } }
77cf37f46a08a36abbc9474ea8e0b0aa
41.903042
157
0.632029
false
false
false
false
KaneCheshire/Communicator
refs/heads/main
Example/Communicator/ViewController.swift
mit
1
// // ViewController.swift // Communicator // // Created by Kane Cheshire on 07/19/2017. // Copyright (c) 2017 Kane Cheshire. All rights reserved. // import UIKit import Communicator class ViewController: UIViewController { @IBAction func sendMessageTapped() { let message = ImmediateMessage(identifier: "message", content: ["hello": "world"]) Communicator.shared.send(message) { error in print("Error sending immediate message", error) } } @IBAction func sendInteractiveMessageTapped() { let message = InteractiveImmediateMessage(identifier: "interactive_message", content: ["hello": "world"]) { reply in print("Received reply from message: \(reply)") } Communicator.shared.send(message) { error in print("Error sending immediate message", error) } } @IBAction func sendGuaranteedMessageTapped() { let message = GuaranteedMessage(identifier: "guaranteed_message", content: ["hello": "world"]) Communicator.shared.send(message) { result in switch result { case .failure(let error): print("Error transferring blob: \(error.localizedDescription)") case .success: print("Successfully transferred guaranteed message to watch") } } } @IBAction func transferBlobTapped() { let data = Data("hello world".utf8) let blob = Blob(identifier: "blob", content: data) let task = Communicator.shared.transfer(blob) { result in switch result { case .failure(let error): print("Error transferring blob: \(error.localizedDescription)") case .success: print("Successfully transferred blob to watch") } } task?.cancel() } @IBAction func syncContextTapped() { let context = Context(content: ["hello" : "world"]) do { try Communicator.shared.sync(context) print("Synced context to watch") } catch let error { print("Error syncing context to watch: \(error.localizedDescription)") } } @IBAction func transferComplicationInfoTapped() { switch Communicator.shared.currentWatchState { case .notPaired: print("Watch is not paired, cannot transfer complication info") case .paired(let appState): switch appState { case .notInstalled: print("App is not installed, cannot transfer complication info") case .installed(let compState, _): switch compState { case .notEnabled: print("Complication is not enabled on the active watch face, cannot transfer complication info") case .enabled(let numberOfComplicationUpdatesAvailable): print("Number of complication transfers available today (usually out of 50)", numberOfComplicationUpdatesAvailable) transferCompInfo() } } } } private func transferCompInfo() { let complicationInfo = ComplicationInfo(content: ["Value" : 1]) Communicator.shared.transfer(complicationInfo) { result in switch result { case .success(let numberOfComplicationUpdatesAvailable): print("Successfully transferred complication info, number of complications now available: ", numberOfComplicationUpdatesAvailable) case .failure(let error): print("Failed to transfer complication info", error.localizedDescription) } } } }
ec04b779e681610d760239b906e690c9
38.04
150
0.578381
false
false
false
false
mozilla-mobile/firefox-ios
refs/heads/main
Storage/SQL/SQLiteHistoryFavicons.swift
mpl-2.0
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import UIKit import Fuzi import SwiftyJSON import Shared private let log = Logger.syncLogger // Set up for downloading web content for parsing. // NOTE: We use the desktop UA to try and get hi-res icons. private var urlSession: URLSession = makeURLSession(userAgent: UserAgent.desktopUserAgent(), configuration: URLSessionConfiguration.default, timeout: 5) // If all else fails, this is the default "default" icon. private var defaultFavicon: UIImage = { return UIImage(named: ImageIdentifiers.defaultFavicon)! }() // An in-memory cache of "default" favicons keyed by the // first character of a site's domain name. private var defaultFaviconImageCache = [String: UIImage]() // Some of our top-sites domains exist in various // region-specific TLDs. This helps us resolve them. private let multiRegionTopSitesDomains = ["craigslist", "google", "amazon"] private let topSitesIcons: [String: (color: UIColor, fileURL: URL)] = { var icons: [String: (color: UIColor, fileURL: URL)] = [:] let filePath = Bundle.main.path(forResource: "top_sites", ofType: "json") let file = try! Data(contentsOf: URL(fileURLWithPath: filePath!)) JSON(file).forEach({ guard let domain = $0.1["domain"].string, let color = $0.1["background_color"].string?.lowercased(), let path = $0.1["image_url"].string?.replacingOccurrences(of: ".png", with: "") else { return } if let fileURL = Bundle.main.url(forResource: "TopSites/" + path, withExtension: "png") { if color == "#fff" { icons[domain] = (UIColor.clear, fileURL) } else { icons[domain] = (UIColor(colorString: color.replacingOccurrences(of: "#", with: "")), fileURL) } } }) return icons }() class FaviconLookupError: MaybeErrorType { let siteURL: String init(siteURL: String) { self.siteURL = siteURL } var description: String { return "Unable to find favicon for site URL: \(siteURL)" } } class FaviconDownloadError: MaybeErrorType { let faviconURL: String init(faviconURL: String) { self.faviconURL = faviconURL } internal var description: String { return "Unable to download favicon at URL: \(faviconURL)" } } extension SQLiteHistory: Favicons { public func getFaviconImage(forSite site: Site) -> Deferred<Maybe<UIImage>> { // First, attempt to lookup the favicon from our bundled top sites. return getTopSitesFaviconImage(forSite: site).bind { result in guard let image = result.successValue else { // Note: "Attempt to lookup the favicon URL from the database" was removed as part of FXIOS-5164 and // FXIOS-5294. This means at the moment we don't save nor retrieve favicon URLs from the database. // Attempt to scrape its URL from the web page. return self.lookupFaviconURLFromWebPage(forSite: site).bind { result in guard let faviconURL = result.successValue else { // Otherwise, get the default favicon image. return self.generateDefaultFaviconImage(forSite: site) } // Try to get the favicon from the URL scraped from the web page. return self.retrieveTopSiteSQLiteHistoryFaviconImage(faviconURL: faviconURL).bind { result in // If the favicon could not be downloaded, use the generated "default" favicon. guard let image = result.successValue else { return self.generateDefaultFaviconImage(forSite: site) } return deferMaybe(image) } } } return deferMaybe(image) } } // Downloads a favicon image from the web or retrieves it from the cache. fileprivate func retrieveTopSiteSQLiteHistoryFaviconImage(faviconURL: URL) -> Deferred<Maybe<UIImage>> { let deferred = CancellableDeferred<Maybe<UIImage>>() ImageLoadingHandler.shared.getImageFromCacheOrDownload(with: faviconURL, limit: ImageLoadingConstants.MaximumFaviconSize) { image, error in guard error == nil, let image = image else { deferred.fill(Maybe(failure: FaviconDownloadError(faviconURL: faviconURL.absoluteString))) return } deferred.fill(Maybe(success: image)) } return deferred } fileprivate func getTopSitesFaviconImage(forSite site: Site) -> Deferred<Maybe<UIImage>> { guard let url = URL(string: site.url) else { return deferMaybe(FaviconLookupError(siteURL: site.url)) } func imageFor(icon: (color: UIColor, fileURL: URL)) -> Deferred<Maybe<UIImage>> { guard let image = UIImage(contentsOfFile: icon.fileURL.path) else { return deferMaybe(FaviconLookupError(siteURL: site.url)) } UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext(), let cgImage = image.cgImage else { return deferMaybe(image) } let rect = CGRect(origin: .zero, size: image.size) context.setFillColor(icon.color.cgColor) context.fill(rect) context.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: rect.height)) context.draw(cgImage, in: rect) guard let imageWithBackground = UIGraphicsGetImageFromCurrentImageContext() else { return deferMaybe(image) } return deferMaybe(imageWithBackground) } let domain = url.shortDisplayString if multiRegionTopSitesDomains.contains(domain), let icon = topSitesIcons[domain] { return imageFor(icon: icon) } let urlWithoutScheme = url.absoluteDisplayString.remove("\(url.scheme ?? "")://") if let baseDomain = url.baseDomain, let icon = topSitesIcons[baseDomain] ?? topSitesIcons[urlWithoutScheme] { return imageFor(icon: icon) } return deferMaybe(FaviconLookupError(siteURL: site.url)) } // Retrieve's a site's favicon URL from the web. fileprivate func lookupFaviconURLFromWebPage(forSite site: Site) -> Deferred<Maybe<URL>> { guard let url = URL(string: site.url) else { return deferMaybe(FaviconLookupError(siteURL: site.url)) } let deferred = CancellableDeferred<Maybe<URL>>() getFaviconURLsFromWebPage(url: url).upon { result in guard let faviconURLs = result.successValue, let faviconURL = faviconURLs.first else { deferred.fill(Maybe(failure: FaviconLookupError(siteURL: site.url))) return } deferred.fill(Maybe(success: faviconURL)) } return deferred } // Scrapes an HTMLDocument DOM from a web page URL. fileprivate func getHTMLDocumentFromWebPage(url: URL) -> Deferred<Maybe<HTMLDocument>> { let deferred = CancellableDeferred<Maybe<HTMLDocument>>() // getHTMLDocumentFromWebPage can be called from getFaviconURLsFromWebPage, and that function is off-main. DispatchQueue.main.async { urlSession.dataTask(with: url) { (data, response, error) in guard error == nil, let data = data, let document = try? HTMLDocument(data: data) else { deferred.fill(Maybe(failure: FaviconLookupError(siteURL: url.absoluteString))) return } deferred.fill(Maybe(success: document)) }.resume() } return deferred } // Scrapes the web page at the specified URL for its favicon URLs. fileprivate func getFaviconURLsFromWebPage(url: URL) -> Deferred<Maybe<[URL]>> { return getHTMLDocumentFromWebPage(url: url).bind { result in guard let document = result.successValue else { return deferMaybe(FaviconLookupError(siteURL: url.absoluteString)) } // If we were redirected via a <meta> tag on the page to a different // URL, go to the redirected page for the favicon instead. for meta in document.xpath("//head/meta") { if let refresh = meta["http-equiv"], refresh == "Refresh", let content = meta["content"], let index = content.range(of: "URL="), let reloadURL = URL(string: String(content[index.upperBound...])), reloadURL != url { return self.getFaviconURLsFromWebPage(url: reloadURL) } } var icons = [URL]() // Iterate over each <link rel="icon"> tag on the page. for link in document.xpath("//head//link[contains(@rel, 'icon')]") { // Only consider <link rel="icon"> tags with an [href] attribute. if let href = link["href"], let faviconURL = URL(string: href, relativeTo: url) { icons.append(faviconURL) } } // Also, consider a "/favicon.ico" icon at the root of the domain. if let faviconURL = URL(string: "/favicon.ico", relativeTo: url) { icons.append(faviconURL) } return deferMaybe(icons) } } // Generates a "default" favicon based on the first character in the // site's domain name or gets an already-generated icon from the cache. fileprivate func generateDefaultFaviconImage(forSite site: Site) -> Deferred<Maybe<UIImage>> { let deferred = Deferred<Maybe<UIImage>>() DispatchQueue.main.async { guard let url = URL(string: site.url), let character = url.baseDomain?.first else { deferred.fill(Maybe(success: defaultFavicon)) return } let faviconLetter = String(character).uppercased() if let cachedFavicon = defaultFaviconImageCache[faviconLetter] { deferred.fill(Maybe(success: cachedFavicon)) return } func generateBackgroundColor(forURL url: URL) -> UIColor { guard let hash = url.baseDomain?.hashValue else { return UIColor.Photon.Grey50 } let index = abs(hash) % (DefaultFaviconBackgroundColors.count - 1) let colorHex = DefaultFaviconBackgroundColors[index] return UIColor(colorString: colorHex) } var image = UIImage() let label = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 60)) label.text = faviconLetter label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 40, weight: UIFont.Weight.medium) label.textColor = UIColor.Photon.White100 UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0.0) let rect = CGRect(origin: .zero, size: label.bounds.size) let context = UIGraphicsGetCurrentContext()! context.setFillColor(generateBackgroundColor(forURL: url).cgColor) context.fill(rect) label.layer.render(in: context) image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() defaultFaviconImageCache[faviconLetter] = image deferred.fill(Maybe(success: image)) } return deferred } }
a0d9c6100c886445620767e23b1db6c1
40.659794
152
0.607605
false
false
false
false
dannofx/AudioPal
refs/heads/master
AudioPal/AudioPal/NetService+Utils.swift
mit
1
// // NetService+Utils.swift // AudioPal // // Created by Danno on 5/31/17. // Copyright © 2017 Daniel Heredia. All rights reserved. // import UIKit extension NetService { var baseName: String { get { let tuple = parseNameData() if tuple == nil { return "" } return tuple!.base } } public convenience init(domain: String, type: String, baseName: String, uuid: UUID, port: Int32) { let customServiceName = "\(uuid.uuidString)|\(baseName)" self.init(domain: "\(domain).", type: serviceType, name: customServiceName, port: 0) } var uuid: UUID? { get { let tuple = parseNameData() if tuple == nil { return nil } return tuple!.uuid } } var version: Int { let tuple = parseNameData() if tuple == nil { return -1 } return tuple!.version } private func parseNameData() -> (base: String, uuid: UUID, version: Int)? { var elements = self.name.components(separatedBy: "|") if elements.count < 2 { return nil } let uuidString = elements[0] let uuid = NSUUID(uuidString: uuidString)! as UUID elements = elements[1].components(separatedBy: " (") let base = elements[0] var version = 0 if elements.count == 2 { var versionString = elements[1] versionString = versionString.replacingOccurrences(of: ")", with: "") version = Int(versionString)! } return (base, uuid, version) } }
b80bc5190677d27553ba37596d4d46e2
24.865672
100
0.512983
false
false
false
false
JuanjoArreola/AllCache
refs/heads/master
Sources/AllCache/ElementDescriptor.swift
mit
1
// // ElementDescriptor.swift // AllCache // // Created by JuanJo on 13/05/20. // import Foundation public struct ElementDescriptor<T, F: Fetcher> where F.T == T { public var key: String public var fetcher: F? public var processor: Processor<T>? public var descriptorKey: String { if let processor = processor { return [key, processor.key].joined(separator: "-") } return key } public init(key: String, fetcher: F?, processor: Processor<T>?) { self.key = key self.fetcher = fetcher self.processor = processor } }
1aa4af505195b71bba4bf3ea4712252c
21.814815
69
0.600649
false
false
false
false
JamesWatling/actor-platform
refs/heads/master
actor-apps/app-ios/Actor/Controllers/Compose/ComposeController.swift
mit
15
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit class ComposeController: ContactsBaseViewController, UISearchBarDelegate, UISearchDisplayDelegate { @IBOutlet weak var tableView: UITableView! var searchView: UISearchBar? var searchDisplay: UISearchDisplayController? var searchSource: ContactsSearchSource? init() { super.init(contentSection: 1, nibName: "ComposeController", bundle: nil) self.navigationItem.title = NSLocalizedString("ComposeTitle", comment: "Compose Title") self.extendedLayoutIncludesOpaqueBars = true } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { view.backgroundColor = UIColor.whiteColor() bindTable(tableView, fade: true) searchView = UISearchBar() searchView!.delegate = self searchView!.frame = CGRectMake(0, 0, 0, 44) searchView!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light MainAppTheme.search.styleSearchBar(searchView!) searchDisplay = UISearchDisplayController(searchBar: searchView, contentsController: self) searchDisplay?.searchResultsDelegate = self searchDisplay?.searchResultsTableView.rowHeight = 56 searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None searchDisplay?.searchResultsTableView.backgroundColor = Resources.BackyardColor searchDisplay?.searchResultsTableView.frame = tableView.frame var header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44)) header.addSubview(searchView!) var headerShadow = UIImageView(frame: CGRectMake(0, -4, 320, 4)); headerShadow.image = UIImage(named: "CardTop2"); headerShadow.contentMode = UIViewContentMode.ScaleToFill; header.addSubview(headerShadow); tableView.tableHeaderView = header searchSource = ContactsSearchSource(searchDisplay: searchDisplay!) super.viewDidLoad() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 1) { return super.tableView(tableView, numberOfRowsInSection: section) } else { return 2 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if (indexPath.section == 1) { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) } else { if (indexPath.row == 1) { let reuseId = "create_group"; var res = ContactActionCell(reuseIdentifier: reuseId) res.bind("ic_add_user", actionTitle: NSLocalizedString("CreateGroup", comment: "Create Group"), isLast: false) return res } else { let reuseId = "find_public"; var res = ContactActionCell(reuseIdentifier: reuseId) res.bind("ic_add_user", actionTitle: NSLocalizedString("Join public group", comment: "Create Group"), isLast: false) return res } } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (tableView == self.tableView) { if (indexPath.section == 0) { if (indexPath.row == 0) { navigateNext(DiscoverViewController(), removeCurrent: true) } else { navigateNext(GroupCreateViewController(), removeCurrent: true) } MainAppTheme.navigation.applyStatusBar() } else { var contact = objectAtIndexPath(indexPath) as! AMContact navigateToMessagesWithPeerId(contact.getUid()) } } else { var contact = searchSource!.objectAtIndexPath(indexPath) as! AMContact navigateToMessagesWithPeerId(contact.getUid()) } } // MARK: - // MARK: Navigation private func navigateToMessagesWithPeerId(peerId: jint) { navigateNext(ConversationViewController(peer: AMPeer.userWithInt(peerId)), removeCurrent: true) MainAppTheme.navigation.applyStatusBar() } func createGroup() { navigateNext(GroupCreateViewController(), removeCurrent: true) MainAppTheme.navigation.applyStatusBar() } }
392ff1ea55b42811c0914d6979e21010
37.926829
132
0.633173
false
false
false
false
SwiftAndroid/swift
refs/heads/master
test/1_stdlib/Reflection.swift
apache-2.0
2
// RUN: rm -rf %t && mkdir %t // RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -o %t/a.out // RUN: %S/timeout.sh 360 %target-run %t/a.out | FileCheck %s // REQUIRES: executable_test // FIXME: timeout wrapper is necessary because the ASan test runs for hours // // DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift. // import Swift // A more interesting struct type. struct Complex<T> { let real, imag: T } // CHECK-LABEL: Complex: print("Complex:") // CHECK-NEXT: Reflection.Complex<Swift.Double> // CHECK-NEXT: real: 1.5 // CHECK-NEXT: imag: 0.75 dump(Complex<Double>(real: 1.5, imag: 0.75)) // CHECK-NEXT: Reflection.Complex<Swift.Double> // CHECK-NEXT: real: -1.5 // CHECK-NEXT: imag: -0.75 dump(Complex<Double>(real: -1.5, imag: -0.75)) // CHECK-NEXT: Reflection.Complex<Swift.Int> // CHECK-NEXT: real: 22 // CHECK-NEXT: imag: 44 dump(Complex<Int>(real: 22, imag: 44)) // CHECK-NEXT: Reflection.Complex<Swift.String> // CHECK-NEXT: real: "is this the real life?" // CHECK-NEXT: imag: "is it just fantasy?" dump(Complex<String>(real: "is this the real life?", imag: "is it just fantasy?")) // Test destructuring of a pure Swift class hierarchy. class Good { let x: UInt = 11 let y: String = "222" } class Better : Good { let z: Double = 333.5 } class Best : Better { let w: String = "4444" } // CHECK-LABEL: Root class: // CHECK-NEXT: Reflection.Good #0 // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" print("Root class:") dump(Good()) // CHECK-LABEL: Subclass: // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("Subclass:") dump(Best()) // Test protocol types, which reflect as their dynamic types. // CHECK-LABEL: Any int: // CHECK-NEXT: 1 print("Any int:") var any: Any = 1 dump(any) // CHECK-LABEL: Any class: // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("Any class:") any = Best() dump(any) // CHECK-LABEL: second verse // CHECK-NEXT: Reflection.Best #0 print("second verse same as the first:") dump(any) // CHECK-LABEL: Any double: // CHECK-NEXT: 2.5 print("Any double:") any = 2.5 dump(any) // CHECK-LABEL: Character: // CHECK-NEXT: "a" print("Character:") dump(Character("a")) let range = 3...9 // CHECK-NEXT: Range(3..<10) // CHECK-NEXT: startIndex: 3 // CHECK-NEXT: endIndex: 10 dump(range) protocol Fooable {} extension Int : Fooable {} extension Double : Fooable {} // CHECK-LABEL: Fooable int: // CHECK-NEXT: 1 print("Fooable int:") var fooable: Fooable = 1 dump(fooable) // CHECK-LABEL: Fooable double: // CHECK-NEXT: 2.5 print("Fooable double:") fooable = 2.5 dump(fooable) protocol Barrable : class {} extension Best: Barrable {} // CHECK-LABEL: Barrable class: // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("Barrable class:") var barrable: Barrable = Best() dump(barrable) // CHECK-LABEL: second verse // CHECK-NEXT: Reflection.Best #0 // CHECK-NEXT: super: Reflection.Better // CHECK-NEXT: super: Reflection.Good // CHECK-NEXT: x: 11 // CHECK-NEXT: y: "222" // CHECK-NEXT: z: 333.5 // CHECK-NEXT: w: "4444" print("second verse same as the first:") dump(barrable) // CHECK-NEXT: Logical: true switch true.customPlaygroundQuickLook { case .bool(let x): print("Logical: \(x)") default: print("wrong quicklook type") } // CHECK-NEXT: Optional("Hello world") // CHECK-NEXT: some: "Hello world" dump(Optional<String>("Hello world")) // CHECK-NEXT: - nil let noneString: String? = nil dump(noneString) let intArray = [1,2,3,4,5] // CHECK-NEXT: 5 elements // CHECK-NEXT: 1 // CHECK-NEXT: 2 // CHECK-NEXT: 3 // CHECK-NEXT: 4 // CHECK-NEXT: 5 dump(intArray) var justSomeFunction = { (x:Int) -> Int in return x + 1 } // CHECK-NEXT: (Function) dump(justSomeFunction as Any) // CHECK-NEXT: Swift.String dump(String.self) // CHECK-NEXT: Swift.CollectionOfOne<Swift.String> // CHECK-NEXT: element: "Howdy Swift!" dump(CollectionOfOne("Howdy Swift!")) // CHECK-NEXT: EmptyCollection var emptyCollectionOfInt: EmptyCollection<Int> = EmptyCollection() dump(emptyCollectionOfInt) // CHECK-NEXT: ▿ // CHECK-NEXT: from: 1.0 // CHECK-NEXT: through: 12.15 // CHECK-NEXT: by: 3.14 dump(stride(from: 1.0, through: 12.15, by: 3.14)) // CHECK-NEXT: nil var nilUnsafeMutablePointerString: UnsafeMutablePointer<String>? = nil dump(nilUnsafeMutablePointerString) // CHECK-NEXT: 123456 // CHECK-NEXT: - pointerValue: 1193046 var randomUnsafeMutablePointerString = UnsafeMutablePointer<String>( bitPattern: 0x123456)! dump(randomUnsafeMutablePointerString) // CHECK-NEXT: Hello panda var sanePointerString = UnsafeMutablePointer<String>(allocatingCapacity: 1) sanePointerString.initialize(with: "Hello panda") dump(sanePointerString.pointee) sanePointerString.deinitialize() sanePointerString.deallocateCapacity(1) // Don't crash on types with opaque metadata. rdar://problem/19791252 // CHECK-NEXT: (Opaque Value) var rawPointer = unsafeBitCast(0 as Int, to: Builtin.RawPointer.self) dump(rawPointer) // CHECK-LABEL: and now our song is done print("and now our song is done")
b0bffaca94b3125ba7faa5f38097accf
25.357798
80
0.660285
false
false
false
false
JaSpa/swift
refs/heads/master
test/Compatibility/unsatisfiable_req.swift
apache-2.0
3
// RUN: %target-typecheck-verify-swift -swift-version 3 protocol P { associatedtype A associatedtype B func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B // expected-warning{{adding constraint 'Self.B == Self.A' on 'Self' via instance method requirement 'f' is deprecated}} // expected-note@-1{{protocol requires function 'f' with type '<T> (T) -> ()'; do you want to add a stub?}} } extension P { func f<T: P>(_: T) where T.A == Self.A, T.A == Self.B { } // expected-note{{candidate has non-matching type '<Self, T> (T) -> ()'}} } struct X : P { // expected-error{{type 'X' does not conform to protocol 'P'}} typealias A = X typealias B = Int } struct Y : P { typealias A = Y typealias B = Y }
46cf9b0745f73cf3c4b2d3d52cdfe53d
29.083333
175
0.623269
false
false
false
false
sugarAndsugar/ProgressOverlay
refs/heads/master
ProgressOverlayTest/ProgressOverlay/ProgressOverlay.swift
bsd-3-clause
1
// // ProgressOverlay.swift // ProgressOverlayTest // // Created by xiangkai yin on 16/9/7. // Copyright © 2016年 kuailao_2. All rights reserved. // // // swift 重写 MBProgressOverlay import UIKit public enum ProgressOverlayAnimation:Int { /// Opacity animation (不透明度动画) case fade // Opacity + scale animation (zoom in when appearing zoom out when disappearing) 不透明度+缩放动画(出现时放大缩小消失时) case zoom // Opacity + scale animation (zoom out style) 不透明度+缩放动画(缩小) case zoomOut // Opacity + scale animation (zoom in style) 不透明度+缩放动画(放大) case zoomIn } public enum ProgressOverlayMode: Int { /// UIActivityIndicatorView. case indeterminate /// A round, pie-chart like, progress view. (一个圆,像饼图一样的进度条视图) case determinate /// Horizontal progress bar. (水平进度条) case determinateHorizontalBar /// Ring-shaped progress view. (环形进度条) case annularDeterminate /// Shows a custom view. (显示自定义视图) case customView /// Shows only labels. (仅显示标签) case text } let ProgressOverlayMaxOffset:CGFloat = (UIScreen.main.bounds.size.height - 120)/2 let PODefaultLabelFontSize:CGFloat = 16.0 let PODefaultPadding = 4.0 let PODefaultDetailsLabelFontSize:CGFloat = 12.0 typealias ProgressOverlayCompletionBlock = ()-> () /* * Displays a simple Overlay window containing a progress indicator and two optional labels for short messages. * * This is a simple drop-in class for displaying a progress Overlay view similar to Apple's private UIProgressOverlay class. * The ProgressOverlay window spans over the entire space given to it by the initWithFrame: constructor and catches all * user input on this region, thereby preventing the user operations on components below the view. * * @note To still allow touches to pass through the Overlay, you can set Overlay.userInteractionEnabled = NO. * @attention ProgressOverlay is a UI class and should therefore only be accessed on the main thread. * 一个简单的覆盖窗口,用来显示包含进度指示器和短消息两种可选标签 */ class ProgressOverlay: UIView { // MARK: - Properties /// The animation type that should be used when the Overlay is shown and hidden. default fade (动画显示和隐藏的类型,默认 fade) var animationType: ProgressOverlayAnimation! fileprivate var modeProperty:ProgressOverlayMode = .indeterminate /// ProgressOverlay operation mode. The default is Indeterminate. (ProgressOverlay 显示模式 ,默认是 Indeterminate) var mode:ProgressOverlayMode { set { if newValue != modeProperty { modeProperty = newValue self.updateIndicators() } } get { return modeProperty } } /* The amount of space between the ProgressOverlay edge and the ProgressOverlay elements (labels, indicators or custom views). * This also represents the minimum bezel distance to the edge of the Overlay view. * Defaults to 20.f * (labels, indicators or custom views) 与 边缘之间的间距 默认 20.0 */ var margin:CGFloat = 20 fileprivate var minSizeProperty:CGSize = CGSize.zero /** The minimum size of the Overlay bezel. Defaults to CGSizeZero (no minimum size). */ var minSize:CGSize { set { if !newValue.equalTo(minSizeProperty) { minSizeProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsUpdateConstraints() }) } } get { return minSizeProperty } } /** Force the Overlay dimensions to be equal if possible. (正方形) */ var square = false fileprivate var offsetProperty:CGPoint = CGPoint.zero /** * The bezel offset relative to the center of the view. You can use ProgressOverlayMaxOffset * and -ProgressOverlayMaxOffset to move the Overlay all the way to the screen edge in each direction. * E.g., CGPointMake(0.f, ProgressOverlayMaxOffset) would position the Overlay centered on the bottom edge. */ var offset:CGPoint { set { if !offsetProperty.equalTo(newValue) { offsetProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsUpdateConstraints() }) } } get { return self.offsetProperty } } /// When enabled, the bezel center gets slightly affected by the device accelerometer data. Defaults to true (是否被加速计影响) var defaultMotionEffectsEnabled:Bool! fileprivate var contentColorProperty:UIColor = UIColor.init(white: 0.0, alpha: 0.7) /* A color that gets forwarded to all labels and supported indicators. Also sets the tintColor () * for custom views on iOS 7+. Set to nil to manage color individually. * (labels 和 indicators) 的颜色 */ var contentColor:UIColor { set { if newValue != contentColorProperty { self.contentColorProperty = newValue self.updateViewsForColor(newValue) } } get { return self.contentColorProperty } } /** Called after the Overlay is hiden. */ var completionBlock:ProgressOverlayCompletionBlock? /// View covering the entire overlay area, placed behind bezelView. (最后面的覆盖区域) var backgroundView:OverlayBackgroundView! /// The view containing the labels and indicator (or customView). (包含标签和指示(或自定义视图)的视图。) fileprivate var bezelView:OverlayBackgroundView! /// A label that holds an optional short message to be displayed below the activity indicator. The Overlay is automatically resized to fit /// the entire text. (自适应文本内容标签) var label:UILabel! /// A label that holds an optional details message displayed below the labelText message. The details text can span multiple lines. (显示在下方的多行文本标签) var detailsLabel:UILabel! /// A button that is placed below the labels. Visible only if a target / action is added. (放置在标签下方的按钮) var button:UIButton! var topSpacer:UIView! var bottomSpacer:UIView! var indicator:UIView? var minShowTimer:Timer? var graceTimer:Timer? var userAnimation:Bool = true var finished:Bool = false var hideDelayTimer:Timer? var showStarted:Date? var progressObjectDisplayLink: CADisplayLink? var bezelConstraints = [NSLayoutConstraint]() var paddingConstraints = [NSLayoutConstraint]() // MARK: - Class methods internal class func showOnView(_ view:UIView! ,animated:Bool) -> ProgressOverlay { let overlay = ProgressOverlay.init(view: view) overlay.removeFromSuperViewOnHide = true view.addSubview(overlay) overlay.showAnimated(animated) return overlay } internal class func hideAllOverlaysForView(_ view:UIView! ,animated:Bool) -> Bool { if let overlay:ProgressOverlay = self.hideForView(view) { overlay.removeFromSuperViewOnHide = true overlay.hideAnimated(animated) return true } return false } internal class func hideForView(_ view:UIView!) -> ProgressOverlay? { for subView in view.subviews { if subView .isKind(of: self) { return subView as? ProgressOverlay } } return nil } // MARK: - Lifecycle fileprivate func commonInit() { // Set default values for properties (设置) animationType = .fade mode = .indeterminate margin = 20.0 defaultMotionEffectsEnabled = true // Default color (默认颜色) contentColor = UIColor.init(white: 0.0, alpha: 0.7) // Transparent background (透明背景) self.isOpaque = false self.backgroundColor = UIColor.clear // Make it invisible for now (当前不可见) self.alpha = 0.0 self.autoresizingMask = UIView.AutoresizingMask.init(rawValue: UIView.AutoresizingMask.flexibleWidth.rawValue | UIView.AutoresizingMask.flexibleHeight.rawValue) // group opacity (这项属性默认是启用的。当它被启用时,一些动画将会变得不流畅,它也可以在layer层上被控制) self.layer.allowsGroupOpacity = false self.setupViews() self.updateIndicators() self.registerForNotifications() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } convenience init(view:UIView) { self.init(frame:view.bounds) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } deinit { self.unregisterFromNofifications() } // MARK: - UI fileprivate func setupViews() { let defaultColor = self.contentColor let backgroundView = OverlayBackgroundView.init(frame: self.bounds) backgroundView.style = .solidColor backgroundView.backgroundColor = UIColor.clear backgroundView.autoresizingMask = UIView.AutoresizingMask.init(rawValue: UIView.AutoresizingMask.flexibleWidth.rawValue | UIView.AutoresizingMask.flexibleHeight.rawValue) backgroundView.alpha = 0.0 self.addSubview(backgroundView) self.backgroundView = backgroundView let bezelView = OverlayBackgroundView() bezelView.translatesAutoresizingMaskIntoConstraints = false bezelView.layer.cornerRadius = 5.0 bezelView.alpha = 0.0 self.addSubview(bezelView) self.bezelView = bezelView self.updateBezelMotionEffects() let label = UILabel() //文本自动适应宽度 label.adjustsFontSizeToFitWidth = false label.textAlignment = .center label.textColor = defaultColor label.font = UIFont.boldSystemFont(ofSize: PODefaultLabelFontSize) label.isOpaque = false label.backgroundColor = UIColor.clear self.label = label let detailsLabel = UILabel() detailsLabel.adjustsFontSizeToFitWidth = false detailsLabel.textAlignment = .center detailsLabel.textColor = defaultColor detailsLabel.numberOfLines = 0 detailsLabel.font = UIFont.boldSystemFont(ofSize: PODefaultDetailsLabelFontSize) detailsLabel.isOpaque = false detailsLabel.backgroundColor = UIColor.clear self.detailsLabel = detailsLabel let button = OverlayRoundedButton(type:.custom) button.titleLabel?.textAlignment = .center button.titleLabel?.font = UIFont.boldSystemFont(ofSize: PODefaultDetailsLabelFontSize) button.setTitleColor(defaultColor, for: UIControl.State()) self.button = button for view in [label,detailsLabel,button] { view.translatesAutoresizingMaskIntoConstraints = false view.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 998), for: .horizontal) view.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 998), for: .vertical) bezelView.addSubview(view) } let topSpacer = UIView() topSpacer.translatesAutoresizingMaskIntoConstraints = false topSpacer.isHidden = true bezelView.addSubview(topSpacer) self.topSpacer = topSpacer let bottomSpacer = UIView() bottomSpacer.translatesAutoresizingMaskIntoConstraints = false bottomSpacer.isHidden = true bezelView.addSubview(bottomSpacer) self.bottomSpacer = bottomSpacer } func updateIndicators() { var isActivityIndicator = false var isRoundIndicator = false var indicator = self.indicator if indicator != nil{ isActivityIndicator = indicator!.isKind(of: UIActivityIndicatorView.classForCoder()) isRoundIndicator = indicator!.isKind(of: OverlayBackgroundView.self) } let mode = self.mode if mode == ProgressOverlayMode.indeterminate { if !isActivityIndicator { // Update to indeterminate indicator (更新) indicator?.removeFromSuperview() indicator = UIActivityIndicatorView.init(style: .whiteLarge) (indicator as! UIActivityIndicatorView).startAnimating() self.bezelView.addSubview(indicator!) } } else if (mode == ProgressOverlayMode.determinateHorizontalBar) { // Update to bar determinate indicator indicator?.removeFromSuperview() indicator = OverlayBarProgressView() self.bezelView.addSubview(indicator!) } else if (mode == ProgressOverlayMode.determinate || mode == ProgressOverlayMode.annularDeterminate) { if !isRoundIndicator { // Update to determinante indicator indicator?.removeFromSuperview() indicator = OverlayRoundProgressView.init() self.bezelView.addSubview(indicator!) } if mode == ProgressOverlayMode.annularDeterminate { (indicator as! OverlayRoundProgressView).annular = true } } else if (mode == ProgressOverlayMode.customView && self.customView != indicator) { indicator?.removeFromSuperview() indicator = self.customView self.bezelView.addSubview(indicator!) } else if (mode == ProgressOverlayMode.text) { indicator?.removeFromSuperview() indicator = nil } indicator?.translatesAutoresizingMaskIntoConstraints = false self.indicator = indicator if indicator?.responds(to: #selector(self.forProgress(_:))) == true { indicator?.setValue(self.progress, forKey: "progress") } indicator?.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 998), for: .horizontal) indicator?.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 998), for: .vertical) self.updateViewsForColor(self.contentColor) self.setNeedsUpdateConstraints() } func updateViewsForColor(_ color:UIColor) { self.label.textColor = color self.detailsLabel.textColor = color self.button.setTitleColor(color, for: UIControl.State()) //UIAppearance settings are prioritized. If they are preset the set color is ignored. (UIAppearance 设置优先级) let indicator = self.indicator if indicator?.isKind(of: UIActivityIndicatorView.classForCoder()) == true { let appearance:UIActivityIndicatorView? appearance = UIActivityIndicatorView.appearance(whenContainedInInstancesOf: [ProgressOverlay.classForCoder() as! UIAppearanceContainer.Type]) if appearance?.color == nil { (indicator as! UIActivityIndicatorView).color = color } } else if indicator?.isKind(of: OverlayRoundProgressView.classForCoder()) == true { let opView = (indicator as! OverlayRoundProgressView) opView.progressTintColor = color opView.backgroundTintColor = color.withAlphaComponent(0.1) } else if indicator?.isKind(of: OverlayBarProgressView.classForCoder()) == true { let obpView = indicator as! OverlayBarProgressView obpView.progressColor = color obpView.lineColor = color } else { indicator?.tintColor = color } } func updateBezelMotionEffects() { let bezelView = self.bezelView if self.defaultMotionEffectsEnabled == true { //视觉差效果 let effectOffset:Float = 10.0 let effectX:UIInterpolatingMotionEffect = UIInterpolatingMotionEffect.init(keyPath: "center.x", type: .tiltAlongHorizontalAxis) effectX.maximumRelativeValue = effectOffset effectX.minimumRelativeValue = -effectOffset let effectY:UIInterpolatingMotionEffect = UIInterpolatingMotionEffect.init(keyPath: "center.y", type: .tiltAlongVerticalAxis) effectY.maximumRelativeValue = effectOffset effectY.minimumRelativeValue = -effectOffset let group:UIMotionEffectGroup = UIMotionEffectGroup.init() group.motionEffects = [effectX,effectY] bezelView?.addMotionEffect(group) } else { let effects = bezelView?.motionEffects for effect in effects! { bezelView?.removeMotionEffect(effect) } } } // MARK: - Layout override func updateConstraints() { let bezel = self.bezelView! let topSpacer = self.topSpacer! let bottomSpacer = self.bottomSpacer! let margin:CGFloat = self.margin var bezelConstraints = Array<NSLayoutConstraint>() let metrics = ["margin":margin] var subviews = [self.topSpacer,self.label,self.detailsLabel,self.button,self.bottomSpacer] if self.indicator != nil { subviews.insert(self.indicator, at: 1) } // Remove existing constraints self.removeConstraints(self.constraints) topSpacer.removeConstraints(topSpacer.constraints) bottomSpacer.removeConstraints(bottomSpacer.constraints) if self.bezelConstraints.count > 0 { bezel.removeConstraints(self.bezelConstraints ) self.bezelConstraints = [] } // Center bezel in container (self), applying the offset if set (控制约束 let offset = self.offset var centeringConstraints:Array = [NSLayoutConstraint]() centeringConstraints.append(NSLayoutConstraint.init(item: bezel, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: offset.x)) centeringConstraints.append(NSLayoutConstraint.init(item: bezel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: offset.y)) self.applyPriority(UILayoutPriority(rawValue: 999), constraints: centeringConstraints) self.addConstraints(centeringConstraints) // Ensure minimum side margin is kept (保证最小的侧边 VFL) var sideConstraints = Array<NSLayoutConstraint>() sideConstraints += NSLayoutConstraint.constraints(withVisualFormat: "|-(>=margin)-[bezel]-(>=margin)-|", options: NSLayoutConstraint.FormatOptions(), metrics: metrics, views: ["bezel":bezel]) sideConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=margin)-[bezel]-(>=margin)-|", options: NSLayoutConstraint.FormatOptions(), metrics: metrics, views: ["bezel":bezel]) self.applyPriority(UILayoutPriority(rawValue: 999), constraints: sideConstraints) self.addConstraints(sideConstraints) // Minmum bezel size,if set (bezel 最小尺寸) let minimumSize = self.minSize if !minimumSize.equalTo(CGSize.zero) { var minSizeConstraints = Array<NSLayoutConstraint>() minSizeConstraints.append(NSLayoutConstraint.init(item: bezel, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: minimumSize.width)) minSizeConstraints.append(NSLayoutConstraint.init(item: bezel, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: minimumSize.height)) self.applyPriority(UILayoutPriority(rawValue: 997), constraints: minSizeConstraints) bezelConstraints += minSizeConstraints } // Square aspect ratio, if set (宽高比) if self.square { let square = NSLayoutConstraint.init(item: bezel, attribute: .height, relatedBy: .equal, toItem: bezel, attribute: .width, multiplier: 1.0, constant: 0) square.priority = UILayoutPriority(rawValue: 997) bezelConstraints.append(square) } // Top and bottom spacing (上下边距) topSpacer.addConstraint(NSLayoutConstraint.init(item: topSpacer, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: margin)) bottomSpacer.addConstraint(NSLayoutConstraint.init(item: bottomSpacer, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: margin)) // Top and bottom spaces should be equal (上下边距应保持一致) bezelConstraints.append(NSLayoutConstraint.init(item: topSpacer, attribute: .height, relatedBy: .equal, toItem: bottomSpacer, attribute: .height, multiplier: 1.0, constant: 0.0)) // Layout subviews in bezel (重置子视图约束) var paddingConstraints = Array<NSLayoutConstraint>() let subViewsNS:NSArray = subviews as NSArray for (idx,view) in subviews.enumerated() { // Center in bezel (居中) bezelConstraints.append(NSLayoutConstraint.init(item: view!, attribute: .centerX, relatedBy: .equal, toItem: bezel, attribute: .centerX, multiplier: 1.0, constant: 0.0)) // Ensure the minimum edge margin is kept bezelConstraints += NSLayoutConstraint.constraints(withVisualFormat: "|-(>=margin)-[view]-(>=margin)-|", options: NSLayoutConstraint.FormatOptions(), metrics: metrics, views: ["view":view!]) // Element spacing if idx == 0 { // First, ensure spacing to bezel edge bezelConstraints.append(NSLayoutConstraint.init(item: view!, attribute: NSLayoutConstraint.Attribute.top, relatedBy: .equal, toItem: bezel, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 0.0)) } else if (idx == subViewsNS.count - 1) { // Last, ensure spacing to bezel edge bezelConstraints.append(NSLayoutConstraint.init(item: view!, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: .equal, toItem: bezel, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: 0.0)) } if idx > 0 { // Has previous let itemView:UIView = subViewsNS[idx - 1] as! UIView let padding = NSLayoutConstraint.init(item: view!, attribute: NSLayoutConstraint.Attribute.top, relatedBy: .equal, toItem: itemView, attribute: .bottom, multiplier: 1.0, constant: 0.0) bezelConstraints.append(padding) paddingConstraints.append(padding) } } bezel.addConstraints(bezelConstraints) self.bezelConstraints = bezelConstraints self.paddingConstraints = paddingConstraints self.updatePaddingConstraints() super.updateConstraints() } override func layoutSubviews() { if !self.needsUpdateConstraints() { self.updatePaddingConstraints() } super.layoutSubviews() } func updatePaddingConstraints() { // Set padding dynamically, depending on whether the view is visible or not (根据是否可见来设置视图) var hasVisibleAncestors = false for (_,pad) in self.paddingConstraints.enumerated() { let padding = pad let firstView = padding.firstItem let secondView = padding.secondItem let firstVisible = !(firstView?.isHidden)! && !(firstView?.intrinsicContentSize.equalTo(CGSize.zero))! let secondVisible = !secondView!.isHidden && !secondView!.intrinsicContentSize.equalTo(CGSize.zero) // Set if both views are visible or if there's a visible view on top that doesn't have padding // added relative to the current view yet padding.constant = CGFloat((firstVisible && (secondVisible || hasVisibleAncestors)) ? PODefaultPadding : 0.0) if hasVisibleAncestors || secondVisible { hasVisibleAncestors = true } } } func applyPriority(_ priority:UILayoutPriority,constraints:Array<AnyObject>) { for constraint in constraints { let conPro = constraint as! NSLayoutConstraint conPro.priority = priority } } // MARK: - Show & Hide func showAnimated(_ animated:Bool) { assert(Thread.isMainThread, "ProgressOverlay needs to be accessed on the main thread.") self.minShowTimer?.invalidate() self.userAnimation = animated self.finished = false if self.graceTime > 0.0 { let timer = Timer.init(timeInterval: self.graceTime, target: self, selector: #selector(self.handleGraceTimer(_:)), userInfo: nil, repeats: false) RunLoop.current.add(timer, forMode: RunLoop.Mode.common) self.graceTimer = timer } else { self.showUsingAnimation(animated) } } func hideAnimated(_ animated:Bool) { assert(Thread.isMainThread, "ProgressOverlay needs to be accessed on the main thread.") self.graceTimer?.invalidate() self.finished = true // If the minShow time is set, calculate how long the Overlay was shown, // and postpone the hiding operation if necessary if self.minShowTime > 0.0 && (self.showStarted != nil) { let interv:TimeInterval = Date().timeIntervalSince(self.showStarted!) if interv < self.minShowTime { let timer = Timer.init(timeInterval: self.minShowTime - interv, target: self, selector: #selector(self.handleMinShowTimer(_:)), userInfo: nil, repeats: false) RunLoop.current.add(timer, forMode: RunLoop.Mode.common) self.minShowTimer = timer return } } // ... otherwise hide the Overlay immediately self.hideUsingAnimation(self.userAnimation) } func hideAnimated(_ animated:Bool,delay:TimeInterval) { let timer = Timer.init(timeInterval:delay, target: self, selector: #selector(self.handleHideTimer(_:)), userInfo: animated, repeats: false) RunLoop.current.add(timer, forMode: RunLoop.Mode.common) self.hideDelayTimer = timer } // MARK: - Timer Callbacks @objc func handleGraceTimer(_ theTimer:Timer) { if !self.finished { self.showUsingAnimation(self.userAnimation) } } @objc func handleMinShowTimer(_ theTimer:Timer) { self.hideUsingAnimation(self.userAnimation) } @objc func handleHideTimer(_ theTimer:Timer) { self.hideAnimated(((theTimer.userInfo! as AnyObject).boolValue)!) } // MARK: - Internal show & hide operations fileprivate func showUsingAnimation(_ animated:Bool) { //Cancel any previous animations self.bezelView.layer.removeAllAnimations() self.backgroundView.layer.removeAllAnimations() //Cancel any scheduled hideDelayed: calls self.hideDelayTimer?.invalidate() self.showStarted = Date() self.alpha = 1.0 // Needed in case we hide and re-show with the same NSProgress object attached. self.setNSProgressDisplayLinkEnabled(true) if animated { self.animteIn(true, type: self.animationType, completion: {_ in }) } else { self.backgroundView.alpha = 1.0 } } fileprivate func hideUsingAnimation(_ animated:Bool) { if animated && (self.showStarted != nil) { self.showStarted = nil self.animteIn(false, type: self.animationType, completion: { (finished) in self.done() }) } else { self.showStarted = nil self.bezelView.alpha = 0.0 self.backgroundView.alpha = 1.0 self.done() } } fileprivate func animteIn(_ animatingIn:Bool,type:ProgressOverlayAnimation,completion:@escaping (_ finished:Bool) -> ()){ var type = type if type == ProgressOverlayAnimation.zoom { type = animatingIn ? ProgressOverlayAnimation.zoomIn : ProgressOverlayAnimation.zoomOut } let small = CGAffineTransform(scaleX: 0.5, y: 0.5) let large = CGAffineTransform(scaleX: 1.5, y: 1.5) let bezelView = self.bezelView if animatingIn && bezelView?.alpha == 0.0 && type == ProgressOverlayAnimation.zoomIn { bezelView?.transform = small } else if animatingIn && bezelView?.alpha == 0.0 && type == ProgressOverlayAnimation.zoomOut { bezelView?.transform = large } let animations = { if animatingIn { bezelView?.transform = CGAffineTransform.identity } else if !animatingIn && type == ProgressOverlayAnimation.zoomIn { bezelView?.transform = large } else if !animatingIn && type == ProgressOverlayAnimation.zoomOut { bezelView?.transform = small } bezelView?.alpha = animatingIn ? 1.0 : 0.0 self.backgroundView.alpha = animatingIn ? 1.0 : 0.0 } //Spring animations are nicer (弹性动画) UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .beginFromCurrentState, animations: animations, completion: completion) } fileprivate func done() { // Cancel any scheduled hideDelayed: calls (取消延迟) self.hideDelayTimer?.invalidate() self.setNSProgressDisplayLinkEnabled(false) if self.finished { self.alpha = 0.0 if self.removeFromSuperViewOnHide { self.removeFromSuperview() } } if let comBlock = self.completionBlock { comBlock() } } // MARK: - NSProgress fileprivate func setNSProgressDisplayLinkEnabled (_ enabled:Bool) { // We're using CADisplayLink, because NSProgress can change very quickly and observing it may starve the main thread, // so we're refreshing the progress only every frame draw if enabled && (self.progressObject != nil) { if self.progressObjectDisplayLink == nil { self.progressObjectDisplayLink = CADisplayLink.init(target: self, selector: #selector(self.updateProgressFormProgressObject)) } } else { self.progressObjectDisplayLink = nil } } @objc func updateProgressFormProgressObject() { self.progress = (self.progressObject?.fractionCompleted)! } // MARK: - Properties fileprivate var customViewProperty:UIView = UIView.init() /// The UIView (e.g., a UIImageView) to be shown when the Overlay is in CustomView. /// The view should implement intrinsicContentSize for proper sizing. For best results use approximately 37 by 37 pixels. var customView:UIView { set { if newValue != customViewProperty { customViewProperty = newValue self.updateIndicators() } } get { return customViewProperty } } /* Grace period is the time (in seconds) that the invoked method may be run without * showing the Overlay. If the task finishes before the grace time runs out, the Overlay will * not be shown at all. * This may be used to prevent Overlay display for very short tasks. * Defaults to 0 (no grace time). */ var graceTime:TimeInterval = 0.0 /* * The minimum time (in seconds) that the Overlay is shown. * This avoids the problem of the Overlay being shown and than instantly hidden. * Defaults to 0 (no minimum show time). */ var minShowTime:TimeInterval = 0.0 /// Removes the Overlay from its parent view when hidden. (自动隐藏) var removeFromSuperViewOnHide:Bool = true /// The NSProgress object feeding the progress information to the progress indicator. (进度指示器) fileprivate var progressObject:Progress? fileprivate var progress:Double = 0.0 @objc func forProgress(_ pro:Double) { if pro != progress { progress = pro let indicator = self.indicator if self.responds(to: #selector(self.forProgress(_:))) { indicator?.setValue(pro, forKey: "progress") } } } // MARK: - Notifications func registerForNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(self.statusBarOrientationDidChange(_:)), name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) } func unregisterFromNofifications(){ let nc = NotificationCenter.default nc.removeObserver(self, name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) } @objc func statusBarOrientationDidChange(_ nofification:Notification) { if self.superview != nil { self.updateForCurrentOrientationAnimated(true) } } func updateForCurrentOrientationAnimated(_ animated:Bool) { // Stay in sync with the superview in any case if self.superview != nil { self.bounds = (self.superview?.bounds)! } } } public enum OverlayBackgroundStyle { /// Solid color background (纯色背景) case solidColor /// UIVisualEffectView background view (模糊视图) case blur } class OverlayBackgroundView: UIView { fileprivate var effectView:UIVisualEffectView? /* Defaults to Blur on iOS 7 or later and SolidColor otherwise. * 背景样式 */ fileprivate var styleProperty:OverlayBackgroundStyle = .blur /// The background style. var style:OverlayBackgroundStyle { set { if styleProperty != newValue { self.styleProperty = newValue self.updateForBackgroundStyle() } } get { return self.styleProperty } } fileprivate var colorProperty:UIColor = UIColor.init(white: 0.8, alpha: 0.6) /// The background color or the blur tint color. (背景颜色) var color:UIColor { set { if colorProperty != newValue && !newValue.isEqual(colorProperty) { self.colorProperty = newValue self.updateViewsForColor(newValue) } } get { return self.colorProperty } } // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) style = .blur color = UIColor.init(white: 0.8, alpha: 0.6) self.clipsToBounds = true self.updateForBackgroundStyle() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override var intrinsicContentSize : CGSize { //Smallest size possible. Content pushes against this. (最小尺寸) return CGSize.zero } // MARK: - Views func updateForBackgroundStyle() { let style = self.style if style == .blur { // UIBlurEffect 毛玻璃 let effect = UIBlurEffect.init(style: .light) let effectView = UIVisualEffectView.init(effect: effect) self.addSubview(effectView) effectView.frame = self.frame effectView.autoresizingMask = UIView.AutoresizingMask.init(rawValue: UIView.AutoresizingMask.flexibleHeight.rawValue | UIView.AutoresizingMask.flexibleWidth.rawValue) self.backgroundColor = self.color self.layer.allowsGroupOpacity = false self.effectView = effectView } else { self.effectView?.removeFromSuperview() self.effectView = nil self.backgroundColor = self.color } } func updateViewsForColor(_ color:UIColor) { if self.style == .blur { self.backgroundColor = self.color } else { self.backgroundColor = self.color } } } /// RoundedButton 圆角按钮 class OverlayRoundedButton: UIButton { // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) let layer:CALayer = self.layer layer.borderWidth = 1.0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() //Fully rounded corners (圆角) let height = self.bounds.height // ceil 用于返回大于或者等于指定表达式的最小整数 self.layer.cornerRadius = ceil(height/2.0) } override var intrinsicContentSize : CGSize { // Only show if we have associated control events (只显示相关的控制事件) if self.allControlEvents.rawValue == 0 { return CGSize.zero } var size:CGSize = super.intrinsicContentSize // Add some side padding size.width += 20.0 return size } // MARK: - Color override func setTitleColor(_ color: UIColor?, for state: UIControl.State) { super.setTitleColor(color, for: state) // Update related colors (更新相关颜色) } override var isHighlighted: Bool { set { super.isHighlighted = newValue let baseColor:UIColor = self.titleColor(for: .selected)! self.backgroundColor = isHighlighted ? baseColor.withAlphaComponent(0.1) : UIColor.clear } get { return super.isHighlighted } } } /// OverlayBarProgressView class OverlayBarProgressView: UIView { fileprivate var progressProperty:CGFloat! /// Progress (0.0 to 1.0) var progress:CGFloat { set { if newValue != progressProperty { self.progressProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsDisplay() }) } } get { return self.progressProperty } } fileprivate var progressColorProperty:UIColor = UIColor.white /// Bar progress color. /// Defaults to white [UIColor whiteColor]. var progressColor:UIColor { set { if newValue != progressColorProperty && !progressColorProperty.isEqual(newValue) { self.progressColorProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsDisplay() }) } } get { return self.progressColorProperty } } fileprivate var progressRemainingColorProperty:UIColor = UIColor.clear /// Bar background color. /// Defaults to white [UIColor whiteColor]. var progressRemainingColor:UIColor { set { if newValue != progressRemainingColorProperty && !progressRemainingColorProperty.isEqual(newValue) { self.progressRemainingColorProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsDisplay() }) } } get { return self.progressRemainingColorProperty } } /// Bar border line color. var lineColor:UIColor = UIColor.white // MARK: - Lifecycle convenience init () { self.init(frame: CGRect(x: 0.0, y: 0.0, width: 120.0, height: 120.0)) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear self.isOpaque = false self.progress = 0.0 self.progressColor = UIColor.white self.progressRemainingColor = UIColor.clear self.lineColor = UIColor.white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override var intrinsicContentSize : CGSize { return CGSize(width: 120.0, height: 10.0) } // MARK: - Drawing override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context?.setLineWidth(2) context?.setStrokeColor(lineColor.cgColor) context?.setFillColor(self.progressRemainingColor.cgColor) // Draw background var radius = (rect.size.height / 2) - 2 context?.move(to: CGPoint(x: 2, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 2, y: 2), tangent2End: CGPoint.init(x: radius + 2, y: 2), radius: radius) context?.addLine(to: CGPoint(x: rect.size.width - radius - 2, y: 2)) context?.addArc(tangent1End: CGPoint.init(x: rect.size.width - 2, y: 2), tangent2End: CGPoint.init(x: rect.size.width - 2, y: rect.size.height / 2), radius: radius) context?.addArc(tangent1End: CGPoint.init(x: rect.size.width - 2, y: rect.size.height - 2), tangent2End: CGPoint.init(x: rect.size.width - radius - 2, y: rect.size.height - 2), radius: radius) context?.addLine(to: CGPoint(x: radius + 2, y: rect.size.height - 2)) context?.addArc(tangent1End: CGPoint.init(x: 2, y: rect.size.height - 2), tangent2End: CGPoint.init(x: 2, y: rect.size.height/2), radius: radius) context?.fillPath() // Draw border context?.move(to: CGPoint(x: 2, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 2, y: 2), tangent2End: CGPoint.init(x: radius + 2, y: 2), radius: radius) context?.addLine(to: CGPoint(x: rect.size.width - radius - 2, y: 2)) context?.addArc(tangent1End: CGPoint.init(x: rect.size.width - 2, y: 2), tangent2End: CGPoint.init(x: rect.size.width - 2, y: rect.size.height / 2), radius: radius) context?.addArc(tangent1End: CGPoint.init(x: rect.size.width - 2, y: rect.size.height - 2), tangent2End: CGPoint.init(x: rect.size.width - radius - 2, y: rect.size.height - 2), radius: radius) context?.addLine(to: CGPoint(x: radius + 2, y: rect.size.height - 2)) context?.addArc(tangent1End: CGPoint.init(x: 2, y: rect.size.height - 2), tangent2End: CGPoint.init(x: 2, y: rect.size.height/2), radius: radius) context?.strokePath() context?.setFillColor(self.progressColor.cgColor) radius = radius - 2 let amount = self.progress * rect.size.width // Progress in the middle area if (amount >= radius + 4 && amount <= (rect.size.width - radius - 4)) { context?.move(to: CGPoint(x: 4, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 4, y: 4), tangent2End: CGPoint.init(x: radius + 4, y: 4), radius: radius) context?.addLine(to: CGPoint(x: amount, y: 4)) context?.addLine(to: CGPoint(x: amount, y: radius + 4)) context?.move(to: CGPoint(x: 4, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 4, y: rect.size.height - 4), tangent2End: CGPoint.init(x: radius + 4, y: rect.size.height - 4), radius: radius) context?.addLine(to: CGPoint(x: amount, y: rect.size.height - 4)) context?.addLine(to: CGPoint(x: amount, y: radius + 4)) context?.fillPath() } // Progress in the right arc else if (amount > radius + 4) { let x = amount - (rect.size.width - radius - 4) context?.move(to: CGPoint(x: 4, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 4, y: 4), tangent2End: CGPoint.init(x: radius + 4, y: 4), radius: radius) context?.addLine(to: CGPoint(x: rect.size.width - radius - 4, y: 4)) var angle = -acos(x/radius) if (angle.isNaN){ angle = 0 } context?.addArc(center: CGPoint.init(x: rect.size.width - radius - 4, y: rect.size.height/2), radius: radius, startAngle: CGFloat(Double.pi), endAngle: angle, clockwise: false) context?.addLine(to: CGPoint(x: amount, y: rect.size.height/2)) context?.move(to: CGPoint(x: 4, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 4, y: rect.size.height - 4), tangent2End: CGPoint.init(x: radius + 4, y: rect.size.height - 4), radius: radius) context?.addLine(to: CGPoint(x: rect.size.width - radius - 4, y: rect.size.height - 4)) angle = acos(x/radius) if (angle.isNaN) { angle = 0 } context?.addArc(center: CGPoint.init(x: rect.size.width - radius - 4, y: rect.size.height/2), radius: radius, startAngle: -CGFloat(Double.pi), endAngle: angle, clockwise: true) context?.addLine(to: CGPoint(x: amount, y: rect.size.height/2)) context?.fillPath() } // Progress is in the left arc else if (amount < radius + 4 && amount > 0) { context?.move(to: CGPoint(x: 4, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 4, y: 4), tangent2End: CGPoint.init(x: radius + 4, y: 4), radius: radius) context?.addLine(to: CGPoint(x: radius + 4, y: rect.size.height/2)) context?.move(to: CGPoint(x: 4, y: rect.size.height/2)) context?.addArc(tangent1End: CGPoint.init(x: 4, y: rect.size.height - 4), tangent2End: CGPoint.init(x: radius + 4, y: rect.size.height - 4), radius: radius) context?.addLine(to: CGPoint(x: radius + 4, y: rect.size.height/2)) context?.fillPath() } } } class OverlayRoundProgressView: UIView { fileprivate var progressProperty:CGFloat! /// Progress (0.0 to 1.0) var progress:CGFloat { set { if newValue != progressProperty { self.progressProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsDisplay() }) } } get { return self.progressProperty } } /// Display mode - false = round or true = annular. Defaults to round (显示模式,false 圆形,true 为环形) var annular = false fileprivate var progressTintColorProperty:UIColor = UIColor.init(white: 1.0, alpha: 1.0) /// Indicator progress color. /// Defaults to white [UIColor whiteColor]. var progressTintColor:UIColor { set { if newValue != progressTintColorProperty && !progressTintColorProperty.isEqual(newValue) { self.progressTintColorProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsDisplay() }) } } get { return self.progressTintColorProperty } } fileprivate var backgroundTintColorProperty:UIColor = UIColor.init(white: 1.0, alpha: 1.0) /// Indicator background (non-progress) color. /// Defaults to translucent white (alpha 0.1). var backgroundTintColor:UIColor { set { if newValue != backgroundTintColorProperty && !backgroundTintColorProperty.isEqual(newValue) { self.backgroundTintColorProperty = newValue DispatchQueue.main.async(execute: { () -> Void in self.setNeedsDisplay() }) } } get { return self.backgroundTintColorProperty } } // MARK: - Lifecycle convenience init () { self.init(frame: CGRect(x: 0.0, y: 0.0, width: 37.0, height: 37.0)) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear self.isOpaque = false self.progress = 0.0 self.progressTintColor = UIColor.init(white: 1.0, alpha: 1.0) self.backgroundTintColor = UIColor.init(white: 1.0, alpha: 1.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout override var intrinsicContentSize : CGSize { return CGSize(width: 37.0, height: 37.0) } // MARK: - Drawing override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() if self.annular { // Draw background let lineWidth:CGFloat = 2.0 let processBackgroundPath = UIBezierPath.init() processBackgroundPath.lineWidth = lineWidth processBackgroundPath.lineCapStyle = .butt let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) let radius = (self.bounds.size.width - lineWidth)/2 let startAngle:CGFloat = -CGFloat(Double.pi/2) //90 degrees var endAngle:CGFloat = (2 * CGFloat(Double.pi)) + startAngle processBackgroundPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) self.backgroundTintColor.set() processBackgroundPath.stroke() // Draw progress let processPath = UIBezierPath.init() processPath.lineCapStyle = .square processPath.lineWidth = lineWidth endAngle = self.progress * 2 * CGFloat(Double.pi) + startAngle processPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) self.progressTintColor.set() processPath.stroke() } else { // Draw background let lineWidth:CGFloat = 2.0 let allRect = self.bounds let circleRect = allRect.insetBy(dx: lineWidth/2.0, dy: lineWidth/2.0) let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) self.progressTintColor.setStroke() self.backgroundTintColor.setFill() context?.setLineWidth(lineWidth) context?.strokeEllipse(in: circleRect) let startAngle = -CGFloat(Double.pi) / 2.0 let processPath = UIBezierPath() processPath.lineCapStyle = .butt processPath.lineWidth = lineWidth * 2.0 let radius = self.bounds.width/2.0 - processPath.lineWidth / 2.0 let endAngle = self.progress * 2.0 * CGFloat(Double.pi) + startAngle processPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) context?.setBlendMode(.copy) self.progressTintColor.set() processPath.stroke() } } }
1b1f89c1436c5a6ef5616038124cc3c0
39.413009
270
0.622569
false
false
false
false
dcunited001/SwiftState
refs/heads/swift/2.0
SwiftStateTests/HierarchicalStateMachineTests.swift
mit
3
// // HierarchicalStateMachineTests.swift // SwiftState // // Created by Yasuhiro Inami on 2014/10/13. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import SwiftState import XCTest class HierarchicalStateMachineTests: _TestCase { var mainMachine: HSM? var sub1Machine: HSM? var sub2Machine: HSM? // // set up hierarchical state machines as following: // // - mainMachine // - sub1Machine // - State1 (substate) // - State2 (substate) // - sub2Machine // - State1 (substate) // - State2 (substate) // - MainState0 (state) // override func setUp() { super.setUp() let sub1Machine = HSM(name: "Sub1", state: "State1") let sub2Machine = HSM(name: "Sub2", state: "State1") // [sub1] add 1-1 => 1-2 sub1Machine.addRoute("State1" => "State2") // [sub2] add 2-1 => 2-2 sub2Machine.addRoute("State1" => "State2") // create mainMachine with configuring submachines // NOTE: accessing submachine's state will be of form: "\(submachine.name).\(substate)" let mainMachine = HSM(name: "Main", submachines:[sub1Machine, sub2Machine], state: "Sub1.State1") // [main] add '1-2 => 2-1' & '2-2 => 0' & '0 => 1-1' (switching submachine) // NOTE: MainState0 does not belong to any submachine's state mainMachine.addRoute("Sub1.State2" => "Sub2.State1") mainMachine.addRoute("Sub2.State2" => "MainState0") mainMachine.addRoute("MainState0" => "Sub1.State1") // add logging handlers sub1Machine.addHandler(nil => nil) { print("[Sub1] \($0.transition)") } sub1Machine.addErrorHandler { print("[ERROR][Sub1] \($0.transition)") } sub2Machine.addHandler(nil => nil) { print("[Sub2] \($0.transition)") } sub2Machine.addErrorHandler { print("[ERROR][Sub2] \($0.transition)") } mainMachine.addHandler(nil => nil) { print("[Main] \($0.transition)") } mainMachine.addErrorHandler { print("[ERROR][Main] \($0.transition)") } self.mainMachine = mainMachine self.sub1Machine = sub1Machine self.sub2Machine = sub2Machine } func testHasRoute_submachine_internal() { let mainMachine = self.mainMachine! // NOTE: mainMachine can check submachine's internal routes // sub1 internal routes XCTAssertFalse(mainMachine.hasRoute("Sub1.State1" => "Sub1.State1")) XCTAssertTrue(mainMachine.hasRoute("Sub1.State1" => "Sub1.State2")) // 1-1 => 1-2 XCTAssertFalse(mainMachine.hasRoute("Sub1.State2" => "Sub1.State1")) XCTAssertFalse(mainMachine.hasRoute("Sub1.State2" => "Sub1.State2")) // sub2 internal routes XCTAssertFalse(mainMachine.hasRoute("Sub2.State1" => "Sub2.State1")) XCTAssertTrue(mainMachine.hasRoute("Sub2.State1" => "Sub2.State2")) // 2-1 => 2-2 XCTAssertFalse(mainMachine.hasRoute("Sub2.State2" => "Sub2.State1")) XCTAssertFalse(mainMachine.hasRoute("Sub2.State2" => "Sub2.State2")) } func testHasRoute_submachine_switching() { let mainMachine = self.mainMachine! // NOTE: mainMachine can check switchable submachines // (external routes between submachines = Sub1, Sub2, or nil) XCTAssertFalse(mainMachine.hasRoute("Sub1.State1" => "Sub2.State1")) XCTAssertFalse(mainMachine.hasRoute("Sub1.State1" => "Sub2.State2")) XCTAssertFalse(mainMachine.hasRoute("Sub1.State1" => "MainState0")) XCTAssertTrue(mainMachine.hasRoute("Sub1.State2" => "Sub2.State1")) // 1-2 => 2-1 XCTAssertFalse(mainMachine.hasRoute("Sub1.State2" => "Sub2.State2")) XCTAssertFalse(mainMachine.hasRoute("Sub1.State2" => "MainState0")) XCTAssertFalse(mainMachine.hasRoute("Sub2.State1" => "Sub1.State1")) XCTAssertFalse(mainMachine.hasRoute("Sub2.State1" => "Sub1.State2")) XCTAssertFalse(mainMachine.hasRoute("Sub2.State1" => "MainState0")) XCTAssertFalse(mainMachine.hasRoute("Sub2.State2" => "Sub1.State1")) XCTAssertFalse(mainMachine.hasRoute("Sub2.State2" => "Sub1.State2")) XCTAssertTrue(mainMachine.hasRoute("Sub2.State2" => "MainState0")) // 2-2 => 0 XCTAssertTrue(mainMachine.hasRoute("MainState0" => "Sub1.State1")) // 0 => 1-1 XCTAssertFalse(mainMachine.hasRoute("MainState0" => "Sub1.State2")) XCTAssertFalse(mainMachine.hasRoute("MainState0" => "Sub2.State1")) XCTAssertFalse(mainMachine.hasRoute("MainState0" => "Sub2.State2")) } func testTryState() { let mainMachine = self.mainMachine! let sub1Machine = self.sub1Machine! XCTAssertEqual(mainMachine.state, "Sub1.State1") // 1-1 => 1-2 (sub1 internal transition) mainMachine <- "Sub1.State2" XCTAssertEqual(mainMachine.state, "Sub1.State2") // dummy mainMachine <- "DUMMY" XCTAssertEqual(mainMachine.state, "Sub1.State2", "mainMachine.state should not be updated because there is no 1-2 => DUMMY route.") // 1-2 => 2-1 (sub1 => sub2 external transition) mainMachine <- "Sub2.State1" XCTAssertEqual(mainMachine.state, "Sub2.State1") // dummy mainMachine <- "MainState0" XCTAssertEqual(mainMachine.state, "Sub2.State1", "mainMachine.state should not be updated because there is no 2-1 => 0 route.") // 2-1 => 2-2 (sub1 internal transition) mainMachine <- "Sub2.State2" XCTAssertEqual(mainMachine.state, "Sub2.State2") // 2-2 => 0 (sub2 => main external transition) mainMachine <- "MainState0" XCTAssertEqual(mainMachine.state, "MainState0") // 0 => 1-1 (fail) mainMachine <- "Sub1.State1" XCTAssertEqual(mainMachine.state, "MainState0", "mainMachine.state should not be updated because current sub1Machine.state is State2, not State1.") XCTAssertEqual(sub1Machine.state, "State2") // let's add resetting route for sub1Machine & reset to Sub1.State1 sub1Machine.addRoute(nil => "State1") sub1Machine <- "State1" XCTAssertEqual(mainMachine.state, "MainState0") XCTAssertEqual(sub1Machine.state, "State1") // 0 => 1-1 (retry, succeed) mainMachine <- "Sub1.State1" XCTAssertEqual(mainMachine.state, "Sub1.State1") XCTAssertEqual(sub1Machine.state, "State1") } func testAddHandler() { let mainMachine = self.mainMachine! var didPass = false // NOTE: this handler is added to mainMachine and doesn't make submachines dirty mainMachine.addHandler("Sub1.State1" => "Sub1.State2") { context in print("[Main] 1-1 => 1-2 (specific)") didPass = true } XCTAssertEqual(mainMachine.state, "Sub1.State1") XCTAssertFalse(didPass) mainMachine <- "Sub1.State2" XCTAssertEqual(mainMachine.state, "Sub1.State2") XCTAssertTrue(didPass) } }
e5de2b931c518a2a557b55b9bcadc473
39.759777
155
0.611431
false
false
false
false
jianwoo/Cartography
refs/heads/master
CartographyTests/PointTests.swift
mit
1
// // PointTests.swift // Cartography // // Created by Robert Böhnke on 18/06/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // import Cartography import XCTest class PointTests: XCTestCase { var superview: View! var view: View! override func setUp() { superview = View(frame: CGRectMake(0, 0, 400, 400)) view = View(frame: CGRectZero) superview.addSubview(view) layout(view) { view in view.width == 200 view.height == 200 } } func testPoint() { layout(view) { view in view.center == view.superview!.center; return } XCTAssertEqual(view.frame, CGRectMake(100, 100, 200, 200), "should layout stuff") } }
8c18e1881f88ed10313f66a8db44fba7
20.542857
89
0.590186
false
true
false
false
bradleypj823/ParseAndCoreImage
refs/heads/master
ParseCoreImage/Filters.swift
mit
1
// // Filters.swift // ParseCoreImage // // Created by Bradley Johnson on 3/4/15. // Copyright (c) 2015 BPJ. All rights reserved. // import Foundation class Filters { class func sepia(originalImage : UIImage, context : CIContext) -> UIImage { let startImage = CIImage(image: originalImage) let filter = CIFilter(name: "CISepiaTone") filter.setDefaults() filter.setValue(startImage, forKey: kCIInputImageKey) let result = filter.valueForKey(kCIOutputImageKey) as! CIImage let extent = result.extent() let imageRef = context.createCGImage(result, fromRect: extent) return UIImage(CGImage: imageRef)! } class func blur(originalImage : UIImage, context : CIContext) -> UIImage { let startImage = CIImage(image: originalImage) let filter = CIFilter(name: "CIGaussianBlur") filter.setDefaults() filter.setValue(startImage, forKey: kCIInputImageKey) filter.setValue(5.0, forKey: kCIInputRadiusKey) let result = filter.valueForKey(kCIOutputImageKey) as! CIImage let extent = result.extent() let imageRef = context.createCGImage(result, fromRect: extent) return UIImage(CGImage: imageRef)! } class func noir(originalImage: UIImage, context : CIContext) -> UIImage { let startImage = CIImage(image: originalImage) let filter = CIFilter(name: "CIPhotoEffectNoir") filter.setDefaults() filter.setValue(startImage, forKey: kCIInputImageKey) let result = filter.valueForKey(kCIOutputImageKey) as! CIImage let extent = result.extent() let imageRef = context.createCGImage(result, fromRect: extent) return UIImage(CGImage: imageRef)! } class func chrome(originalImage: UIImage, context : CIContext) -> UIImage { let startImage = CIImage(image: originalImage) let filter = CIFilter(name: "CIPhotoEffectChrome") filter.setDefaults() filter.setValue(startImage, forKey: kCIInputImageKey) let result = filter.valueForKey(kCIOutputImageKey) as! CIImage let extent = result.extent() let imageRef = context.createCGImage(result, fromRect: extent) return UIImage(CGImage: imageRef)! } class func instant(originalImage: UIImage, context : CIContext) -> UIImage { let startImage = CIImage(image: originalImage) let filter = CIFilter(name: "CIPhotoEffectInstant") filter.setDefaults() filter.setValue(startImage, forKey: kCIInputImageKey) let result = filter.valueForKey(kCIOutputImageKey) as! CIImage let extent = result.extent() let imageRef = context.createCGImage(result, fromRect: extent) return UIImage(CGImage: imageRef)! } }
f91c4431a951f1a7fbccebb9bb4e559b
36.855072
78
0.72501
false
false
false
false
ericwastaken/Xcode_Playgrounds
refs/heads/master
Playgrounds/Delegate Example.playground/Contents.swift
unlicense
1
//: Playground - noun: a place where people can play import Foundation // Define our first delegate (CarPainter) protocol CarPainterDelegate { func myCarWasPainted(color:String) } // Define our Car protocol protocol Car { var color: String {get} var brand: String {get} var model: String {get set} } // Create a Car Maintenance class class CarMaintenance { var carDelegate: CarPainterDelegate? func paintCar(color:String) { carDelegate?.myCarWasPainted(color: color) } } // Create a specific Car's class that implements our protocols class MazdaRX7: Car, CarPainterDelegate, CustomStringConvertible { internal var brand: String = "Mazda" internal var color: String = "White" internal var model: String = "RX7" var description: String { return "\(brand) \(model) \(color)" } func myCarWasPainted(color: String) { self.color = color } } // Setup our classes and tie them together via the protocol/delegate let myCarShop = CarMaintenance() let myCar = MazdaRX7() myCarShop.carDelegate = myCar // Show the initial car color = White myCar.color // Now, have the Shop associated with this car paint it Red myCarShop.paintCar(color: "Red") // Show that the car object now shows color = Red myCar.color
d2dfb4d0f6959a4a35ee4479e7f6693b
24.038462
68
0.698157
false
false
false
false
baottran/nSURE
refs/heads/master
nSURE/RepairReviewAssessmentViewController.swift
mit
1
// // RepairReviewAssessmentViewController.swift // nSURE // // Created by Bao Tran on 8/25/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit import MBProgressHUD class RepairReviewAssessmentViewController: UIViewController { var repairObj: PFObject! @IBOutlet weak var frontCenterButton: UIButton! @IBOutlet weak var backCenterButton: UIButton! @IBOutlet weak var frontLeftButton: UIButton! @IBOutlet weak var frontPassengerLeftButton: UIButton! @IBOutlet weak var middlePassengerLeftButton: UIButton! @IBOutlet weak var backPassengerLeftButton: UIButton! @IBOutlet weak var backLeftButton: UIButton! @IBOutlet weak var frontRightButton: UIButton! @IBOutlet weak var frontPassengerRightButton: UIButton! @IBOutlet weak var middlePassengerRightButton: UIButton! @IBOutlet weak var backPassengerRightButton: UIButton! @IBOutlet weak var backRightButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // print(repairObj) // // frontCenterButton.setTitle("TEST", forState: .Normal) // print(repairObj["backCenterDamage"]) // // if let backCenterObj = self.repairObj["backCenterDamage"] as? PFObject { // print("yes") // } // Do any additional setup after loading the view. // // if let frontCenterObj = self.repairObj["frontCenterDamage"] as? PFObject { // self.getImage(frontCenterObj, damagedSectionButton: self.frontCenterButton) // } let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.labelText = "Loading Assessment Data" dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), { if let frontCenterObj = self.repairObj["frontCenterDamage"] as? PFObject { self.getImage(frontCenterObj, damagedSectionButton: self.frontCenterButton) } if let backCenterObj = self.repairObj["backCenterDamage"] as? PFObject { self.getImage(backCenterObj, damagedSectionButton: self.backCenterButton) } if let frontLeftObj = self.repairObj["frontLeftDamage"] as? PFObject { self.getImage(frontLeftObj, damagedSectionButton: self.frontLeftButton) } if let frontPassengerLeftObj = self.repairObj["frontPassengerLeftDamage"] as? PFObject { self.getImage(frontPassengerLeftObj, damagedSectionButton: self.frontPassengerLeftButton) } if let middlePassengerLeftObj = self.repairObj["middlePassengerLeftDamage"] as? PFObject { self.getImage(middlePassengerLeftObj, damagedSectionButton: self.middlePassengerLeftButton) } if let backPassengerLeftObj = self.repairObj["backPassengerLeftDamage"] as? PFObject { self.getImage(backPassengerLeftObj, damagedSectionButton: self.backPassengerLeftButton) } if let backLeftObj = self.repairObj["backLeftDamage"] as? PFObject { self.getImage(backLeftObj, damagedSectionButton: self.backLeftButton) } if let frontRightObj = self.repairObj["frontRightDamage"] as? PFObject { self.getImage(frontRightObj, damagedSectionButton: self.frontRightButton) } if let frontPassengerRightObj = self.repairObj["frontPassengerRightDamage"] as? PFObject { self.getImage(frontPassengerRightObj, damagedSectionButton: self.frontPassengerRightButton) } if let middlePassengerRightObj = self.repairObj["middlePassengerRightDamage"] as? PFObject { self.getImage(middlePassengerRightObj, damagedSectionButton: self.middlePassengerRightButton) } if let backPassengerRightObj = self.repairObj["backPassengerRightDamage"] as? PFObject { self.getImage(backPassengerRightObj, damagedSectionButton: self.backPassengerRightButton) } if let backRightObj = self.repairObj["backRightDamage"] as? PFObject { self.getImage(backRightObj, damagedSectionButton: self.backRightButton) } dispatch_async(dispatch_get_main_queue(), { MBProgressHUD.hideAllHUDsForView(self.view, animated: true) }) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getImage(damagedSectionObj: PFObject, damagedSectionButton: UIButton){ let query = PFQuery(className: "DamagedSection") let result = query.getObjectWithId(damagedSectionObj.objectId!) if let damageObj = result { if let damagePhotos = damageObj["images"] as? [PFFile]{ let coverPhoto = damagePhotos.first! coverPhoto.getDataInBackgroundWithBlock{ (imageData: NSData?, error: NSError?) -> Void in if let imageData = imageData { let image = UIImage(data: imageData) damagedSectionButton.setBackgroundImage(image, forState: .Normal) } } } } //set button text color damagedSectionButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState()) damagedSectionButton.setTitleShadowColor(UIColor.blackColor(), forState: UIControlState()) } @IBAction func viewFrontCenterLog(){ self.performSegueWithIdentifier("Review Damage", sender: "frontCenterDamage") } @IBAction func viewFrontLeftLog(){ self.performSegueWithIdentifier("Review Damage", sender: "frontLeftDamage") } @IBAction func viewFrontRightLog(){ self.performSegueWithIdentifier("Review Damage", sender: "frontRightDamage") } @IBAction func viewFrontPassengerRight(){ self.performSegueWithIdentifier("Review Damage", sender: "frontPassengerRightDamage") } @IBAction func viewFrontPassengerLeft(){ self.performSegueWithIdentifier("Review Damage", sender: "frontPassengerLeftDamage") } @IBAction func viewMiddlePassengerRight(){ self.performSegueWithIdentifier("Review Damage", sender: "middlePassengerRightDamage") } @IBAction func viewMiddlePassengerLeft(){ self.performSegueWithIdentifier("Review Damage", sender: "middlePassengerLeftDamage") } @IBAction func viewBackPassengerRight(){ self.performSegueWithIdentifier("Review Damage", sender: "backPassengerRightDamage") } @IBAction func viewBackPassengerLeft(){ self.performSegueWithIdentifier("Review Damage", sender: "backPassengerLeftDamage") } @IBAction func viewBackRight(){ self.performSegueWithIdentifier("Review Damage", sender: "backRightDamage") } @IBAction func viewBackCenter(){ self.performSegueWithIdentifier("Review Damage", sender: "backCenterDamage") } @IBAction func viewBackLeft(){ self.performSegueWithIdentifier("Review Damage", sender: "backLeftDamage") } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "Review Damage" { let navController = segue.destinationViewController as! UINavigationController let logController = navController.viewControllers.first as! ESLogDamageViewController let sectionKey = sender as! String logController.carSection = repairObj[sectionKey] as! PFObject } } /* // 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. } */ }
64866592311e09217bf46c12d57f4d40
43.377049
109
0.668637
false
false
false
false
Ramotion/showroom
refs/heads/master
Showroom/ViewControllers/GlidingCollection/GlidingCollectionDemoViewController.swift
gpl-3.0
1
// // ViewController.swift // GlidingCollectionDemo // // Created by Abdurahim Jauzee on 04/03/2017. // Copyright © 2017 Ramotion Inc. All rights reserved. // import UIKit import GlidingCollection class GlidingCollectionDemoViewController: UIViewController { fileprivate var glidingView: GlidingCollection! fileprivate var collectionView: UICollectionView! fileprivate var items = ["gloves", "boots", "bindings", "hoodie"] fileprivate var images: [[UIImage?]] = [] override func viewDidLoad() { super.viewDidLoad() setup() // Setup Showroom MenuPopUpViewController.showPopup(on: self, url: Showroom.Control.glidingCollection.sharedURL) { [weak self] in self?.dismiss(animated: true, completion: nil) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) ThingersTapViewController.showPopup(on: self) } } // MARK: - Setup extension GlidingCollectionDemoViewController { func setup() { setupGlidingCollectionView() loadImages() } private func setupGlidingCollectionView() { var config = GlidingConfig.shared config.buttonsFont = UIFont.boldSystemFont(ofSize: 22) config.inactiveButtonsColor = config.activeButtonColor GlidingConfig.shared = config glidingView = GlidingCollection(frame: view.bounds) glidingView.backgroundColor = UIColor.white view = glidingView glidingView.dataSource = self let nib = UINib(nibName: "CollectionCell", bundle: nil) collectionView = glidingView.collectionView collectionView.register(nib, forCellWithReuseIdentifier: "Cell") collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = glidingView.backgroundColor } private func loadImages() { for item in items { let imageURLs = FileManager.default.fileUrls(for: "jpeg", fileName: item) var images: [UIImage?] = [] for url in imageURLs { guard let data = try? Data(contentsOf: url) else { continue } let image = UIImage(data: data) images.append(image) } self.images.append(images) } } } // MARK: - CollectionView 🎛 extension GlidingCollectionDemoViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let section = glidingView.expandedItemIndex return images[section].count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? CollectionCell else { return UICollectionViewCell() } let section = glidingView.expandedItemIndex let image = images[section][indexPath.row] cell.imageView.image = image cell.contentView.clipsToBounds = true let layer = cell.layer let config = GlidingConfig.shared layer.shadowOffset = config.cardShadowOffset layer.shadowColor = config.cardShadowColor.cgColor layer.shadowOpacity = config.cardShadowOpacity layer.shadowRadius = config.cardShadowRadius layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale return cell } // func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // let section = glidingView.expandedItemIndex // let item = indexPath.item // print("Selected item #\(item) in section #\(section)") // } } // MARK: - Gliding Collection 🎢 extension GlidingCollectionDemoViewController: GlidingCollectionDatasource { func numberOfItems(in collection: GlidingCollection) -> Int { return items.count } func glidingCollection(_ collection: GlidingCollection, itemAtIndex index: Int) -> String { return "– " + items[index] } }
f2d470b8eb2f94c8dba9af5f661595ad
30.190476
158
0.722646
false
true
false
false
HTWDD/HTWDresden-iOS
refs/heads/master
HTWDD/Components/RoomOccupancy/ViewModels/RoomOccupancyDetailViewModel.swift
gpl-2.0
1
// // RoomOccupancyDetailViewModel.swift // HTWDD // // Created by Mustafa Karademir on 25.09.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import Foundation import RxSwift import RealmSwift // MARK: - Items enum Occupancies { case header(model: OccupancyHeader) case occupancy(model: Occupancy) } // MARK: - VM class RoomOccupancyDetailViewModel { private let bag = DisposeBag() func load(id: String) -> Observable<[Occupancies]> { let realm = try! Realm() let occupancies = realm .objects(RoomRealm.self).filter(NSPredicate(format: "id = %@", id)) .first?.occupancies.sorted(byKeyPath: "day") guard let res = occupancies else { return Observable.empty() } return Observable .collection(from: res) .map { (items: Results<OccupancyRealm> ) -> [Occupancy] in items.map { (item: OccupancyRealm) -> Occupancy in let weeks = String(String(item.weeksOnly.dropFirst()).dropLast()).replacingOccurrences(of: " ", with: "").components(separatedBy: ",").compactMap({ Int($0) }) return Occupancy( id: item.id, name: item.name, type: item.type, day: item.day, beginTime: item.beginTime, endTime: item.endTime, week: item.week, professor: item.professor, weeksOnly: weeks ) } } .map { (items: [Occupancy]) -> Dictionary<Int, [Occupancy]> in return Dictionary.init(grouping: items) { (e: Occupancy) in return e.day } } .map { (hMap: Dictionary<Int, [Occupancy]>) -> [Occupancies] in var result: [Occupancies] = [] for (k, v) in hMap.sorted(by: { (lhs, rhs) in lhs.key < rhs.key }) { result.append(.header(model: OccupancyHeader(header: k, subheader: "\(v.count) \(R.string.localizable.roomOccupancyDescription())"))) v.sorted { (lhs, rhs) in lhs.beginTime < rhs.beginTime }.forEach { occupancy in result.append(.occupancy(model: occupancy)) } } return result } .catchErrorJustReturn([]) } }
4b67a317a8826b1eaf5c3090f812f2b6
35.768116
178
0.507686
false
false
false
false
Chriskuei/Bon-for-Mac
refs/heads/master
Bon/BonFormat.swift
mit
1
// // BonFormat.swift // Bon // // Created by Chris on 16/5/15. // Copyright © 2016年 Chris. All rights reserved. // import Foundation class BonFormat { class func formatTime(_ seconds: Int) -> String { let hour = String(format: "%02d", seconds / 3600) let minute = String(format: "%02d", (seconds % 3600) / 60) let second = String(format: "%02d", seconds % 3600 % 60) let usedTime = hour + ":" + minute + ":" + second return usedTime } class func formatData(_ byte: Double) -> String { if byte > 1024 * 1024 * 1024 { let gigabyte = String(format: "%.2f", byte.byteToGigabyte()) + "G" return gigabyte } if byte > 1024 * 1024 { let megabyte = String(format: "%.2f", byte.byteToMegabyte()) + "M" return megabyte } else if byte > 1024 { let kilobyte = String(format: "%.2f", byte.byteToKilobyte()) + "K" return kilobyte } else { let byte = String(format: "%.2f", byte) + "b" return byte } } class func formatOnlineInfo(_ info: [String]) -> [String] { let usernameInfo = info[4] let usedData = Double(info[0])! let usedDataInfo = BonFormat.formatData(usedData) let seconds = Int(info[1])! let usedTimeInfo = BonFormat.formatTime(seconds) let balance = Double(info[2])! let balanceInfo = String(format: "%.2f", balance) + "G" let dailyAvailableData = getDailyAvailableData(balance, usedData: usedData) let dailyAvailableDataInfo = BonFormat.formatData(dailyAvailableData) // let userInformation: [String: String] = { // var dict = Dictionary<String, String>() // for index in 0...7 { // dict[key[index]] = info[index] // } // return dict // }() var itemsInfo = [String]() itemsInfo.append(usernameInfo) itemsInfo.append(usedDataInfo) itemsInfo.append(usedTimeInfo) itemsInfo.append(balanceInfo) itemsInfo.append(dailyAvailableDataInfo) return itemsInfo } class func getRemainingDaysOfCurrentMonth() -> Double { var date = Date() let calendar = Calendar.current let components = (calendar as NSCalendar).components([.day , .month , .year], from: date) let year = components.year let month = components.month let day = components.day var dateComponents = DateComponents() dateComponents.year = year dateComponents.month = month date = calendar.date(from: dateComponents)! let range = (calendar as NSCalendar).range(of: .day, in: .month, for: date) let numDays = range.length let remainingDaysOfCurrentMonth = numDays - day! return Double(remainingDaysOfCurrentMonth) } class func getDailyAvailableData(_ balance: Double, usedData: Double) -> Double { let remainingDaysOfCurrentMonth = getRemainingDaysOfCurrentMonth() let availableData = balance.gigabyteToByte() - usedData let dailyAvailableData = availableData / remainingDaysOfCurrentMonth return dailyAvailableData > 0 ? dailyAvailableData : 0 } }
4013c65c8fccf47373d5b43ab391e0e2
31.962963
97
0.554213
false
false
false
false
mibaldi/IOS_MIMO_APP
refs/heads/master
iosAPP/BD/RecipeDataHelper.swift
apache-2.0
1
// // RecipeDataHelper.swift // iosAPP // // Created by mikel balduciel diaz on 17/2/16. // Copyright © 2016 mikel balduciel diaz. All rights reserved. // import Foundation import SQLite class RecipeDataHelper: DataHelperProtocol { static let TABLE_NAME = "Recipes" static let table = Table(TABLE_NAME) static let recipeId = Expression<Int64>("recipeId") static let recipeIdServer = Expression<Int64>("recipeIdServer") static let name = Expression<String>("name") static let portions = Expression<Int64>("portions") static let favorite = Expression<Int64>("favorite") static let author = Expression<String>("author") static let score = Expression<Int64>("score") static let photo = Expression<String>("photo") typealias T = Recipe static func createTable() throws { guard let DB = SQLiteDataStore.sharedInstance.DB else { throw DataAccessError.Datastore_Connection_Error } do { let _ = try DB.run(table.create(temporary: false, ifNotExists: true) { t in t.column(recipeId, primaryKey: true) t.column(recipeIdServer) t.column(name) t.column(portions) t.column(favorite) t.column(author) t.column(score) t.column(photo) }) }catch _ { print("error create table") } } static func insert (item: T) throws -> Int64 { guard let DB = SQLiteDataStore.sharedInstance.DB else { throw DataAccessError.Datastore_Connection_Error } let insert = table.insert(recipeIdServer <- item.recipeIdServer, name <- item.name, portions <- item.portions, favorite <- item.favorite!.rawValue, author <- item.author, score <- item.score, photo <- item.photo) do { let rowId = try DB.run(insert) guard rowId > 0 else { throw DataAccessError.Insert_Error } return rowId }catch _ { throw DataAccessError.Insert_Error } } static func delete (item: T) throws -> Void { guard let DB = SQLiteDataStore.sharedInstance.DB else { throw DataAccessError.Datastore_Connection_Error } let query = table.filter(recipeId == item.recipeId) do { let tmp = try DB.run(query.delete()) guard tmp == 1 else { throw DataAccessError.Delete_Error } } catch _ { throw DataAccessError.Delete_Error } } static func find(id: Int64) throws -> T? { guard let DB = SQLiteDataStore.sharedInstance.DB else { throw DataAccessError.Datastore_Connection_Error } let query = table.filter(recipeId == id) let items = try DB.prepare(query) for item in items { let recipe = Recipe() recipe.recipeId = item[recipeId] recipe.recipeIdServer = item[recipeIdServer] recipe.name = item[name] recipe.portions = item[portions] recipe.photo = item[photo] recipe.favorite = FavoriteTypes(rawValue: item[favorite]) recipe.author = item[author] recipe.score = item[score] return recipe } return nil } static func findIdServer(id: Int64) throws -> T? { guard let DB = SQLiteDataStore.sharedInstance.DB else { throw DataAccessError.Datastore_Connection_Error } let query = table.filter(recipeIdServer == id) let items = try DB.prepare(query) for item in items { let recipe = Recipe() recipe.recipeId = item[recipeId] recipe.recipeIdServer = item[recipeIdServer] recipe.name = item[name] recipe.portions = item[portions] recipe.photo = item[photo] recipe.favorite = FavoriteTypes(rawValue: item[favorite]) recipe.author = item[author] recipe.score = item[score] return recipe } return nil } static func findAll() throws -> [T]? { guard let DB = SQLiteDataStore.sharedInstance.DB else { throw DataAccessError.Datastore_Connection_Error } var retArray = [T]() let items = try DB.prepare(table) for item in items { let recipe = Recipe() recipe.recipeId = item[recipeId] recipe.recipeIdServer = item[recipeIdServer] recipe.name = item[name] recipe.portions = item[portions] recipe.photo = item[photo] recipe.favorite = FavoriteTypes(rawValue: item[favorite]) recipe.author = item[author] recipe.score = item[score] retArray.append(recipe) } return retArray } static func findAllFavorites() throws -> [T]? { guard let DB = SQLiteDataStore.sharedInstance.DB else { throw DataAccessError.Datastore_Connection_Error } var retArray = [T]() let query = table.filter(favorite == 1) let items = try DB.prepare(query) for item in items { let recipe = Recipe() recipe.recipeId = item[recipeId] recipe.recipeIdServer = item[recipeIdServer] recipe.name = item[name] recipe.portions = item[portions] recipe.photo = item[photo] recipe.favorite = FavoriteTypes(rawValue: item[favorite]) recipe.author = item[author] recipe.score = item[score] retArray.append(recipe) } return retArray } }
48aab5d4a751ed91a6c1615cc7d41a17
34.053571
224
0.565387
false
false
false
false
ZackKingS/Tasks
refs/heads/master
task/Classes/Me/ZBFinishedController.swift
apache-2.0
1
// // TasksViewController.swift // go // // Created by 柏超曾 on 2017/9/14. // Copyright © 2017年 柏超曾. All rights reserved. // import Foundation import UIKit import SwiftTheme import Alamofire import SVProgressHUD class ZBFinishedController: UIViewController,UITableViewDelegate,UITableViewDataSource{ var tableView : UITableView? fileprivate var array = [TopicTitle]() fileprivate var dataArray = [Tasks]() var countL :UILabel? var leftBtn :UIButton? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 设置导航栏颜色 } override func viewDidLoad() { super.viewDidLoad() setupTableVie() setRefresh() setupNavBar() tableView?.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: kNavBarHeight, right: 0); } func setRefresh() { let header = RefreshHeder(refreshingBlock: { [weak self] in //自定义的header var str = "" if ZBLOGINED_FLAG { //已经登录 str = "\(API_DONETASK_URL)?userid=\(User.GetUser().id!)" }else{ //未登录 // SVProgressHUD.showError(withStatus: "请登录") self?.showHint(hint: "请登录") return } NetworkTool.getTaskList(url: str, completionHandler: { (json) in /* id : 50 title : 仙人掌股票开户 price : 5.00 create_time : 2017-09-30 17:11:57 check_time : null */ let dataArr = json["data"]["list"].arrayValue var temparr = [Tasks]() for dict in dataArr{ print(dict) let task = Tasks.init(dictt: (dict.dictionaryValue )) temparr.append(task) } self!.tableView?.mj_header.endRefreshing() self!.dataArray = temparr self!.tableView?.reloadData() DispatchQueue.main.async { self?.countL?.text = "\(self!.dataArray.count)项" } }) }) header?.isAutomaticallyChangeAlpha = true header?.lastUpdatedTimeLabel.isHidden = true tableView?.mj_header = header tableView?.mj_header.beginRefreshing() tableView?.mj_header = header } func setupNavBar() { let barColor = UIColor.themeColor() navigationController?.navigationBar.barTintColor = barColor; navigationController?.navigationBar.isTranslucent = false; navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 18) ] //UIFont(name: "Heiti SC", size: 24.0)! navigationItem.title = "已完成的任务"; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupTableVie() { tableView = UITableView(frame: CGRect(x: 0 , y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height ), style: UITableViewStyle.plain) tableView?.dataSource = self tableView?.delegate = self tableView?.separatorStyle = .none self.view.addSubview(tableView!) view.backgroundColor = UIColor.globalBackgroundColor() // automaticallyAdjustsScrollViewInsets = true } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //每一块有多少行 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let inview = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 80)) inview.backgroundColor = UIColor.white let bordView = UIView() inview.addSubview(bordView) bordView.layer.cornerRadius = 6 bordView.layer.borderColor = UIColor.gray.cgColor bordView.layer.borderWidth = 1 bordView.layer.masksToBounds = true bordView.snp.makeConstraints { (make) in make.top.equalTo(inview).offset(10) make.left.equalTo(inview).offset(20) make.bottom.equalTo(inview).offset(-5) make.right.equalTo(inview).offset(-15) } let finiTasskL = UILabel() finiTasskL.text = "你共完成任务" finiTasskL.font = UIFont.systemFont(ofSize: 18) inview.addSubview(finiTasskL) finiTasskL.snp.makeConstraints { (make) in make.centerY.equalTo(inview.snp.centerY) make.left.equalTo(inview).offset(35) make.width.equalTo(200) make.height.equalTo(15) } let taskcountL = UILabel() countL = taskcountL taskcountL.text = "0项" taskcountL.textAlignment = .right taskcountL.font = UIFont.systemFont(ofSize: 18) inview.addSubview(taskcountL) taskcountL.snp.makeConstraints { (make) in make.centerY.equalTo(inview.snp.centerY) make.right.equalTo(inview).offset(-35) make.width.equalTo(100) make.height.equalTo(15) } return inview } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "mainCell" let cell = TasksCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: identifier) cell.type = "2" cell.viewModel = dataArray[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 160; } deinit { NotificationCenter.default.removeObserver(self) } // MARK:======== 点击cell============ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let task : Tasks = dataArray[indexPath.row] let suss = ZBTaskSuccessController() suss.price = task.price navigationController?.pushViewController(suss, animated: true) } }
8500932add75258534c8d62a4174e226
27.246032
164
0.548469
false
false
false
false
dleonard00/firebase-user-signup
refs/heads/master
Pods/Material/Sources/SearchBarView.swift
mit
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 Material 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 UIKit public class SearchBarView : StatusBarView { /// The UITextField for the searchBar. public private(set) lazy var textField: TextField = TextField() /// The UIImage for the clear icon. public var clearButton: UIButton? { get { return textField.clearButton } set(value) { textField.clearButton = value } } /// TintColor for searchBar. public override var tintColor: UIColor? { didSet { textField.tintColor = tintColor } } /// TextColor for searchBar. public var textColor: UIColor? { didSet { textField.textColor = textColor } } /// A wrapper for searchBar.placeholder. public var placeholder: String? { didSet { textField.placeholder = placeholder } } /// Placeholder textColor. public var placeholderTextColor: UIColor { get { return textField.placeholderTextColor } set(value) { textField.placeholderTextColor = value } } /// A convenience initializer. public convenience init() { self.init(frame: CGRectZero) } public override func layoutSubviews() { super.layoutSubviews() if willRenderView { contentView.grid.views?.append(textField) contentView.grid.reloadLayout() textField.font = textField.font?.fontWithSize(20) textField.reloadView() } } /// Prepares the contentView. public override func prepareContentView() { super.prepareContentView() prepareTextField() } /// Prepares the textField. private func prepareTextField() { textField.placeholder = "Search" textField.backgroundColor = MaterialColor.clear textField.clearButtonMode = .WhileEditing contentView.addSubview(textField) } }
713cc0d725015fa145a3eeaa38011e73
29.056075
86
0.748134
false
false
false
false
muukii/JAYSON
refs/heads/main
JAYSON.playground/Pages/Build.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation @testable import JAYSON var json = JSON() json["id"] = 18737649 json["active"] = true json["name"] = "muukii" json["images"] = JSON([ "large" : "http://...foo", "medium" : "http://...foo", "small" : "http://...foo", ]) let data: Data = try json.data(options: .prettyPrinted) do { let data = try json.data(options: .prettyPrinted) print(String(data: data, encoding: .utf8)!) } catch { print(error) } //: [Next](@next)
30a87871a64e7fe0ed3abe624ca052f3
17.37037
55
0.58871
false
false
false
false
matthijs2704/vapor-apns
refs/heads/master
Sources/VaporAPNS/VaporAPNS.swift
mit
1
import Dispatch import Foundation import SwiftString import JSON import CCurl import JSON import JWT import Console open class VaporAPNS { fileprivate var options: Options private var lastGeneratedToken: (date: Date, token: String)? fileprivate var curlHandle: UnsafeMutableRawPointer! public init(options: Options) throws { self.options = options if !options.disableCurlCheck { if options.forceCurlInstall { let curlupdater = CurlUpdater() curlupdater.updateCurl() } else { let curlVersionChecker = CurlVersionHelper() curlVersionChecker.checkVersion() } } self.curlHandle = curl_multi_init() curlHelperSetMultiOpt(curlHandle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX) } deinit { curl_multi_cleanup(self.curlHandle) } // MARK: CURL Config private func configureCurlHandle(for message: ApplePushMessage, to deviceToken: String, completionHandler: @escaping (Result) -> Void) -> Connection? { guard let handle = curl_easy_init() else { return nil } curlHelperSetOptBool(handle, CURLOPT_VERBOSE, options.debugLogging ? CURL_TRUE : CURL_FALSE) if self.options.usesCertificateAuthentication { curlHelperSetOptString(handle, CURLOPT_SSLCERT, options.certPath) curlHelperSetOptString(handle, CURLOPT_SSLCERTTYPE, "PEM") curlHelperSetOptString(handle, CURLOPT_SSLKEY, options.keyPath) curlHelperSetOptString(handle, CURLOPT_SSLKEYTYPE, "PEM") } curlHelperSetOptInt(handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0) let url = ("\(self.hostURL(message.sandbox))/3/device/\(deviceToken)") curlHelperSetOptString(handle, CURLOPT_URL, url) // force set port to 443 curlHelperSetOptInt(handle, CURLOPT_PORT, options.port.rawValue) // Follow location curlHelperSetOptBool(handle, CURLOPT_FOLLOWLOCATION, CURL_TRUE) // set POST request curlHelperSetOptBool(handle, CURLOPT_POST, CURL_TRUE) // Pipeline curlHelperSetOptInt(handle, CURLOPT_PIPEWAIT, 1) // setup payload // Use CURLOPT_COPYPOSTFIELDS so Swift can release str and let CURL take // care of the rest. This implies we need to set CURLOPT_POSTFIELDSIZE // first let serialized = try! message.payload.makeJSON().serialize(prettyPrint: false) let str = String(bytes: serialized) curlHelperSetOptInt(handle, CURLOPT_POSTFIELDSIZE, str.utf8.count) curlHelperSetOptString(handle, CURLOPT_COPYPOSTFIELDS, str.cString(using: .utf8)) // Tell CURL to add headers curlHelperSetOptBool(handle, CURLOPT_HEADER, CURL_TRUE) //Headers let headers = self.requestHeaders(for: message) var curlHeaders: UnsafeMutablePointer<curl_slist>? if !options.usesCertificateAuthentication { let token: String if let recentToken = lastGeneratedToken, abs(recentToken.date.timeIntervalSinceNow) < 59 * 60 { token = recentToken.token } else { let privateKey = options.privateKey!.bytes.base64Decoded let claims: [Claim] = [ IssuerClaim(string: options.teamId!), IssuedAtClaim() ] let jwt = try! JWT(additionalHeaders: [KeyID(options.keyId!)], payload: JSON(claims), signer: ES256(key: privateKey)) let tokenString = try! jwt.createToken() let publicKey = options.publicKey!.bytes.base64Decoded do { let jwt2 = try JWT(token: tokenString) do { try jwt2.verifySignature(using: ES256(key: publicKey)) } catch { // If we fail here, its an invalid signature // return Result.error(apnsId: message.messageId, deviceToken: deviceToken, error: .invalidSignature) } } catch { print ("Couldn't verify token. This is a non-fatal error, we'll try to send the notification anyway.") if options.debugLogging { print("\(error)") } } token = tokenString.replacingOccurrences(of: " ", with: "") lastGeneratedToken = (date: Date(), token: token) } curlHeaders = curl_slist_append(curlHeaders, "Authorization: bearer \(token)") } curlHeaders = curl_slist_append(curlHeaders, "User-Agent: VaporAPNS") for header in headers { curlHeaders = curl_slist_append(curlHeaders, "\(header.key): \(header.value)") } curlHeaders = curl_slist_append(curlHeaders, "Accept: application/json") curlHeaders = curl_slist_append(curlHeaders, "Content-Type: application/json"); curlHelperSetOptList(handle, CURLOPT_HTTPHEADER, curlHeaders) return Connection(handle: handle, message: message, token: deviceToken, headers: curlHeaders, completionHandler: completionHandler) } private func requestHeaders(for message: ApplePushMessage) -> [String: String] { var headers: [String : String] = [ "apns-id": message.messageId, "apns-expiration": "\(Int(message.expirationDate?.timeIntervalSince1970.rounded() ?? 0))", "apns-priority": "\(message.priority.rawValue)", "apns-topic": message.topic ?? options.topic ] if let collapseId = message.collapseIdentifier { headers["apns-collapse-id"] = collapseId } return headers } // MARK: Connections private let connectionQueue: DispatchQueue = DispatchQueue(label: "VaporAPNS.connection-managment") private class Connection: Equatable, Hashable { private(set) var data: Data = Data() let handle: UnsafeMutableRawPointer let headers: UnsafeMutablePointer<curl_slist>? let messageId: String let token: String let completionHandler: (Result) -> Void fileprivate func append(bytes: [UInt8]) { data.append(contentsOf: bytes) } init(handle: UnsafeMutableRawPointer, message: ApplePushMessage, token: String, headers: UnsafeMutablePointer<curl_slist>?, completionHandler: @escaping (Result) -> Void) { self.handle = handle self.messageId = message.messageId self.token = token self.completionHandler = completionHandler self.headers = headers } deinit { // if the connection get's dealloced we can clenaup the // curl structures as well curl_slist_free_all(headers) curl_easy_cleanup(handle) } var hashValue: Int { return messageId.hashValue } static func == (lhs: Connection, rhs: Connection) -> Bool { return lhs.messageId == rhs.messageId && lhs.token == rhs.token } } private var connections: Set<Connection> = Set() private func complete(connection: Connection) { connectionQueue.async { guard self.connections.contains(connection) else { return } self.connections.remove(connection) self.performQueue.async { curl_multi_remove_handle(self.curlHandle, connection.handle) self.handleCompleted(connection: connection) } } } private func handleCompleted(connection: Connection) { // Create string from Data let str = String.init(data: connection.data, encoding: .utf8)! // Split into two pieces by '\r\n\r\n' as the response has two newlines before the returned data. This causes us to have two pieces, the headers/crap and the server returned data let splittedString = str.components(separatedBy: "\r\n\r\n") let result: Result! // Ditch the first part and only get the useful data part let dataString: String? if splittedString.count > 1 { dataString = splittedString[1] } else { dataString = nil } if let responseData = dataString, responseData != "", let data = responseData.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data, options: []), let responseJSON = json as? [String: Any] { // Get JSON from loaded data string if let reason = responseJSON["reason"] as? String { result = Result.error(apnsId: connection.messageId, deviceToken: connection.token, error: APNSError.init(errorReason: reason)) } else { result = Result.success(apnsId: connection.messageId, deviceToken: connection.token, serviceStatus: .success) } } else { result = Result.success(apnsId: connection.messageId, deviceToken: connection.token, serviceStatus: .success) } connection.completionHandler(result) } // MARK: Running cURL Multi private let performQueue: DispatchQueue = DispatchQueue(label: "VaporAPNS.curl_multi_perform") private var runningConnectionsCount: Int32 = 0 private var repeats = 0 /// Core cURL-multi Loop is done here private func performActiveConnections() { var code: CURLMcode = CURLM_CALL_MULTI_PERFORM var numfds: Int32 = 0 code = curl_multi_perform(self.curlHandle, &self.runningConnectionsCount) if code == CURLM_OK { code = curl_multi_wait(self.curlHandle, nil, 0, 1000, &numfds); } if code != CURLM_OK { print("curl_multi_wait failed with error code \(code): \(String(cString: curl_multi_strerror(code)))") return } if numfds != 0 { self.repeats += 1 } else { self.repeats = 0 } var numMessages: Int32 = 0 var curlMessage: UnsafeMutablePointer<CURLMsg>? repeat { curlMessage = curl_multi_info_read(self.curlHandle, &numMessages) if let message = curlMessage { let handle = message.pointee.easy_handle let msg = message.pointee.msg if msg == CURLMSG_DONE { self.connectionQueue.async { guard let connection = self.connections.first(where: { $0.handle == handle }) else { self.performQueue.async { print("Warning: Removing handle not in connection list") curl_multi_remove_handle(self.curlHandle, handle) } return } self.complete(connection: connection) } } else { print("Connection failiure: \(msg) \(String(cString: curl_easy_strerror(message.pointee.data.result)))") } } } while numMessages > 0 if self.runningConnectionsCount > 0 { performQueue.async { if self.repeats > 1 { self.performQueue.asyncAfter(deadline: DispatchTime.now() + 0.1) { self.performActiveConnections() } } else { self.performActiveConnections() } } } } // MARK: API @available(*, unavailable, renamed: "send(to:completionHandler:)") open func send(_ message: ApplePushMessage, to deviceToken: String) -> Result { send(message, to: deviceToken, completionHandler: { _ in }) return Result.networkError(error: SimpleError.string(message: "API is deprecated use send(to:completionHandler:)")) } open func send(_ message: ApplePushMessage, to deviceToken: String, completionHandler: @escaping (Result) -> Void) { guard let connection = configureCurlHandle(for: message, to: deviceToken, completionHandler: completionHandler) else { completionHandler(Result.networkError(error: SimpleError.string(message: "Could not configure cURL"))) return } connectionQueue.async { self.connections.insert(connection) let ptr = Unmanaged<Connection>.passUnretained(connection).toOpaque() let _ = curlHelperSetOptWriteFunc(connection.handle, ptr) { (ptr, size, nMemb, privateData) -> Int in let realsize = size * nMemb let pointee = Unmanaged<Connection>.fromOpaque(privateData!).takeUnretainedValue() var bytes: [UInt8] = [UInt8](repeating: 0, count: realsize) memcpy(&bytes, ptr!, realsize) pointee.append(bytes: bytes) return realsize } self.performQueue.async { // curlHandle should only be touched on performQueue curl_multi_add_handle(self.curlHandle, connection.handle) self.performActiveConnections() } } } open func send(_ message: ApplePushMessage, to deviceTokens: [String], perDeviceResultHandler: @escaping ((_ result: Result) -> Void)) { for deviceToken in deviceTokens { self.send(message, to: deviceToken, completionHandler: perDeviceResultHandler) } } // MARK: Helpers private func toNullTerminatedUtf8String(_ str: [UTF8.CodeUnit]) -> Data? { return str.withUnsafeBufferPointer() { buffer -> Data? in return buffer.baseAddress != nil ? Data(bytes: buffer.baseAddress!, count: buffer.count) : nil } } } extension VaporAPNS { fileprivate func hostURL(_ development: Bool) -> String { if development { return "https://api.development.push.apple.com" // " } else { return "https://api.push.apple.com" // /3/device/" } } } struct KeyID: Header { static let name = "kid" var node: Node init(_ keyID: String) { node = Node(keyID) } }
a63a22dc1db38fe9d87691e42a42fd8b
38.037879
186
0.554952
false
false
false
false
Azoy/Sword
refs/heads/rewrite
Sources/Sword/Types/GuildChannels.swift
mit
1
// // GuildChannels.swift // Sword // // Created by Alejandro Alonso // Copyright © 2018 Alejandro Alonso. All rights reserved. // extension Guild { // Guild.Channel namespace public enum Channel {} } extension Guild.Channel { public class Category: GuildChannel, _SwordChild { public internal(set) weak var sword: Sword? public weak var guild: Guild? { guard let guildId = guildId else { return nil } return sword?.guilds[guildId] } public weak var category: Category? { guard let parentId = parentId else { return nil } return guild?.channels[parentId] as? Category } public internal(set) var guildId: Snowflake? public let id: Snowflake public let isNsfw: Bool? public let name: String public let overwrites: [Overwrite]? public let parentId: Snowflake? public let position: UInt16 public let topic: String? public let type: ChannelKind public enum CodingKeys: String, CodingKey { case guildId = "guild_id" case id case name case isNsfw = "nsfw" case overwrites = "permission_overwrites" case parentId case position case topic case type } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.sword = decoder.userInfo[Sword.decodingInfo] as? Sword self.guildId = try container.decodeIfPresent( Snowflake.self, forKey: .guildId ) self.id = try container.decode(Snowflake.self, forKey: .id) self.isNsfw = try container.decodeIfPresent(Bool.self, forKey: .isNsfw) self.name = try container.decode(String.self, forKey: .name) self.overwrites = try container.decodeIfPresent( [Overwrite].self, forKey: .overwrites ) self.parentId = try container.decodeIfPresent( Snowflake.self, forKey: .parentId ) self.position = try container.decode(UInt16.self, forKey: .position) self.topic = try container.decodeIfPresent(String.self, forKey: .topic) self.type = try container.decode(ChannelKind.self, forKey: .type) } public func encode(to encoder: Encoder) throws { } } } extension Guild.Channel { public class Text: GuildChannel, TextChannel, _SwordChild { public internal(set) weak var sword: Sword? public weak var guild: Guild? { guard let guildId = guildId else { return nil } return sword?.guilds[guildId] } public weak var category: Category? { guard let parentId = parentId else { return nil } return guild?.channels[parentId] as? Category } public internal(set) var guildId: Snowflake? public let id: Snowflake public let isNsfw: Bool? public let lastMessageId: Snowflake? public let name: String public let overwrites: [Overwrite]? public let parentId: Snowflake? public let position: UInt16 public let topic: String? public let type: ChannelKind public enum CodingKeys: String, CodingKey { case guildId = "guild_id" case id case isNsfw = "nsfw" case lastMessageId = "last_message_id" case name case overwrites = "permission_overwrites" case parentId case position case topic case type } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.sword = decoder.userInfo[Sword.decodingInfo] as? Sword self.guildId = try container.decodeIfPresent( Snowflake.self, forKey: .guildId ) self.id = try container.decode(Snowflake.self, forKey: .id) self.isNsfw = try container.decodeIfPresent(Bool.self, forKey: .isNsfw) self.lastMessageId = try container.decodeIfPresent( Snowflake.self, forKey: .lastMessageId ) self.name = try container.decode(String.self, forKey: .name) self.overwrites = try container.decodeIfPresent( [Overwrite].self, forKey: .overwrites ) self.parentId = try container.decodeIfPresent( Snowflake.self, forKey: .parentId ) self.position = try container.decode(UInt16.self, forKey: .position) self.topic = try container.decodeIfPresent(String.self, forKey: .topic) self.type = try container.decode(ChannelKind.self, forKey: .type) } public func encode(to encoder: Encoder) throws { } } } extension Guild.Channel { public class Voice: GuildChannel, _SwordChild { public internal(set) weak var sword: Sword? public weak var guild: Guild? { guard let guildId = guildId else { return nil } return sword?.guilds[guildId] } public weak var category: Category? { guard let parentId = parentId else { return nil } return guild?.channels[parentId] as? Category } public internal(set) var guildId: Snowflake? public let id: Snowflake public let isNsfw: Bool? public let name: String public let overwrites: [Overwrite]? public let parentId: Snowflake? public let position: UInt16 public let topic: String? public let type: ChannelKind public enum CodingKeys: String, CodingKey { case guildId = "guild_id" case id case isNsfw = "nsfw" case name case overwrites = "permission_overwrites" case parentId case position case topic case type } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.sword = decoder.userInfo[Sword.decodingInfo] as? Sword self.guildId = try container.decodeIfPresent( Snowflake.self, forKey: .guildId ) self.id = try container.decode(Snowflake.self, forKey: .id) self.isNsfw = try container.decodeIfPresent(Bool.self, forKey: .isNsfw) self.name = try container.decode(String.self, forKey: .name) self.overwrites = try container.decodeIfPresent( [Overwrite].self, forKey: .overwrites ) self.parentId = try container.decodeIfPresent( Snowflake.self, forKey: .parentId ) self.position = try container.decode(UInt16.self, forKey: .position) self.topic = try container.decodeIfPresent(String.self, forKey: .topic) self.type = try container.decode(ChannelKind.self, forKey: .type) } public func encode(to encoder: Encoder) throws { } } }
38ae48f6e7cc9bf449f2853f4553ecb8
28.12987
77
0.64066
false
false
false
false
nikrad/ios
refs/heads/master
FiveCalls/FiveCalls/MyImpactViewController.swift
mit
1
// // MyImpactViewController.swift // FiveCalls // // Created by Ben Scheirman on 2/6/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit import Crashlytics import Rswift class MyImpactViewController : UITableViewController { var viewModel: ImpactViewModel! var totalCalls: Int? @IBOutlet weak var streakLabel: UILabel! @IBOutlet weak var impactLabel: UILabel! @IBOutlet weak var subheadLabel: UILabel! enum Sections: Int { case stats case contacts case count var cellIdentifier: Rswift.ReuseIdentifier<UIKit.UITableViewCell>? { switch self { case .stats: return R.reuseIdentifier.statCell case .contacts: return R.reuseIdentifier.contactStatCell default: return nil } } } enum StatRow: Int { case madeContact case voicemail case unavailable case count } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() Answers.logCustomEvent(withName:"Screen: My Impact") viewModel = ImpactViewModel(logs: ContactLogs.load().all) let weeklyStreakCount = viewModel.weeklyStreakCount streakLabel.text = weeklyStreakMessage(for: weeklyStreakCount) let numberOfCalls = viewModel.numberOfCalls impactLabel.text = impactMessage(for: numberOfCalls) subheadLabel.isHidden = numberOfCalls == 0 let op = FetchStatsOperation() op.completionBlock = { self.totalCalls = op.numberOfCalls DispatchQueue.main.async { self.tableView.reloadData() } } OperationQueue.main.addOperation(op) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let headerView = tableView.tableHeaderView { let height = subheadLabel.isHidden ? impactLabel.frame.maxY : (subheadLabel.frame.maxY + 25.0) headerView.frame.size.height = height } } override func numberOfSections(in tableView: UITableView) -> Int { return Sections.count.rawValue } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Sections(rawValue: section)! { case .stats: return StatRow.count.rawValue case .contacts: return 0 default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = Sections(rawValue: indexPath.section)! let identifier = section.cellIdentifier let cell = tableView.dequeueReusableCell(withIdentifier: identifier!, for: indexPath)! switch section { case .stats: configureStatRow(cell: cell, stat: StatRow(rawValue: indexPath.row)!) default: break } return cell } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { guard let total = totalCalls, section == Sections.stats.rawValue else { return nil } let statsVm = StatsViewModel(numberOfCalls: total) return R.string.localizable.communityCalls(statsVm.formattedNumberOfCalls) } private func weeklyStreakMessage(for weeklyStreakCount: Int) -> String { switch weeklyStreakCount { case 0: return R.string.localizable.yourWeeklyStreakZero(weeklyStreakCount) case 1: return R.string.localizable.yourWeeklyStreakSingle() default: return R.string.localizable.yourWeeklyStreakMultiple(weeklyStreakCount) } } private func impactMessage(for numberOfCalls: Int) -> String { switch numberOfCalls { case 0: return R.string.localizable.yourImpactZero(numberOfCalls) case 1: return R.string.localizable.yourImpactSingle(numberOfCalls) default: return R.string.localizable.yourImpactMultiple(numberOfCalls) } } private func configureStatRow(cell: UITableViewCell, stat: StatRow) { switch stat { case .madeContact: cell.textLabel?.text = R.string.localizable.madeContact() cell.detailTextLabel?.text = timesString(count: viewModel.madeContactCount) case .unavailable: cell.textLabel?.text = R.string.localizable.unavailable() cell.detailTextLabel?.text = timesString(count: viewModel.unavailableCount) case .voicemail: cell.textLabel?.text = R.string.localizable.leftVoicemail() cell.detailTextLabel?.text = timesString(count: viewModel.voicemailCount) default: break } } @IBAction func done(_ sender: Any) { dismiss(animated: true, completion: nil) } private func timesString(count: Int) -> String { guard count != 1 else { return R.string.localizable.calledSingle(count) } return R.string.localizable.calledMultiple(count) } }
cc2afc3ccc6c9116310e2c2dd265e34a
32.556962
109
0.635986
false
false
false
false
jfosterdavis/Charles
refs/heads/develop
Charles/DepartingItemsViewController.swift
apache-2.0
1
// // DepartingItemsViewController.swift // Charles // // Created by Jacob Foster Davis on 6/4/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit import CoreData class DepartingItemsViewController: StoreCollectionViewController { @IBOutlet weak var explainationLabel: UILabel! var departingCharacters = [Character]() var departingPerks = [Perk]() override func viewDidLoad() { super.viewDidLoad() self.collectionView = storeCollectionView self.collectionView.dataSource = self self.collectionView.delegate = self perkCollectionViewData = departingPerks collectionViewData = departingCharacters } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.playerScoreLabel.text = String(describing: score.formattedWithSeparator) } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case "UICollectionElementKindSectionHeader": let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "departingSectionHeader", for: indexPath) as! SectionHeaderCollectionReusableView let section = indexPath.section switch section { case charactersSection: headerView.headerTitleLabel.text = "Departing Companions" case toolsSection: headerView.headerTitleLabel.text = "Expiring Tools" case iapsSection: headerView.headerTitleLabel.text = "Availablė In-App Purchasės" default: headerView.headerTitleLabel.text = "Unknown Section" } return headerView default: assert(false, "Unexpected element kind") return UICollectionReusableView() } } //sections override func numberOfSections(in collectionView: UICollectionView) -> Int { //if there are inapp purchases to be displayed, return 2 let iapCount = self.appStoreProducts.count let toolsCount = perkCollectionViewData.count let characterCount = collectionViewData.count var sectionCount = 0 //start with 0 if characterCount > 0 { charactersSection = sectionCount sectionCount += 1 } else { charactersSection = -1 } if toolsCount > 0 { toolsSection = sectionCount sectionCount += 1 } else { toolsSection = -1 } if iapCount > 0 { iapsSection = sectionCount sectionCount += 1 } else { iapsSection = -1 } return sectionCount } @IBAction override func dismissButtonPressed(_ sender: Any) { //close the store so the view will refresh with characters just bought let pVC = self.parentVC pVC?.storeClosed() self.dismiss(animated: true, completion: nil) } }
cf394fe8dd28982df2ad8805b417167a
29.536364
193
0.604049
false
false
false
false
festrs/DotaComp
refs/heads/master
DotaComp/MainViewController.swift
mit
1
// // ViewController.swift // DotaComp // // Created by Felipe Dias Pereira on 2016-10-20. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import UIKit import Alamofire import ObjectMapper import Chameleon extension UIView { func addBlurEffect() { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation self.addSubview(blurEffectView) } } class MainViewController: UIViewController { @IBOutlet weak var gamesSementedControl: UISegmentedControl! @IBOutlet weak var tableView: UITableView! var refreshControl: UIRefreshControl! var refreshImageView: UIImageView! var dataDownloader = DataDownloader() var activityIndicatorView: UIActivityIndicatorView! struct Alerts { static let DismissAlert = "Dismiss" static let DataDownloaderError = "Error while data downloading." static let DefaultTitle = "Ops" static let DefaultMessage = "There was a problem, please try again." } struct Keys { static let MainCellHeight = 76 static let MainCellIdentifier = "MainCell" static let LiveGamesCellIdentifier = "LiveGamesCell" static let EventSoonGamesCellIdentifier = "EventSoonGamesCell" static let DoneGamesCellIdentifier = "DoneGamesCell" static let segueIdentifier = "toGame" } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension title = "Games" configRefreshControl() reloadData() activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) tableView.backgroundView = activityIndicatorView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if dataDownloader.liveGames.count == 0 && dataDownloader.soonGames.count == 0 && dataDownloader.doneGames.count == 0 { tableView.separatorStyle = UITableViewCellSeparatorStyle.none activityIndicatorView.startAnimating() } } func configRefreshControl() { refreshControl = UIRefreshControl() refreshControl.backgroundColor = UIColor.clear refreshControl.tintColor = UIColor.clear refreshControl.addTarget(self, action: #selector(refresh), for: UIControlEvents.valueChanged) var images:[UIImage] = [] for i in (0...15).reversed(){ images.append(UIImage(named: "\(i)")!) } refreshImageView = UIImageView(image: UIImage(named: "14")) refreshImageView.backgroundColor = UIColor.clear refreshImageView.animationImages = images refreshImageView.animationDuration = 2 refreshControl.addSubview(refreshImageView) tableView.addSubview(refreshControl) } @IBAction func refreshGames(_ sender: Any) { reloadData() } @IBAction func segmentChanged(_ sender: Any) { tableView.reloadData(); } func refresh(sender:AnyObject) { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { guard let refresher = sender as? UIRefreshControl else { return } if(refresher.isRefreshing){ self.reloadData() } }) } func reloadData() { UIApplication.shared.isNetworkActivityIndicatorVisible = true self.dataDownloader.updateData(){ error in if error != nil { self.showAlert(Alerts.DataDownloaderError, message: String(describing: error)) } self.stopRefreshing() } } func stopRefreshing() { tableView.reloadData(); refreshImageView.stopAnimating() refreshControl.endRefreshing() activityIndicatorView.stopAnimating() UIApplication.shared.isNetworkActivityIndicatorVisible = false } func showAlert(_ title: String, message: String) { let alert = UIAlertController(title: Alerts.DefaultTitle, message: Alerts.DefaultMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Alerts.DismissAlert, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Keys.segueIdentifier{ if let indexPath = sender as? IndexPath, let vc = segue.destination as? GameViewController{ vc.game = dataDownloader.liveGames[indexPath.row] } } } } extension MainViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { // Get the current size of the refresh controller var refreshBounds = self.refreshControl!.bounds; // Distance the table has been pulled >= 0 let pullDistance = max(0.0, -self.refreshControl!.frame.origin.y); // Half the width of the table let midX = self.tableView.frame.size.width / 2.0; // Calculate the pull ratio, between 0.0-1.0 //let pullRatio = min( max(pullDistance, 0.0), 100.0) / 100.0; // Calculate the width and height of our graphics let imageViewHeight = self.refreshImageView.bounds.size.height; let imageViewWidth = self.refreshImageView.bounds.size.width; // Set the Y coord of the graphics, based on pull distance let imageViewY = pullDistance - ( imageViewHeight); let imageViewX = midX - imageViewWidth / 2.0; // Set the graphic's frames var imageViewFrame = self.refreshImageView.frame; imageViewFrame.origin.x = imageViewX imageViewFrame.origin.y = imageViewY; refreshImageView.frame = imageViewFrame; // Set the encompassing view's frames refreshBounds.size.height = pullDistance; // If we're refreshing and the animation is not playing, then play the animation if (refreshControl!.isRefreshing && !refreshImageView.isAnimating) { refreshImageView.startAnimating() } //print("pullDistance \(pullDistance), pullRatio: \(pullRatio), midX: \(midX), refreshing: \(self.refreshControl!.isRefreshing)") } } extension MainViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if gamesSementedControl.selectedSegmentIndex == 0 { self.performSegue(withIdentifier: Keys.segueIdentifier, sender: indexPath) } else if gamesSementedControl.selectedSegmentIndex == 1 { let upComingGame = dataDownloader.soonGames[indexPath.row] if let url = URL(string: upComingGame.linkID!) { UIApplication.shared.open(url, options: [:]) { boolean in } } } else { let doneGame = dataDownloader.doneGames[indexPath.row] if let url = URL(string: doneGame.linkID!) { UIApplication.shared.open(url, options: [:]) { boolean in } } } } } extension MainViewController: UITableViewDataSource { @objc(tableView:heightForRowAtIndexPath:) func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(Keys.MainCellHeight) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch gamesSementedControl.selectedSegmentIndex { case 0: return dataDownloader.liveGames.count case 1: return dataDownloader.soonGames.count case 2: return dataDownloader.doneGames.count default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch gamesSementedControl.selectedSegmentIndex { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: Keys.LiveGamesCellIdentifier, for: indexPath) as! LiveGamesTableViewCell let game = dataDownloader.liveGames[indexPath.row] cell.setUpCell(liveGame: game) return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: Keys.EventSoonGamesCellIdentifier, for: indexPath) as! EventSoonGamesTableViewCell let eventSoon = dataDownloader.soonGames[indexPath.row] cell.setUpCellForUpComingGame(upComingGame: eventSoon) return cell case 2: let cell = tableView.dequeueReusableCell(withIdentifier: Keys.DoneGamesCellIdentifier, for: indexPath) as! DoneGamesTableViewCell let eventDone = dataDownloader.doneGames[indexPath.row] cell.setUpCellForEndedGame(doneGame: eventDone) return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: Keys.LiveGamesCellIdentifier, for: indexPath) return cell } } }
85f918c95264d959eed03be45c0acaa2
35.570342
151
0.640466
false
false
false
false
saurabytes/JSQCoreDataKit
refs/heads/develop
Source/CoreDataModel.swift
mit
1
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://www.jessesquires.com/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import CoreData import Foundation /** Describes a Core Data model file exention type based on the [Model File Format and Versions](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmModelFormat.html) documentation. */ public enum ModelFileExtension: String { /// The extension for a model bundle, or a `.xcdatamodeld` file package. case bundle = "momd" /// The extension for a versioned model file, or a `.xcdatamodel` file. case versionedFile = "mom" /// The extension for a mapping model file, or a `.xcmappingmodel` file. case mapping = "cdm" /// The extension for a sqlite store. case sqlite = "sqlite" } /** An instance of `CoreDataModel` represents a Core Data model — a `.xcdatamodeld` file package. It provides the model and store URLs as well as methods for interacting with the store. */ public struct CoreDataModel: CustomStringConvertible, Equatable { // MARK: Properties /// The name of the Core Data model resource. public let name: String /// The bundle in which the model is located. public let bundle: NSBundle /// The type of the Core Data persistent store for the model. public let storeType: StoreType /** The file URL specifying the full path to the store. - note: If the store is in-memory, then this value will be `nil`. */ public var storeURL: NSURL? { get { return storeType.storeDirectory()?.URLByAppendingPathComponent(databaseFileName) } } /// The file URL specifying the model file in the bundle specified by `bundle`. public var modelURL: NSURL { get { guard let url = bundle.URLForResource(name, withExtension: ModelFileExtension.bundle.rawValue) else { fatalError("*** Error loading model URL for model named \(name) in bundle: \(bundle)") } return url } } /// The database file name for the store. public var databaseFileName: String { get { switch storeType { case .sqlite: return name + "." + ModelFileExtension.sqlite.rawValue default: return name } } } /// The managed object model for the model specified by `name`. public var managedObjectModel: NSManagedObjectModel { get { guard let model = NSManagedObjectModel(contentsOfURL: modelURL) else { fatalError("*** Error loading managed object model at url: \(modelURL)") } return model } } /** Queries the meta data for the persistent store specified by the receiver and returns whether or not a migration is needed. - returns: `true` if the store requires a migration, `false` otherwise. */ public var needsMigration: Bool { get { guard let storeURL = storeURL else { return false } do { let metadata = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType(storeType.type, URL: storeURL, options: nil) return !managedObjectModel.isConfiguration(nil, compatibleWithStoreMetadata: metadata) } catch { debugPrint("*** Error checking persistent store coordinator meta data: \(error)") return false } } } // MARK: Initialization /** Constructs a new `CoreDataModel` instance with the specified name and bundle. - parameter name: The name of the Core Data model. - parameter bundle: The bundle in which the model is located. The default is the main bundle. - parameter storeType: The store type for the Core Data model. The default is `.sqlite`, with the user's documents directory. - returns: A new `CoreDataModel` instance. */ public init(name: String, bundle: NSBundle = .mainBundle(), storeType: StoreType = .sqlite(defaultDirectoryURL())) { self.name = name self.bundle = bundle self.storeType = storeType } // MARK: Methods /** Removes the existing model store specfied by the receiver. - throws: If removing the store fails or errors, then this function throws an `NSError`. */ public func removeExistingStore() throws { let fileManager = NSFileManager.defaultManager() if let storePath = storeURL?.path where fileManager.fileExistsAtPath(storePath) { try fileManager.removeItemAtPath(storePath) } } // MARK: CustomStringConvertible /// :nodoc: public var description: String { get { return "<\(CoreDataModel.self): name=\(name); storeType=\(storeType); needsMigration=\(needsMigration); " + "modelURL=\(modelURL); storeURL=\(storeURL)>" } } }
3ed45cc496ca47ba4612d8b0d9b83a96
31.083333
152
0.619666
false
false
false
false
derpue/pecunia-client
refs/heads/master
Source/WordMapping.swift
gpl-2.0
1
/** * Copyright (c) 2014, 2015, Pecunia Project. All rights reserved. * * 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; version 2 of the * License. * * 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ import Foundation import CoreData // Number of entries in one batch of a dispatch_apply invocation. let wordsLoadStride : Int = 50000; @objc public class WordMapping: NSManagedObject { @NSManaged var wordKey: String @NSManaged var translated: String static private var mappingsAvailable : Bool?; public class func pecuniaWordsLoadedNotification() -> String { return "PecuniaWordsLoadedNotification"; } public class var wordMappingsAvailable : Bool { if mappingsAvailable == nil { let request = NSFetchRequest(); request.entity = NSEntityDescription.entityForName("WordMapping", inManagedObjectContext: MOAssistant.sharedAssistant().context); request.includesSubentities = false; let count = MOAssistant.sharedAssistant().context.countForFetchRequest(request, error: nil); mappingsAvailable = count > 0; } return mappingsAvailable!; } /** * Called when a new (or first-time) word list was downloaded and updates the shared data store. */ public class func updateWordMappings() { logEnter(); // First check if there's a word.zip file before removing the existing values. let fm = NSFileManager.defaultManager(); let zipPath = MOAssistant.sharedAssistant().resourcesDir + "/words.zip"; if !fm.fileExistsAtPath(zipPath) { logLeave(); return; } // Now we are safe to remove old mappings. removeWordMappings(); logDebug("Loading new word list"); let startTime = Mathematics.beginTimeMeasure(); let file : ZipFile = ZipFile(fileName: zipPath, mode: ZipFileModeUnzip); let info : FileInZipInfo = file.getCurrentFileInZipInfo(); if info.length < 100000000 { // Sanity check. Not more than 100MB. var buffer = NSMutableData(length: Int(info.length)); let stream = file.readCurrentFileInZip(); let length = stream.readDataWithBuffer(buffer); if (length == info.length) { var text = NSString(data: buffer!, encoding: NSUTF8StringEncoding); buffer = nil; // Free buffer to lower mem consuption. let lines = text!.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()); text = nil; // Convert to lower case and decompose diacritics (e.g. umlauts). // Split work into blocks of wordsLoadStride size and iterate in parallel over them. let lineCount = lines.count; var blockCount = lineCount / wordsLoadStride; if lineCount % wordsLoadStride != 0 { ++blockCount; // One more (incomplete) block for the remainder. } // Create an own managed context for each block, so we don't get into concurrency issues. dispatch_apply(blockCount, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { index in // Create a local managed context for this thread. let coordinator = MOAssistant.sharedAssistant().context.persistentStoreCoordinator; let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType); context.persistentStoreCoordinator = coordinator; let start = index * wordsLoadStride; var end = start + wordsLoadStride; if (end > lineCount) { end = lineCount; } for (var i = start; i < end; ++i) { let key = lines[Int(i)].stringWithNormalizedGermanChars().lowercaseString; let mapping = NSEntityDescription.insertNewObjectForEntityForName("WordMapping", inManagedObjectContext: context) as! WordMapping; mapping.wordKey = key; mapping.translated = lines[Int(i)] as String; } do { try context.save(); } catch let error as NSError { let alert = NSAlert(error: error); alert.runModal(); } } ); } mappingsAvailable = true; let notification = NSNotification(name: pecuniaWordsLoadedNotification(), object: nil); NSNotificationCenter.defaultCenter().postNotification(notification); } logDebug("Word list loading done in: %.2fs", arguments: Mathematics.timeDifferenceSince(startTime) / 1000000000); logLeave(); } /** * Removes all shared word list data (e.g. for updates or if the user decided not to want * the overhead anymore. */ public class func removeWordMappings() { logDebug("Clearing word list"); mappingsAvailable = false; let startTime = Mathematics.beginTimeMeasure(); let coordinator = MOAssistant.sharedAssistant().context.persistentStoreCoordinator; let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType); context.persistentStoreCoordinator = coordinator; let allMappings = NSFetchRequest(); allMappings.entity = NSEntityDescription.entityForName("WordMapping", inManagedObjectContext: context); allMappings.includesPropertyValues = false; // Fetch only IDs. do { let mappings = try context.executeFetchRequest(allMappings); for mapping in mappings { context.deleteObject(mapping as! WordMapping); } try context.save(); } catch let error as NSError { let alert = NSAlert(error: error); alert.runModal(); } logDebug("Word list truncation done in: %.2fs", arguments: Mathematics.timeDifferenceSince(startTime) / 1000000000); } }
f98e30447b19a2ea4938ee37c25595c9
41.290123
124
0.617136
false
false
false
false
everald/JetPack
refs/heads/master
Sources/Extensions/Foundation/NSDecimalNumber.swift
mit
1
import Foundation public extension NSDecimalNumber { @nonobjc internal func modulo(_ divisor: NSDecimalNumber) -> NSDecimalNumber { let roundingMode: NSDecimalNumber.RoundingMode = (isNegative != divisor.isNegative) ? .up : .down let roundingHandler = NSDecimalNumberHandler(roundingMode: roundingMode, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) let quotient = dividing(by: divisor, withBehavior: roundingHandler) let subtract = quotient.multiplying(by: divisor) let remainder = subtracting(subtract) return divisor.isNegative ? remainder.negate() : remainder } @nonobjc public static let minusOne = NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true) @nonobjc internal func negate() -> NSDecimalNumber { return multiplying(by: .minusOne) } }
4e60052b719b824711a7d4d00bf23603
31.692308
186
0.770588
false
false
false
false
mitchtreece/Spider
refs/heads/master
Spider/Classes/Core/Spider.swift
mit
1
// // Spider.swift // Spider-Web // // Created by Mitch Treece on 8/22/18. // import Foundation /// `Spider` provides a simple & declarative way to execute web requests. public class Spider { /// The shared base URL prepended to all request paths. /// /// If no base URL is provided, request paths are expected to be fully-qualified URLs. public var baseUrl: URLRepresentable? /// The shared authorization applied to all requests. public var authorization: RequestAuth? /// The shared headers applied to all requests. public var headers: Headers? /// The shared timeout applied to all requests. public var timeout: TimeInterval? /// The shared middlewares applied to all responses. public var middlewares: [Middleware]? /// Flag indicating if debug logging is enabled. public var isDebugEnabled: Bool = false { didSet { self.reachability?.isDebugEnabled = isDebugEnabled } } // The `Spider` instance's reachability monitor. public private(set) var reachability: ReachabilityMonitor? private var builder: RequestBuilder! private var session = URLSession.shared /// The shared `Spider` instance. public static let web = Spider() public init() { self.builder = RequestBuilder(spider: self) self.reachability = ReachabilityMonitor(host: nil) } /// Initializes a `Spider` instance. /// - Parameter baseUrl: An optional shared base URL. /// - Parameter authorization: An optional shared authorization type. /// - Parameter reachabilityHostUrl: An optional host URL to use for reachability monitoring. /// - Returns: A configured `Spider` instance. public convenience init(baseUrl: URLRepresentable?, authorization: RequestAuth?, reachabilityHostUrl: URLRepresentable?) { self.init() self.baseUrl = baseUrl self.authorization = authorization self.reachability = ReachabilityMonitor(host: reachabilityHostUrl) } // MARK: Perform /// Creates a request worker using a request. /// - Parameter request: The request. /// - Returns: A request worker. public func perform(_ request: Request) -> RequestWorker { return RequestWorker( request: request, builder: self.builder, middlewares: self.middlewares ?? [], session: self.session, isDebugEnabled: self.isDebugEnabled ) } /// Creates a GET request worker. /// - Parameter path: The resource path to append to the shared base URL _or_ /// a fully qualified URL (if no shared base URL is specified). /// ``` /// "/users/12345" /// "http://base.url/v1/users/12345" /// ``` /// - Parameter parameters: An optional parameter object to be query-encoded into the request path. /// - Parameter authorization: Optional authorization to use for this request. /// - Returns: A request worker. public func get(_ path: String, parameters: JSON? = nil, authorization: RequestAuth? = nil) -> RequestWorker { return perform(Request( method: .get, path: path, parameters: parameters, authorization: authorization )) } /// Creates a POST request worker. /// - Parameter path: The resource path to append to the shared base URL _or_ /// a fully qualified URL (if no shared base URL is specified). /// ``` /// "/users/12345" /// "http://base.url/v1/users/12345" /// ``` /// - Parameter parameters: An optional parameter object to sent in the request body. /// - Parameter authorization: Optional authorization to use for this request. /// - Returns: A request worker. public func post(_ path: String, parameters: JSON? = nil, authorization: RequestAuth? = nil) -> RequestWorker { return perform(Request( method: .post, path: path, parameters: parameters, authorization: authorization )) } /// Creates a PUT request worker. /// - Parameter path: The resource path to append to the shared base URL _or_ /// a fully qualified URL (if no shared base URL is specified). /// ``` /// "/users/12345" /// "http://base.url/v1/users/12345" /// ``` /// - Parameter parameters: An optional parameter object to sent in the request body. /// - Parameter authorization: Optional authorization to use for this request. /// - Returns: A request worker. public func put(_ path: String, parameters: JSON? = nil, authorization: RequestAuth? = nil) -> RequestWorker { return perform(Request( method: .put, path: path, parameters: parameters, authorization: authorization )) } /// Creates a PATCH request worker. /// - Parameter path: The resource path to append to the shared base URL _or_ /// a fully qualified URL (if no shared base URL is specified). /// ``` /// "/users/12345" /// "http://base.url/v1/users/12345" /// ``` /// - Parameter parameters: An optional parameter object to sent in the request body. /// - Parameter authorization: Optional authorization to use for this request. /// - Returns: A request worker. public func patch(_ path: String, parameters: JSON? = nil, authorization: RequestAuth? = nil) -> RequestWorker { return perform(Request( method: .patch, path: path, parameters: parameters, authorization: authorization )) } /// Creates a DELETE request worker. /// - Parameter path: The resource path to append to the shared base URL _or_ /// a fully qualified URL (if no shared base URL is specified). /// ``` /// "/users/12345" /// "http://base.url/v1/users/12345" /// ``` /// - Parameter parameters: An optional parameter object to sent in the request body. /// - Parameter authorization: Optional authorization to use for this request. /// - Returns: A request worker. public func delete(_ path: String, parameters: JSON? = nil, authorization: RequestAuth? = nil) -> RequestWorker { return perform(Request( method: .delete, path: path, parameters: parameters, authorization: authorization )) } /// Creates a multipart request worker. /// - Parameter method: The request's multipart HTTP method; _defaults to POST_. /// - Parameter path: The resource path to append to the shared base URL _or_ /// a fully qualified URL (if no shared base URL is specified). /// ``` /// "/users/12345" /// "http://base.url/v1/users/12345" /// ``` /// - Parameter parameters: An optional parameter object to sent in the request body. /// - Parameter files: An array of files to be sent with the request. /// - Parameter authorization: Optional authorization to use for this request. /// - Returns: A request worker. public func multipart(method: MultipartRequest.Method = .post, path: String, parameters: JSON? = nil, files: [MultipartFile], authorization: RequestAuth? = nil) -> RequestWorker { return perform(MultipartRequest( method: method, path: path, parameters: parameters, files: files, authorization: authorization )) } }
3a748a5218f1edd437de239170020b9b
34.491304
103
0.576259
false
false
false
false
1457792186/JWSwift
refs/heads/dev
07-transforming-operators/starter/RxSwiftPlayground/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift
apache-2.0
109
// // BehaviorSubject.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents a value that changes over time. /// /// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. public final class BehaviorSubject<Element> : Observable<Element> , SubjectType , ObserverType , SynchronizedUnsubscribeType , Disposable { public typealias SubjectObserverType = BehaviorSubject<Element> typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType /// Indicates whether the subject has any observers public var hasObservers: Bool { _lock.lock() let value = _observers.count > 0 _lock.unlock() return value } let _lock = RecursiveLock() // state private var _isDisposed = false private var _element: Element private var _observers = Observers() private var _stoppedEvent: Event<Element>? #if DEBUG fileprivate let _synchronizationTracker = SynchronizationTracker() #endif /// Indicates whether the subject has been disposed. public var isDisposed: Bool { return _isDisposed } /// Initializes a new instance of the subject that caches its last value and starts with the specified value. /// /// - parameter value: Initial value sent to observers when no other value has been received by the subject yet. public init(value: Element) { _element = value #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } /// Gets the current value or throws an error. /// /// - returns: Latest value. public func value() throws -> Element { _lock.lock(); defer { _lock.unlock() } // { if _isDisposed { throw RxError.disposed(object: self) } if let error = _stoppedEvent?.error { // intentionally throw exception throw error } else { return _element } //} } /// Notifies all subscribed observers about next event. /// /// - parameter event: Event to send to the observers. public func on(_ event: Event<E>) { #if DEBUG _synchronizationTracker.register(synchronizationErrorMessage: .default) defer { _synchronizationTracker.unregister() } #endif dispatch(_synchronized_on(event), event) } func _synchronized_on(_ event: Event<E>) -> Observers { _lock.lock(); defer { _lock.unlock() } if _stoppedEvent != nil || _isDisposed { return Observers() } switch event { case .next(let element): _element = element case .error, .completed: _stoppedEvent = event } return _observers } /// Subscribes an observer to the subject. /// /// - parameter observer: Observer to subscribe to the subject. /// - returns: Disposable object that can be used to unsubscribe the observer from the subject. public override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock() let subscription = _synchronized_subscribe(observer) _lock.unlock() return subscription } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if _isDisposed { observer.on(.error(RxError.disposed(object: self))) return Disposables.create() } if let stoppedEvent = _stoppedEvent { observer.on(stoppedEvent) return Disposables.create() } let key = _observers.insert(observer.on) observer.on(.next(_element)) return SubscriptionDisposable(owner: self, key: key) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() _synchronized_unsubscribe(disposeKey) _lock.unlock() } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { if _isDisposed { return } _ = _observers.removeKey(disposeKey) } /// Returns observer interface for subject. public func asObserver() -> BehaviorSubject<Element> { return self } /// Unsubscribe all observers and release resources. public func dispose() { _lock.lock() _isDisposed = true _observers.removeAll() _stoppedEvent = nil _lock.unlock() } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif }
c07a76563b19bc3ecbb6245cbb9e26d1
28.090361
116
0.593705
false
false
false
false
panyam/SwiftIO
refs/heads/master
Sources/BufferedWriter.swift
apache-2.0
1
// // BufferedWriter.swift // SwiftIO // // Created by Sriram Panyam on 1/16/16. // Copyright © 2016 Sriram Panyam. All rights reserved. // import Foundation public class BufferedWriter : Writer { public var writer : Writer private var dataBuffer : Buffer private var bufferSize : LengthType = 0 public init (_ writer: Writer, bufferSize: LengthType) { self.writer = writer self.bufferSize = bufferSize self.dataBuffer = Buffer(bufferSize) } public convenience init (_ writer: Writer) { self.init(writer, bufferSize: DEFAULT_BUFFER_LENGTH) } public var stream : Stream { return writer.stream } public func flush() { } public func write(value : UInt8, _ callback: CompletionCallback?) { if !dataBuffer.isFull { dataBuffer.write(value) callback?(error: nil) } else { // flush it write later let oldBuffer = dataBuffer dataBuffer = Buffer(bufferSize) oldBuffer.write(writer, callback: nil) write(value, callback) } } public func write(buffer: WriteBufferType, length: LengthType, _ callback: IOCallback?) { } }
2b13c55b56cf8e83bf1a94ecb86848c0
22.62963
91
0.592941
false
false
false
false
kak-ios-codepath/everest
refs/heads/master
Everest/Everest/Controllers/TimeLine/TimeLineMapViewController.swift
apache-2.0
1
// // TimeLineMapViewController.swift // Everest // // Created by Kaushik on 10/25/17. // Copyright © 2017 Kavita Gaitonde. All rights reserved. // import UIKit import MapKit import CoreLocation class TimeLineMapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var timelineMapView: MKMapView! var moments : [Moment]? var annotations : [MomentAnnotation] = [] var navController : UINavigationController? let locationManager = UserLocationManager.sharedInstance override func viewDidLoad() { super.viewDidLoad() self.timelineMapView.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(onUserLocation), name: NSNotification.Name(rawValue: "didReceiveUserLocation"), object: nil) locationManager.requestForUserLocation() let location = CLLocation(latitude: 37.5, longitude: -122 ) let spanView = MKCoordinateSpanMake(3, 3) let region = MKCoordinateRegionMake(location.coordinate, spanView) timelineMapView.setRegion(region, animated: true) } func onUserLocation() -> Void { let locValue:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: locationManager.userLatitude!, longitude: locationManager.userLongitude!) let region = MKCoordinateRegionMakeWithDistance(locValue, 2000, 2000) self.timelineMapView.setRegion(region, animated: true) NotificationCenter.default.removeObserver(self, name:NSNotification.Name(rawValue: "didReceiveUserLocation"), object: nil) self.loadMapFor(moments: self.moments) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadMapFor(moments: [Moment]?) -> Void { self.timelineMapView.removeAnnotations(self.annotations) self.annotations = [] self.moments = moments for moment in moments! { let annotation = MomentAnnotation() if (((moment.geoLocation?["lat"]) != nil) && ((moment.geoLocation?["lon"]) != nil)) { let lat = Double((moment.geoLocation?["lat"])!) let lon = Double((moment.geoLocation?["lon"])!) let coordinate = CLLocationCoordinate2D(latitude: lat!, longitude: lon!) annotation.coordinate = coordinate annotation.title = moment.title annotation.momentId = moment.id self.annotations.append(annotation) } } self.timelineMapView.addAnnotations(self.annotations) } /* // 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. } */ func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // if !(annotation is MKPointAnnotation) { // return nil // } var view = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotationView") if view == nil { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotationView") view!.canShowCallout = true view!.rightCalloutAccessoryView = UIButton.init(type: .detailDisclosure) as UIView } return view } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let index = (self.annotations as NSArray).index(of: view.annotation ?? 0) if index >= 0 { let momentAnnnotation = view.annotation as! MomentAnnotation let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let momentsDetailVC = storyboard.instantiateViewController(withIdentifier: "MomentsViewController") as! MomentsViewController momentsDetailVC.momentId = momentAnnnotation.momentId momentsDetailVC.isUserMomentDetail = false self.navController?.pushViewController(momentsDetailVC, animated: true) } } }
21facd338d2711cdbbc9978aeafbf83a
40.158879
165
0.664623
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/API/Requests/Room/RoomMessagesRequest.swift
mit
1
// // RoomMessagesRequest.swift // Rocket.Chat // // Created by Matheus Cardoso on 9/21/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import SwiftyJSON import Foundation fileprivate extension SubscriptionType { var path: String { switch self { case .channel: return "/api/v1/channels.messages" case .group: return "/api/v1/groups.messages" case .directMessage: return "/api/v1/dm.messages" } } } final class RoomMessagesRequest: APIRequest { typealias APIResourceType = RoomMessagesResource var path: String { return type.path } var query: String? let roomId: String? let roomName: String? let type: SubscriptionType init(roomId: String, type: SubscriptionType = .channel, query: String? = nil) { self.type = type self.roomId = roomId self.roomName = nil if let query = query { self.query = "roomId=\(roomId)&query=\(query)" } else { self.query = "roomId=\(roomId)" } } init(roomName: String, type: SubscriptionType = .channel) { self.type = type self.roomName = roomName self.roomId = nil if let query = query { self.query = "roomName=\(roomName)&query=\(query)" } else { self.query = "roomName=\(roomName)" } } } final class RoomMessagesResource: APIResource { var messages: [Message?]? { return raw?["messages"].arrayValue.map { let message = Message() message.map($0, realm: nil) return message } } var count: Int? { return raw?["count"].int } var offset: Int? { return raw?["offset"].int } var total: Int? { return raw?["total"].int } }
04b4906aaf3668d3baa795727db3e2d8
21.445783
83
0.562534
false
false
false
false
linkedin/ConsistencyManager-iOS
refs/heads/master
ConsistencyManagerTests/HelperClasses/TestListener.swift
apache-2.0
2
// © 2016 LinkedIn Corp. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import Foundation import ConsistencyManager class TestListener: ConsistencyManagerListener { var model: ConsistencyManagerModel? var updateClosure: ((ConsistencyManagerModel?, ModelUpdates) -> Void)? var contextClosure: ((Any?) -> Void)? var currentModelRequested: (()->())? init(model: ConsistencyManagerModel?) { self.model = model } func currentModel() -> ConsistencyManagerModel? { assert(Thread.current.isMainThread) // Save the state here, because we may want to change the model for testing purposes in this block let model = self.model currentModelRequested?() return model } func modelUpdated(_ model: ConsistencyManagerModel?, updates: ModelUpdates, context: Any?) { assert(Thread.current.isMainThread) self.model = model if let updateClosure = updateClosure { updateClosure(model, updates) } if let contextClosure = contextClosure { contextClosure(context) } } }
efec62bf1576541a66dffbf14dfceca4
34.534884
106
0.688482
false
false
false
false
AgaKhanFoundation/WCF-iOS
refs/heads/develop
Floral/Pods/RxSwift/RxSwift/Observables/Sink.swift
apache-2.0
14
// // Sink.swift // RxSwift // // Created by Krunoslav Zaher on 2/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // class Sink<Observer: ObserverType> : Disposable { fileprivate let _observer: Observer fileprivate let _cancel: Cancelable fileprivate let _disposed = AtomicInt(0) #if DEBUG fileprivate let _synchronizationTracker = SynchronizationTracker() #endif init(observer: Observer, cancel: Cancelable) { #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif self._observer = observer self._cancel = cancel } final func forwardOn(_ event: Event<Observer.Element>) { #if DEBUG self._synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self._synchronizationTracker.unregister() } #endif if isFlagSet(self._disposed, 1) { return } self._observer.on(event) } final func forwarder() -> SinkForward<Observer> { return SinkForward(forward: self) } final var disposed: Bool { return isFlagSet(self._disposed, 1) } func dispose() { fetchOr(self._disposed, 1) self._cancel.dispose() } deinit { #if TRACE_RESOURCES _ = Resources.decrementTotal() #endif } } final class SinkForward<Observer: ObserverType>: ObserverType { typealias Element = Observer.Element private let _forward: Sink<Observer> init(forward: Sink<Observer>) { self._forward = forward } final func on(_ event: Event<Element>) { switch event { case .next: self._forward._observer.on(event) case .error, .completed: self._forward._observer.on(event) self._forward._cancel.dispose() } } }
991ba8af870f067fc77ef4a9c3444ed0
23.373333
88
0.615974
false
false
false
false
stone3311/Mazegenerator
refs/heads/master
Board.swift
gpl-3.0
1
// Board.swift // Copyright (C) 2015 Fabian Stein // 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 class Board { // Board is quadratic var boardSize: Int = 0 // The raw array private var data: [[Int]] = [] // Initialize data array init (boardsize: Int) { for _ in 0...boardsize-1 { var row: [Int] = [] for _ in 0...boardsize-1 { row.append(0) } data.append(row) } self.boardSize = boardsize } // Check if x and y are valid private func checkXY(x: Int, y: Int) -> Bool { if x <= boardSize && y <= boardSize { return true } else { return false } } // Return field at x,y func getField(x: Int, y: Int) -> Int { let row = self.data[x] return row[y] } // Set field data at x,y func setField(data: Int, x: Int, y: Int) { self.data [x] [y] = data } }
4563cbf4019d8b0f25bd6c760081f589
28.254545
72
0.587687
false
false
false
false