repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
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
Ivacker/swift
refs/heads/master
stdlib/public/core/CTypes.swift
apache-2.0
10
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // C Primitive Types //===----------------------------------------------------------------------===// /// The C 'char' type. /// /// This will be the same as either `CSignedChar` (in the common /// case) or `CUnsignedChar`, depending on the platform. public typealias CChar = Int8 /// The C 'unsigned char' type. public typealias CUnsignedChar = UInt8 /// The C 'unsigned short' type. public typealias CUnsignedShort = UInt16 /// The C 'unsigned int' type. public typealias CUnsignedInt = UInt32 /// The C 'unsigned long' type. public typealias CUnsignedLong = UInt /// The C 'unsigned long long' type. public typealias CUnsignedLongLong = UInt64 /// The C 'signed char' type. public typealias CSignedChar = Int8 /// The C 'short' type. public typealias CShort = Int16 /// The C 'int' type. public typealias CInt = Int32 /// The C 'long' type. public typealias CLong = Int /// The C 'long long' type. public typealias CLongLong = Int64 /// The C 'float' type. public typealias CFloat = Float /// The C 'double' type. public typealias CDouble = Double // FIXME: long double // FIXME: Is it actually UTF-32 on Darwin? // /// The C++ 'wchar_t' type. public typealias CWideChar = UnicodeScalar // FIXME: Swift should probably have a UTF-16 type other than UInt16. // /// The C++11 'char16_t' type, which has UTF-16 encoding. public typealias CChar16 = UInt16 /// The C++11 'char32_t' type, which has UTF-32 encoding. public typealias CChar32 = UnicodeScalar /// The C '_Bool' and C++ 'bool' type. public typealias CBool = Bool /// A wrapper around an opaque C pointer. /// /// Opaque pointers are used to represent C pointers to types that /// cannot be represented in Swift, such as incomplete struct types. public struct COpaquePointer : Equatable, Hashable, NilLiteralConvertible { var _rawValue: Builtin.RawPointer /// Construct a `nil` instance. @_transparent public init() { _rawValue = _nilRawPointer } @_transparent init(_ v: Builtin.RawPointer) { _rawValue = v } /// Construct a `COpaquePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. @_transparent public init(bitPattern: Int) { _rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Construct a `COpaquePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. @_transparent public init(bitPattern: UInt) { _rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Convert a typed `UnsafePointer` to an opaque C pointer. @_transparent public init<T>(_ source: UnsafePointer<T>) { self._rawValue = source._rawValue } /// Convert a typed `UnsafeMutablePointer` to an opaque C pointer. @_transparent public init<T>(_ source: UnsafeMutablePointer<T>) { self._rawValue = source._rawValue } /// Determine whether the given pointer is null. @_transparent var _isNull : Bool { return self == nil } /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`. /// /// - Note: The hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { return Int(Builtin.ptrtoint_Word(_rawValue)) } /// Create an instance initialized with `nil`. @_transparent public init(nilLiteral: ()) { _rawValue = _nilRawPointer } } extension COpaquePointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return _rawPointerToString(_rawValue) } } @warn_unused_result public func ==(lhs: COpaquePointer, rhs: COpaquePointer) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue)) } /// The family of C function pointer types. /// /// This type has been removed. Instead of `CFunctionType<(T) -> U>`, a native /// function type with the C convention can be used, `@convention(c) (T) -> U`. @available(*, unavailable, message="use a function type '@convention(c) (T) -> U'") public struct CFunctionPointer<T> {} /// The corresponding Swift type to `va_list` in imported C APIs. public struct CVaListPointer { var value: UnsafeMutablePointer<Void> public // @testable init(_fromUnsafeMutablePointer from: UnsafeMutablePointer<Void>) { value = from } } extension CVaListPointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return value.debugDescription } } func _memcpy( dest destination: UnsafeMutablePointer<Void>, src: UnsafeMutablePointer<Void>, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memcpy_RawPointer_RawPointer_Int64( dest, src, size, /*alignment:*/ Int32()._value, /*volatile:*/ false._value) }
36455c449caddd65c8a17eb230d204b8
27.455959
83
0.669519
false
false
false
false
KaushalElsewhere/AllHandsOn
refs/heads/master
CleanSwiftTry/CleanSwiftTry/Scenes/CreateOrder/CreateOrderViewController.swift
mit
1
// // CreateOrderViewController.swift // CleanSwiftTry // // Created by Kaushal Elsewhere on 10/05/2017. // Copyright (c) 2017 Elsewhere. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol CreateOrderViewControllerInput { func displayPrice(_ viewModel: CreateOrder_Price_ViewModel) func displaySomething(_ viewModel: CreateOrder.Something.ViewModel) } protocol CreateOrderViewControllerOutput { var shippingMethods: [String] { get } func calculatePrice(_ request: CreateOrder_Price_Request) func doSomething(_ request: CreateOrder.Something.Request) func getPaymentOptions() } class CreateOrderViewController: UITableViewController, CreateOrderViewControllerInput { var output: CreateOrderViewControllerOutput! var router: CreateOrderRouter! @IBOutlet weak var shippingTextField: UITextField! @IBOutlet var pickerView: UIPickerView! override func awakeFromNib() { CreateOrderConfigurator.sharedInstance.configure(self) } override func viewDidLoad() { super.viewDidLoad() doSomethingOnLoad() } func configurePicker() { shippingTextField.inputView = self.pickerView shippingTextField.becomeFirstResponder() } func doSomethingOnLoad() { configurePicker() setDefaultValue() // NOTE: Ask the Interactor to do some work //let request = CreateOrder.Something.Request() //output.doSomething(request) } func setDefaultValue() { pickerView.selectRow(0, inComponent: 0, animated: false) let request = CreateOrder_Price_Request(selectedIndex: 0) output.calculatePrice(request) } // MARK: - Display logic func displaySomething(_ viewModel: CreateOrder.Something.ViewModel) { // NOTE: Display the result from the Presenter // nameTextField.text = viewModel.name } func displayPrice(_ viewModel: CreateOrder_Price_ViewModel) { shippingTextField.text = viewModel.price } } extension CreateOrderViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return output.shippingMethods.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return output.shippingMethods[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let request = CreateOrder_Price_Request(selectedIndex: row) output.calculatePrice(request) } }
16cd68c12b368f03e5a535b87083b612
29.53125
111
0.696349
false
false
false
false
WickedColdfront/Slide-iOS
refs/heads/master
Pods/reddift/reddift/Model/MediaEmbed.swift
apache-2.0
1
// // MediaEmbed.swift // reddift // // Created by sonson on 2015/04/21. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Media represents the content which is embeded a link. */ public struct MediaEmbed { /// Height of content. let height: Int /// Width of content. let width: Int /// Information of content. let content: String /// Is content scrolled? let scrolling: Bool /** Update each property with JSON object. - parameter json: JSON object which is included "t2" JSON. */ public init (json: JSONDictionary) { height = json["height"] as? Int ?? 0 width = json["width"] as? Int ?? 0 let tempContent = json["content"] as? String ?? "" content = tempContent.gtm_stringByUnescapingFromHTML() scrolling = json["scrolling"] as? Bool ?? false } var string: String { get { return "{content=\(content)\nsize=\(width)x\(height)}\n" } } }
14183525d841f47bb0a16ba2e9e9bbe8
22.333333
68
0.615306
false
false
false
false
cdtschange/SwiftMKit
refs/heads/master
SwiftMKitDemo/SwiftMKitDemo/UI/Data/NetworkRequest/MKNetworkRequestTableViewCell.swift
mit
1
// // MKDataNetworkRequestTableViewCell.swift // SwiftMKitDemo // // Created by Mao on 4/18/16. // Copyright © 2016 cdts. All rights reserved. // import UIKit import Kingfisher class MKNetworkRequestTableViewCell: UITableViewCell { @IBOutlet weak var imgPic: UIImageView! @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblContent: UILabel! @IBOutlet weak var lblTime: UILabel! @IBOutlet weak var lblComments: UILabel! @IBOutlet weak var constraintImageHeight: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func prepareForReuse() { super.prepareForReuse() imgPic.image = nil } var newsModel: NewsModel? { didSet { guard let newsModel = newsModel else { return } self.lblTitle?.text = newsModel.title self.lblContent?.text = newsModel.digest + "..." if let imageUrl = newsModel.imgsrc { self.imgPic.kf.setImage(with: URL(string: imageUrl)!, placeholder: UIImage(named: "default_image")) } else { self.imgPic.image = nil self.constraintImageHeight.constant = 0 self.setNeedsLayout() } self.lblTime.text = newsModel.displayTime self.lblComments.text = "\(newsModel.displayCommentCount)跟帖" } } }
08fa75f7a9e1f1c99ae4571e3afc0a3e
29.528302
115
0.630408
false
false
false
false
rafaell-lycan/GithubPulse
refs/heads/master
widget/GithubPulse/Controllers/ContentViewController.swift
mit
2
// // ContentViewController.swift // GithubPulse // // Created by Tadeu Zagallo on 12/28/14. // Copyright (c) 2014 Tadeu Zagallo. All rights reserved. // import Cocoa import WebKit class ContentViewController: NSViewController, NSXMLParserDelegate, WebPolicyDelegate { @IBOutlet weak var webView:WebView? @IBOutlet weak var lastUpdate:NSTextField? var regex = try? NSRegularExpression(pattern: "^osx:(\\w+)\\((.*)\\)$", options: NSRegularExpressionOptions.CaseInsensitive) var calls: [String: [String] -> Void] func loadCalls() { self.calls = [:] self.calls["contributions"] = { (args) in Contributions.fetch(args[0]) { (success, commits, streak, today) in if success { if args.count < 2 || args[1] == "true" { NSNotificationCenter.defaultCenter().postNotificationName("check_icon", object: nil, userInfo: ["today": today]) } } let _ = self.webView?.stringByEvaluatingJavaScriptFromString("contributions(\"\(args[0])\", \(success), \(today),\(streak),\(commits))") } } self.calls["set"] = { (args) in let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(args[1], forKey: args[0]) userDefaults.synchronize() if args[0] == "username" { NSNotificationCenter.defaultCenter().postNotificationName("check_username", object: self, userInfo: nil) } } self.calls["get"] = { (args) in var value = NSUserDefaults.standardUserDefaults().valueForKey(args[0]) as? String if value == nil { value = "" } let key = args[0].stringByReplacingOccurrencesOfString("'", withString: "\\'", options: [], range: nil) let v = value!.stringByReplacingOccurrencesOfString("'", withString: "\\'", options: [], range: nil) self.webView?.stringByEvaluatingJavaScriptFromString("get('\(key)', '\(v)', \(args[1]))"); } self.calls["remove"] = { (args) in let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.removeObjectForKey(args[0]) userDefaults.synchronize() if args[0] == "username" { NSNotificationCenter.defaultCenter().postNotificationName("check_username", object: self, userInfo: nil) } } self.calls["check_login"] = { (args) in let active = NSBundle.mainBundle().isLoginItem() self.webView?.stringByEvaluatingJavaScriptFromString("raw('check_login', \(active))") } self.calls["toggle_login"] = { (args) in if NSBundle.mainBundle().isLoginItem() { NSBundle.mainBundle().removeFromLoginItems() } else { NSBundle.mainBundle().addToLoginItems() } } self.calls["quit"] = { (args) in NSApplication.sharedApplication().terminate(self) } self.calls["update"] = { (args) in GithubUpdate.check(true) } self.calls["open_url"] = { (args) in if let checkURL = NSURL(string: args[0]) { NSWorkspace.sharedWorkspace().openURL(checkURL) } } } required init?(coder: NSCoder) { self.calls = [:] super.init(coder: coder) self.loadCalls() } override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.calls = [:] super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.loadCalls() } override func viewDidLoad() { #if DEBUG let url = NSURL(string: "http://0.0.0.0:8080")! #else let indexPath = NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "front") let url = NSURL(fileURLWithPath: indexPath!) #endif let request = NSURLRequest(URL: url) self.webView?.policyDelegate = self self.webView?.drawsBackground = false self.webView?.wantsLayer = true self.webView?.layer?.cornerRadius = 5 self.webView?.layer?.masksToBounds = true self.webView?.mainFrame.loadRequest(request) super.viewDidLoad() } @IBAction func refresh(sender: AnyObject?) { self.webView?.reload(sender) } func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) { let url:String = request.URL!.absoluteString.stringByRemovingPercentEncoding! if url.hasPrefix("osx:") { let matches = self.regex?.matchesInString(url, options: [], range: NSMakeRange(0, url.characters.count)) if let match = matches?[0] { let fn = (url as NSString).substringWithRange(match.rangeAtIndex(1)) let args = (url as NSString).substringWithRange(match.rangeAtIndex(2)).componentsSeparatedByString("%%") #if DEBUG print(fn, args) #endif let closure = self.calls[fn] closure?(args) } } else if (url.hasPrefix("log:")) { #if DEBUG print(url) #endif } else { listener.use() } } }
30fe2d676d5adb7cccbff6d55fe064c0
31.551948
208
0.635674
false
false
false
false
doronkatz/firefox-ios
refs/heads/master
Client/Frontend/Home/HomePanelViewController.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import SnapKit import UIKit import Storage // For VisitType. private struct HomePanelViewControllerUX { // Height of the top panel switcher button toolbar. static let ButtonContainerHeight: CGFloat = 40 static let ButtonContainerBorderColor = UIColor.black.withAlphaComponent(0.1) static let BackgroundColorNormalMode = UIConstants.PanelBackgroundColor static let BackgroundColorPrivateMode = UIConstants.PrivateModeAssistantToolbarBackgroundColor static let ToolbarButtonDeselectedColorNormalMode = UIColor(white: 0.2, alpha: 0.5) static let ToolbarButtonDeselectedColorPrivateMode = UIColor(white: 0.9, alpha: 1) } protocol HomePanelViewControllerDelegate: class { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) func homePanelViewController(_ HomePanelViewController: HomePanelViewController, didSelectPanel panel: Int) func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) } protocol HomePanel: class { weak var homePanelDelegate: HomePanelDelegate? { get set } } struct HomePanelUX { static let EmptyTabContentOffset = -180 } protocol HomePanelDelegate: class { func homePanelDidRequestToSignIn(_ homePanel: HomePanel) func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) } struct HomePanelState { var isPrivate: Bool = false var selectedIndex: Int = 0 } enum HomePanelType: Int { case topSites = 0 case bookmarks = 1 case history = 2 case readingList = 3 var localhostURL: URL { return URL(string:"#panel=\(self.rawValue)", relativeTo: UIConstants.AboutHomePage as URL)! } } class HomePanelViewController: UIViewController, UITextFieldDelegate, HomePanelDelegate { var profile: Profile! var notificationToken: NSObjectProtocol! var panels: [HomePanelDescriptor]! var url: URL? weak var delegate: HomePanelViewControllerDelegate? weak var appStateDelegate: AppStateDelegate? fileprivate var buttonContainerView: UIView! fileprivate var buttonContainerBottomBorderView: UIView! fileprivate var controllerContainerView: UIView! fileprivate var buttons: [UIButton] = [] var isPrivateMode: Bool = false { didSet { if oldValue != isPrivateMode { self.buttonContainerView.backgroundColor = isPrivateMode ? HomePanelViewControllerUX.BackgroundColorPrivateMode : HomePanelViewControllerUX.BackgroundColorNormalMode self.updateButtonTints() self.updateAppState() } } } var homePanelState: HomePanelState { return HomePanelState(isPrivate: isPrivateMode, selectedIndex: selectedPanel?.rawValue ?? 0) } override func viewDidLoad() { view.backgroundColor = HomePanelViewControllerUX.BackgroundColorNormalMode let blur: UIVisualEffectView? = DeviceInfo.isBlurSupported() ? UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light)) : nil if let blur = blur { view.addSubview(blur) } buttonContainerView = UIView() buttonContainerView.backgroundColor = HomePanelViewControllerUX.BackgroundColorNormalMode buttonContainerView.clipsToBounds = true buttonContainerView.accessibilityNavigationStyle = .combined buttonContainerView.accessibilityLabel = NSLocalizedString("Panel Chooser", comment: "Accessibility label for the Home panel's top toolbar containing list of the home panels (top sites, bookmarsk, history, remote tabs, reading list).") view.addSubview(buttonContainerView) self.buttonContainerBottomBorderView = UIView() buttonContainerView.addSubview(buttonContainerBottomBorderView) buttonContainerBottomBorderView.backgroundColor = HomePanelViewControllerUX.ButtonContainerBorderColor controllerContainerView = UIView() view.addSubview(controllerContainerView) blur?.snp.makeConstraints { make in make.edges.equalTo(self.view) } buttonContainerView.snp.makeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(HomePanelViewControllerUX.ButtonContainerHeight) } buttonContainerBottomBorderView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom).offset(-1) make.left.right.bottom.equalTo(self.buttonContainerView) } controllerContainerView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } self.panels = HomePanels().enabledPanels updateButtons() // Gesture recognizer to dismiss the keyboard in the URLBarView when the buttonContainerView is tapped let dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomePanelViewController.SELhandleDismissKeyboardGestureRecognizer(_:))) dismissKeyboardGestureRecognizer.cancelsTouchesInView = false buttonContainerView.addGestureRecognizer(dismissKeyboardGestureRecognizer) // Invalidate our activity stream data sources whenever we open up the home panels self.profile.panelDataObservers.activityStream.invalidate(highlights: false) } fileprivate func updateAppState() { let state = mainStore.updateState(.homePanels(homePanelState: homePanelState)) self.appStateDelegate?.appDidUpdateState(state) } func SELhandleDismissKeyboardGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) { view.window?.rootViewController?.view.endEditing(true) } var selectedPanel: HomePanelType? = nil { didSet { if oldValue == selectedPanel { // Prevent flicker, allocations, and disk access: avoid duplicate view controllers. return } if let index = oldValue?.rawValue { if index < buttons.count { let currentButton = buttons[index] currentButton.isSelected = false currentButton.isUserInteractionEnabled = true } } hideCurrentPanel() if let index = selectedPanel?.rawValue { if index < buttons.count { let newButton = buttons[index] newButton.isSelected = true newButton.isUserInteractionEnabled = false } if index < panels.count { let panel = self.panels[index].makeViewController(profile) let accessibilityLabel = self.panels[index].accessibilityLabel if let panelController = panel as? UINavigationController, let rootPanel = panelController.viewControllers.first { setupHomePanel(rootPanel, accessibilityLabel: accessibilityLabel) self.showPanel(panelController) } else { setupHomePanel(panel, accessibilityLabel: accessibilityLabel) self.showPanel(panel) } } } self.updateButtonTints() self.updateAppState() } } func setupHomePanel(_ panel: UIViewController, accessibilityLabel: String) { (panel as? HomePanel)?.homePanelDelegate = self panel.view.accessibilityNavigationStyle = .combined panel.view.accessibilityLabel = accessibilityLabel } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } fileprivate func hideCurrentPanel() { if let panel = childViewControllers.first { panel.willMove(toParentViewController: nil) panel.beginAppearanceTransition(false, animated: false) panel.view.removeFromSuperview() panel.endAppearanceTransition() panel.removeFromParentViewController() } } fileprivate func showPanel(_ panel: UIViewController) { addChildViewController(panel) panel.beginAppearanceTransition(true, animated: false) controllerContainerView.addSubview(panel.view) panel.endAppearanceTransition() panel.view.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } panel.didMove(toParentViewController: self) } func SELtappedButton(_ sender: UIButton!) { for (index, button) in buttons.enumerated() where button == sender { selectedPanel = HomePanelType(rawValue: index) delegate?.homePanelViewController(self, didSelectPanel: index) break } } fileprivate func updateButtons() { // Remove any existing buttons if we're rebuilding the toolbar. for button in buttons { button.removeFromSuperview() } buttons.removeAll() var prev: UIView? = nil for panel in panels { let button = UIButton() buttonContainerView.addSubview(button) button.addTarget(self, action: #selector(HomePanelViewController.SELtappedButton(_:)), for: UIControlEvents.touchUpInside) if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)") { button.setImage(image, for: UIControlState.normal) } if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)Selected") { button.setImage(image, for: UIControlState.selected) } button.accessibilityLabel = panel.accessibilityLabel button.accessibilityIdentifier = panel.accessibilityIdentifier buttons.append(button) button.snp.remakeConstraints { make in let left = prev?.snp.right ?? self.view.snp.left make.left.equalTo(left) make.height.centerY.equalTo(self.buttonContainerView) make.width.equalTo(self.buttonContainerView).dividedBy(self.panels.count) } prev = button } } func updateButtonTints() { for (index, button) in self.buttons.enumerated() { if index == self.selectedPanel?.rawValue { button.tintColor = isPrivateMode ? UIConstants.PrivateModePurple : UIConstants.HighlightBlue } else { button.tintColor = isPrivateMode ? HomePanelViewControllerUX.ToolbarButtonDeselectedColorPrivateMode : HomePanelViewControllerUX.ToolbarButtonDeselectedColorNormalMode } } } func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) { // If we can't get a real URL out of what should be a URL, we let the user's // default search engine give it a shot. // Typically we'll be in this state if the user has tapped a bookmarked search template // (e.g., "http://foo.com/bar/?query=%s"), and this will get them the same behavior as if // they'd copied and pasted into the URL bar. // See BrowserViewController.urlBar:didSubmitText:. guard let url = URIFixup.getURL(url) ?? profile.searchEngines.defaultEngine.searchURLForQuery(url) else { Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.") return } return self.homePanel(homePanel, didSelectURL: url, visitType: visitType) } func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) { delegate?.homePanelViewController(self, didSelectURL: url, visitType: visitType) dismiss(animated: true, completion: nil) } func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToCreateAccount(self) } func homePanelDidRequestToSignIn(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToSignIn(self) } func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { delegate?.homePanelViewControllerDidRequestToOpenInNewTab(url, isPrivate: isPrivate) } } protocol HomePanelContextMenu { func getSiteDetails(for indexPath: IndexPath) -> Site? func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [ActionOverlayTableViewAction]? func presentContextMenu(for indexPath: IndexPath) func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> ActionOverlayTableViewController?) } extension HomePanelContextMenu { func presentContextMenu(for indexPath: IndexPath) { guard let site = getSiteDetails(for: indexPath) else { return } presentContextMenu(for: site, with: indexPath, completionHandler: { return self.contextMenu(for: site, with: indexPath) }) } func contextMenu(for site: Site, with indexPath: IndexPath) -> ActionOverlayTableViewController? { guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil } let contextMenu = ActionOverlayTableViewController(site: site, actions: actions) contextMenu.modalPresentationStyle = .overFullScreen contextMenu.modalTransitionStyle = .crossDissolve return contextMenu } func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [ActionOverlayTableViewAction]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewTabContextMenuTitle, iconString: "") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } return [openInNewTabAction, openInNewPrivateTabAction] } }
ecdd0b43ec1713ce5c50718bf1d7e8e2
42.295129
243
0.691926
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Frontend/Browser/AboutHomeHandler.swift
mpl-2.0
2
/* 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/. */ /** * Handles the page request to about/home/ so that the page loads and does not throw an error (404) on initialization */ import GCDWebServers struct AboutHomeHandler { static func register(_ webServer: WebServer) { webServer.registerHandlerForMethod("GET", module: "about", resource: "home") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in return GCDWebServerResponse(statusCode: 200) } } } struct AboutLicenseHandler { static func register(_ webServer: WebServer) { webServer.registerHandlerForMethod("GET", module: "about", resource: "license") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in let path = Bundle.main.path(forResource: "Licenses", ofType: "html") do { let html = try NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue) as String return GCDWebServerDataResponse(html: html) } catch { debugPrint("Unable to register webserver \(error)") } return GCDWebServerResponse(statusCode: 200) } } } struct AboutEulaHandler { static func register(_ webServer: WebServer) { webServer.registerHandlerForMethod("GET", module: "about", resource: "eula") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in let path = Bundle.main.path(forResource: "Eula", ofType: "html") do { let html = try NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue) as String return GCDWebServerDataResponse(html: html) } catch { debugPrint("Unable to register webserver \(error)") } return GCDWebServerResponse(statusCode: 200) } } } extension GCDWebServerDataResponse { convenience init(XHTML: String) { let data = XHTML.data(using: String.Encoding.utf8, allowLossyConversion: false) self.init(data: data, contentType: "application/xhtml+xml; charset=utf-8") } }
8665be7953a86fcd14b674c89af08673
41.509434
149
0.654683
false
false
false
false
Chuck8080/ios-swift-sugar-record
refs/heads/master
library/CoreData/Base/SugarRecordCDContext.swift
mit
1
// // SugarRecordCDContext.swift // SugarRecord // // Created by Pedro Piñera Buendía on 11/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation import CoreData public class SugarRecordCDContext: SugarRecordContext { /// NSManagedObjectContext context let contextCD: NSManagedObjectContext /** SugarRecordCDContext initializer passing the CoreData context :param: context NSManagedObjectContext linked to this SugarRecord context :returns: Initialized SugarRecordCDContext */ init (context: NSManagedObjectContext) { self.contextCD = context } /** Notifies the context that you're going to start an edition/removal/saving operation */ public func beginWriting() { // CD begin writing does nothing } /** Notifies the context that you've finished an edition/removal/saving operation */ public func endWriting() { var error: NSError? self.contextCD.save(&error) if error != nil { let exception: NSException = NSException(name: "Database operations", reason: "Couldn't perform your changes in the context", userInfo: ["error": error!]) SugarRecord.handle(exception) } } /** * Asks the context for writing cancellation */ public func cancelWriting() { self.contextCD.rollback() } /** Creates and object in the context (without saving) :param: objectClass Class of the created object :returns: The created object in the context */ public func createObject(objectClass: AnyClass) -> AnyObject? { let managedObjectClass: NSManagedObject.Type = objectClass as NSManagedObject.Type var object: AnyObject = NSEntityDescription.insertNewObjectForEntityForName(managedObjectClass.modelName(), inManagedObjectContext: self.contextCD) return object } /** Insert an object in the context :param: object NSManagedObject to be inserted in the context */ public func insertObject(object: AnyObject) { moveObject(object as NSManagedObject, inContext: self.contextCD) } /** Find NSManagedObject objects in the database using the passed finder :param: finder SugarRecordFinder usded for querying (filtering/sorting) :returns: Objects fetched */ public func find<T>(finder: SugarRecordFinder<T>) -> SugarRecordResults<T> { let fetchRequest: NSFetchRequest = SugarRecordCDContext.fetchRequest(fromFinder: finder) var error: NSError? var objects: [AnyObject]? = self.contextCD.executeFetchRequest(fetchRequest, error: &error) SugarRecordLogger.logLevelInfo.log("Found \((objects == nil) ? 0 : objects!.count) objects in database") if objects == nil { return SugarRecordResults(coredataResults: [NSManagedObject](), finder: finder) } else { return SugarRecordResults(coredataResults: objects as [NSManagedObject], finder: finder) } } /** Returns the NSFetchRequest from a given Finder :param: finder SugarRecord finder with the information about the filtering and sorting :returns: Created NSFetchRequest */ public class func fetchRequest<T>(fromFinder finder: SugarRecordFinder<T>) -> NSFetchRequest { let objectClass: NSObject.Type = finder.objectClass! let managedObjectClass: NSManagedObject.Type = objectClass as NSManagedObject.Type let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName()) fetchRequest.predicate = finder.predicate var sortDescriptors: [NSSortDescriptor] = finder.sortDescriptors switch finder.elements { case .first: fetchRequest.fetchLimit = 1 case .last: if !sortDescriptors.isEmpty{ sortDescriptors[0] = NSSortDescriptor(key: sortDescriptors.first!.key!, ascending: !(sortDescriptors.first!.ascending)) } fetchRequest.fetchLimit = 1 case .firsts(let number): fetchRequest.fetchLimit = number case .lasts(let number): if !sortDescriptors.isEmpty{ sortDescriptors[0] = NSSortDescriptor(key: sortDescriptors.first!.key!, ascending: !(sortDescriptors.first!.ascending)) } fetchRequest.fetchLimit = number case .all: break } fetchRequest.sortDescriptors = sortDescriptors return fetchRequest } /** Deletes a given object :param: object NSManagedObject to be deleted :returns: If the object has been properly deleted */ public func deleteObject<T>(object: T) -> SugarRecordContext { let managedObject: NSManagedObject? = object as? NSManagedObject let objectInContext: NSManagedObject? = moveObject(managedObject!, inContext: contextCD) if objectInContext == nil { let exception: NSException = NSException(name: "Database operations", reason: "Imposible to remove object \(object)", userInfo: nil) SugarRecord.handle(exception) } SugarRecordLogger.logLevelInfo.log("Object removed from database") self.contextCD.deleteObject(managedObject!) return self } /** Deletes NSManagedObject objecs from an array :param: objects NSManagedObject objects to be dleeted :returns: If the deletion has been successful */ public func deleteObjects<T>(objects: SugarRecordResults<T>) -> () { var objectsDeleted: Int = 0 for (var index = 0; index < Int(objects.count) ; index++) { let object: T! = objects[index] if (object != nil) { let _ = deleteObject(object) } } SugarRecordLogger.logLevelInfo.log("Deleted \(objects.count) objects") } /** * Count the number of entities of the given type */ public func count(objectClass: AnyClass, predicate: NSPredicate? = nil) -> Int { let managedObjectClass: NSManagedObject.Type = objectClass as NSManagedObject.Type let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName()) fetchRequest.predicate = predicate var error: NSError? var count = self.contextCD.countForFetchRequest(fetchRequest, error: &error) SugarRecordLogger.logLevelInfo.log("Found \(count) objects in database") return count } //MARK: - HELPER METHODS /** Moves an NSManagedObject from one context to another :param: object NSManagedObject to be moved :param: context NSManagedObjectContext where the object is going to be moved to :returns: NSManagedObject in the new context */ func moveObject(object: NSManagedObject, inContext context: NSManagedObjectContext) -> NSManagedObject? { var error: NSError? let objectInContext: NSManagedObject? = context.existingObjectWithID(object.objectID, error: &error)? if error != nil { let exception: NSException = NSException(name: "Database operations", reason: "Couldn't move the object into the new context", userInfo: nil) SugarRecord.handle(exception) return nil } else { return objectInContext } } }
4d9703c1568d256101239e689a41bde1
33.87037
166
0.655291
false
false
false
false
skedgo/tripkit-ios
refs/heads/main
Sources/TripKit/model/CoreData/StopLocation.swift
apache-2.0
1
// // StopLocation.swift // TripKit // // Created by Adrian Schoenig on 30/6/17. // Copyright © 2017 SkedGo. All rights reserved. // import Foundation import MapKit extension StopLocation { @objc public var timeZone: TimeZone? { location?.timeZone ?? region?.timeZone } @objc public var region: TKRegion? { if let code = regionName { return TKRegionManager.shared.localRegion(code: code) } else { let region = location?.regions.first regionName = region?.code return region } } @objc public var modeTitle: String { return stopModeInfo?.alt ?? "" } } // MARK: - MKAnnotation extension StopLocation: MKAnnotation { public var title: String? { return name } public var subtitle: String? { return location?.subtitle } public var coordinate: CLLocationCoordinate2D { return location?.coordinate ?? kCLLocationCoordinate2DInvalid } } // MARK: - UIActivityItemSource #if os(iOS) extension StopLocation: UIActivityItemSource { public func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { // Note: We used to return 'nil' if we don't have `lastStopVisit`, but the protocol doesn't allow that return "" } public func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? { guard let last = lastStopVisit else { return nil } var output: String = self.title ?? "" if let filter = filter, !filter.isEmpty { output.append(" (filter: \(filter)") } let predicate = departuresPredicate(from: last.departure) let visits = managedObjectContext?.fetchObjects(StopVisits.self, sortDescriptors: [NSSortDescriptor(key: "departure", ascending: true)], predicate: predicate, relationshipKeyPathsForPrefetching: nil, fetchLimit: 10) ?? [] output.append("\n") output.append(visits.localizedShareString) return output } } extension Array where Element: StopVisits { public var localizedShareString: String { var output = "" let _ = self.reduce(output) { (current, next) -> String in guard let smsString = next.smsString else { return current } output.append(smsString) output.append("\n") return output } if output.contains("*") { output.append("* real-time") } return output } } #endif
9c238d181319f1cf8abd9ddc2803767e
25.458333
227
0.659449
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Blockchain/UserPropertyRecorder/AnalyticsUserPropertyRecorder.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import DIKit import FirebaseAnalytics import PlatformKit import ToolKit /// Records user properties using external analytics client final class AnalyticsUserPropertyRecorder: UserPropertyRecording { // MARK: - Types struct UserPropertyErrorEvent: AnalyticsEvent { let name = "user_property_format_error" let params: [String: String]? } // MARK: - Properties private let logger: Logger private let validator: AnalyticsUserPropertyValidator private let analyticsRecorder: AnalyticsEventRecorderAPI // MARK: - Setup init( validator: AnalyticsUserPropertyValidator = AnalyticsUserPropertyValidator(), analyticsRecorder: AnalyticsEventRecorderAPI = resolve(), logger: Logger = .shared ) { self.validator = validator self.analyticsRecorder = analyticsRecorder self.logger = logger } // MARK: - API func record(id: String) { Analytics.setUserID(id.sha256) } /// Records a standard user property func record(_ property: StandardUserProperty) { record(property: property) } /// Records a hashed user property func record(_ property: HashedUserProperty) { record(property: property) } // MARK: - Accessors private func record(property: UserProperty) { let name = property.key.rawValue let value: String if property.truncatesValueIfNeeded { value = validator.truncated(value: property.value) } else { value = property.value } do { try validator.validate(name: name) try validator.validate(value: value) Analytics.setUserProperty(value, forName: name) } catch { // Catch the error and record it using analytics event recorder defer { logger.error("could not send user property \(name)! \(value) received error: \(String(describing: error))") } guard let error = error as? AnalyticsUserPropertyValidator.UserPropertyError else { return } let errorName = validator.truncated(name: error.rawValue) let errorValue = validator.truncated(value: name) let event = UserPropertyErrorEvent(params: [errorName: errorValue]) analyticsRecorder.record(event: event) } } }
8e59510a05d5f99199e9159f1312c236
29.9375
123
0.647273
false
false
false
false
AndreMuis/STGTISensorTag
refs/heads/master
STGTISensorTag/STGSimpleKeysService.swift
mit
1
// // STGSimpleKeysService.swift // STGTISensorTag // // Created by Andre Muis on 5/14/16. // Copyright © 2016 Andre Muis. All rights reserved. // import CoreBluetooth public class STGSimpleKeysService { weak var delegate : STGSimpleKeysServiceDelegate! let serviceUUID : CBUUID var service : CBService? let dataCharacteristicUUID : CBUUID var dataCharacteristic : CBCharacteristic? init(delegate : STGSimpleKeysServiceDelegate) { self.delegate = delegate self.serviceUUID = CBUUID(string: STGConstants.SimpleKeysService.serviceUUIDString) self.service = nil self.dataCharacteristicUUID = CBUUID(string: STGConstants.SimpleKeysService.dataCharacteristicUUIDString) self.dataCharacteristic = nil } public func enable() { self.delegate.simpleKeysServiceEnable(self) } public func disable() { self.delegate.simpleKeysServiceDisable(self) } func characteristicUpdated(characteristic : CBCharacteristic) { if let value = characteristic.value { if characteristic.UUID == self.dataCharacteristicUUID { let state : STGSimpleKeysState? = self.simpleKeysStateWithCharacteristicValue(value) self.delegate.simpleKeysService(self, didUpdateState: state) } } } func simpleKeysStateWithCharacteristicValue(characteristicValue : NSData) -> STGSimpleKeysState? { let bytes : [UInt8] = characteristicValue.unsignedIntegers let simpleKeysState = STGSimpleKeysState(rawValue: bytes[0]) return simpleKeysState } }
639367cd889c31bd1161a5a2812c378c
21.113924
113
0.65312
false
false
false
false
blitzagency/amigo-swift
refs/heads/master
Amigo/AmigoMetaData.swift
mit
1
// // AmigoMeta.swift // Amigo // // Created by Adam Venturella on 7/1/15. // Copyright © 2015 BLITZ. All rights reserved. // import Foundation import CoreData public class AmigoMetaData{ var tables = [String:MetaModel]() public init(_ managedObjectModel: NSManagedObjectModel){ self.initialize(managedObjectModel) } public func metaModelForType<T: AmigoModel>(type: T.Type) -> MetaModel{ let key = type.description() return metaModelForName(key) } public func metaModelForName(name: String) -> MetaModel{ return tables[name]! } func initialize(managedObjectModel: NSManagedObjectModel){ let lookup = managedObjectModel.entitiesByName // there may be a better way here, right now we ensure we have // all the models, then we need to go do some additional passes // to ensure the ForeignKey Relationships (ToOne) and the Many To Many // relationships (ToMany). // // the N*3 loops hurts my heart, but for now, it'a only done // on initialization. lookup.map{metaModelFromEntity($1)} zip(lookup.values, tables.values).map(initializeRelationships) // lookup.map{registerModel($1)} // zip(lookup.values, tables.values).map(initializeRelationships) // initializeRelationships($0, model: $1) // } // join.map{(x, y) -> String in // print(99) // return "" // }.count } func initializeRelationships(entity:NSEntityDescription, model: MetaModel){ var columns = [Column]() var foreignKeys = [ForeignKey]() // sqlite supports FK's with actions: // https://www.sqlite.org/foreignkeys.html#fk_actions // TODO determine if iOS 9+ sqlite supports this // adjust column creation accordingly entity.relationshipsByName .filter{ $1.toMany == false } .map{ _, relationship -> Void in let target = relationship.destinationEntity! let targetModel = metaModelForName(target.managedObjectClassName) let foreignKey = ForeignKey( label: relationship.name, type: targetModel.primaryKey.type, relatedType: targetModel.table.type, optional: relationship.optional) let column = Column( label: "\(relationship.name)_id", type: targetModel.primaryKey.type, primaryKey: false, indexed: true, optional: relationship.optional, unique: false, foreignKey: foreignKey) columns.append(column) foreignKeys.append(foreignKey) } let model = MetaModel( table: model.table, columns: model.columns + columns, primaryKey: model.primaryKey, foreignKeys: foreignKeys) tables[String(model.table.type)] = model } func registerModel(model: MetaModel){ } func metaModelFromEntity(entityDescription: NSEntityDescription){ let model: MetaModel var primaryKey: Column? let table = Table.fromEntityDescription(entityDescription) var columns = entityDescription.attributesByName.map { Column.fromAttributeDescription($1) } primaryKey = columns.filter{ $0.primaryKey }.first if primaryKey == nil{ primaryKey = Column.defaultPrimaryKey() columns = [primaryKey!] + columns } model = MetaModel(table: table, columns: columns, primaryKey: primaryKey!) tables[String(table.type)] = model } func createAll(engine: Engine){ } }
978622b43dbe4b4245cd0f451ee8bea9
29.207692
85
0.582781
false
false
false
false
grd888/ios_uicollectionview_2nd_edition_source_code
refs/heads/master
Chapter 1/Swift/Chapter 1 Project 1/Chapter 1 Project 1/AFViewController.swift
apache-2.0
1
// // AFViewController.swift // Chapter 1 Project 1 // // Created by Greg Delgado on 26/10/2017. // Copyright © 2017 Greg Delgado. All rights reserved. // import UIKit private let kCellIdentifier = "Cell Identifier" class AFViewController: UICollectionViewController { var colorArray = [UIColor]() override func viewDidLoad() { super.viewDidLoad() self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCellIdentifier) let numberOfColors = 100; var tempArray = [UIColor]() for _ in 0..<numberOfColors { let redValue = Double(arc4random() % 255) / 255.0 let blueValue = Double(arc4random() % 255) / 255.0 let greenValue = Double(arc4random() % 255) / 255.0 tempArray.append(UIColor.init(red: CGFloat(redValue), green: CGFloat(greenValue), blue: CGFloat(blueValue), alpha: 1.0)) } colorArray = tempArray } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return colorArray.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellIdentifier, for: indexPath) cell.backgroundColor = colorArray[indexPath.item] return cell } }
ce7646c8c996c8dd0460e5c5d589711d
28.75
132
0.658048
false
false
false
false
doronkatz/firefox-ios
refs/heads/master
Client/Frontend/Settings/ClearPrivateDataTableViewController.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 UIKit import Shared private let SectionToggles = 0 private let SectionButton = 1 private let NumberOfSections = 2 private let SectionHeaderFooterIdentifier = "SectionHeaderFooterIdentifier" private let TogglesPrefKey = "clearprivatedata.toggles" private let log = Logger.browserLogger private let HistoryClearableIndex = 0 class ClearPrivateDataTableViewController: UITableViewController { fileprivate var clearButton: UITableViewCell? var profile: Profile! var tabManager: TabManager! fileprivate typealias DefaultCheckedState = Bool fileprivate lazy var clearables: [(clearable: Clearable, checked: DefaultCheckedState)] = { return [ (HistoryClearable(profile: self.profile), true), (CacheClearable(tabManager: self.tabManager), true), (CookiesClearable(tabManager: self.tabManager), true), (SiteDataClearable(tabManager: self.tabManager), true), ] }() fileprivate lazy var toggles: [Bool] = { if let savedToggles = self.profile.prefs.arrayForKey(TogglesPrefKey) as? [Bool] { return savedToggles } return self.clearables.map { $0.checked } }() fileprivate var clearButtonEnabled = true { didSet { clearButton?.textLabel?.textColor = clearButtonEnabled ? UIConstants.DestructiveRed : UIColor.lightGray } } override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsClearPrivateDataTitle tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderFooterIdentifier) tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: UIConstants.TableViewHeaderFooterHeight)) footer.showBottomBorder = false tableView.tableFooterView = footer } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) if indexPath.section == SectionToggles { cell.textLabel?.text = clearables[indexPath.item].clearable.label let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: #selector(ClearPrivateDataTableViewController.switchValueChanged(_:)), for: UIControlEvents.valueChanged) control.isOn = toggles[indexPath.item] cell.accessoryView = control cell.selectionStyle = .none control.tag = indexPath.item } else { assert(indexPath.section == SectionButton) cell.textLabel?.text = Strings.SettingsClearPrivateDataClearButton cell.textLabel?.textAlignment = NSTextAlignment.center cell.textLabel?.textColor = UIConstants.DestructiveRed cell.accessibilityTraits = UIAccessibilityTraitButton cell.accessibilityIdentifier = "ClearPrivateData" clearButton = cell } return cell } override func numberOfSections(in tableView: UITableView) -> Int { return NumberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == SectionToggles { return clearables.count } assert(section == SectionButton) return 1 } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { guard indexPath.section == SectionButton else { return false } // Highlight the button only if it's enabled. return clearButtonEnabled } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == SectionButton else { return } func clearPrivateData(_ action: UIAlertAction) { let toggles = self.toggles self.clearables .enumerated() .flatMap { (i, pair) in guard toggles[i] else { return nil } log.debug("Clearing \(pair.clearable).") return pair.clearable.clear() } .allSucceed() .upon { result in assert(result.isSuccess, "Private data cleared successfully") //LeanplumIntegration.sharedInstance.track(eventName: .clearPrivateData) self.profile.prefs.setObject(self.toggles, forKey: TogglesPrefKey) DispatchQueue.main.async { // Disable the Clear Private Data button after it's clicked. self.clearButtonEnabled = false self.tableView.deselectRow(at: indexPath, animated: true) } } } // We have been asked to clear history and we have an account. // (Whether or not it's in a good state is irrelevant.) if self.toggles[HistoryClearableIndex] && profile.hasAccount() { profile.syncManager.hasSyncedHistory().uponQueue(DispatchQueue.main) { yes in // Err on the side of warning, but this shouldn't fail. let alert: UIAlertController if yes.successValue ?? true { // Our local database contains some history items that have been synced. // Warn the user before clearing. alert = UIAlertController.clearSyncedHistoryAlert(okayCallback: clearPrivateData) } else { alert = UIAlertController.clearPrivateDataAlert(okayCallback: clearPrivateData) } self.present(alert, animated: true, completion: nil) return } } else { let alert = UIAlertController.clearPrivateDataAlert(okayCallback: clearPrivateData) self.present(alert, animated: true, completion: nil) } tableView.deselectRow(at: indexPath, animated: false) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderFooterIdentifier) as! SettingsTableSectionHeaderFooterView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UIConstants.TableViewHeaderFooterHeight } @objc func switchValueChanged(_ toggle: UISwitch) { toggles[toggle.tag] = toggle.isOn // Dim the clear button if no clearables are selected. clearButtonEnabled = toggles.contains(true) } }
08521af058a5343178ef0b4c96ed2be0
40.039773
164
0.65333
false
false
false
false
JGiola/swift-package-manager
refs/heads/main
Sources/Basic/RegEx.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation /// A helpful wrapper around NSRegularExpression. /// - SeeAlso: NSRegularExpression public struct RegEx { private let regex: NSRegularExpression public typealias Options = NSRegularExpression.Options /// Creates a new Regex using `pattern`. /// /// - Parameters: /// - pattern: A valid Regular Expression pattern /// - options: NSRegularExpression.Options on how the RegEx should be processed. /// - Note: Deliminators must be double escaped. Once for Swift and once for RegEx. /// Example, to math a negative integer: `RegEx(pattern: "-\d")` -> `RegEx(pattern: "-\\d")` /// - SeeAlso: NSRegularExpression /// - Throws: An Error if `pattern` is an invalid Regular Expression. public init(pattern: String, options: Options = []) throws { self.regex = try NSRegularExpression(pattern: pattern, options: options) } /// Returns match groups for every match of the Regex. /// /// For every match in the string, it constructs the collection /// of groups matched. /// /// RegEx(pattern: "([a-z]+)([0-9]+)").matchGroups(in: "foo1 bar2 baz3") /// /// Returns `[["foo", "1"], ["bar", "2"], ["baz", "3"]]`. /// /// - Parameters: /// - in: A string to check for matches to the whole Regex. /// - Returns: A collection where each elements is the collection of matched groups. public func matchGroups(in string: String) -> [[String]] { let nsString = NSString(string: string) return regex.matches(in: string, options: [], range: NSMakeRange(0, nsString.length)).map{ match -> [String] in return (1 ..< match.numberOfRanges).map { idx -> String in let range = match.range(at: idx) return range.location == NSNotFound ? "" : nsString.substring(with: range) } } } }
19aace5692bf446eee0d4aa2ecafebe9
40.407407
119
0.635063
false
false
false
false
PerfectlySoft/Perfect-Authentication
refs/heads/master
Sources/LocalAuthentication/Routing/webroutes/WebHandlers.registerCompletion.swift
apache-2.0
1
// // WebHandlers.registerCompletion.swift // Perfect-OAuth2-Server // // Created by Jonathan Guthrie on 2017-04-26. // // import PerfectHTTP import PerfectSession import PerfectCrypto import PerfectSessionPostgreSQL extension WebHandlers { // registerCompletion static func registerCompletion(data: [String:Any]) throws -> RequestHandler { return { request, response in let t = request.session?.data["csrf"] as? String ?? "" if let i = request.session?.userid, !i.isEmpty { response.redirect(path: "/") } var context: [String : Any] = ["title": "Perfect Authentication Server"] if let v = request.param(name: "passvalidation"), !(v as String).isEmpty { let acc = Account(validation: v) if acc.id.isEmpty { context["msg_title"] = "Account Validation Error." context["msg_body"] = "" response.render(template: "views/msg", context: context) return } else { if let p1 = request.param(name: "p1"), !(p1 as String).isEmpty, let p2 = request.param(name: "p2"), !(p2 as String).isEmpty, p1 == p2 { if let digestBytes = p1.digest(.sha256), let hexBytes = digestBytes.encode(.hex), let hexBytesStr = String(validatingUTF8: hexBytes) { print(hexBytesStr) acc.password = hexBytesStr // let digestBytes2 = p1.digest(.sha256) // let hexBytes2 = digestBytes2?.encode(.hex) // let hexBytesStr2 = String(validatingUTF8: hexBytes2!) // print(hexBytesStr2) } // acc.password = BCrypt.hash(password: p1) acc.usertype = .standard do { try acc.save() request.session?.userid = acc.id context["msg_title"] = "Account Validated and Completed." context["msg_body"] = "<p><a class=\"button\" href=\"/\">Click to continue</a></p>" response.render(template: "views/msg", context: context) } catch { print(error) } } else { context["msg_body"] = "<p>Account Validation Error: The passwords must not be empty, and must match.</p>" context["passvalidation"] = v context["csrfToken"] = t response.render(template: "views/registerComplete", context: context) return } } } else { context["msg_title"] = "Account Validation Error." context["msg_body"] = "Code not found." response.render(template: "views/msg", context: context) } } } }
0f14ec974f2fffd755c516f06efcae80
29.64557
111
0.623296
false
false
false
false
CodaFi/Algebra
refs/heads/master
Algebra/Module.swift
mit
2
// // Module.swift // Algebra // // Created by Robert Widmann on 11/22/14. // Copyright (c) 2014 TypeLift. All rights reserved. // /// If R is a Ring and M is an abelian group, a Left Module defines a binary operation R *<> M -> M. public struct LeftModule<R: Semiring, A: Additive> { public let multiply: (R, A) -> A } public enum LeftModules { public static let int = LeftModule<Int, Int>(multiply: *) public static let int8 = LeftModule<Int, Int8>(multiply: { Int8($0) * $1 }) public static let int16 = LeftModule<Int, Int16>(multiply: { Int16($0) * $1 }) public static let int32 = LeftModule<Int, Int32>(multiply: { Int32($0) * $1 }) public static let int64 = LeftModule<Int, Int64>(multiply: { Int64($0) * $1 }) } /// If R is a Ring and M is an abelian group, a Right Module defines a binary operation M <>* R -> M. public struct RightModule<A: Additive, R: Semiring> { public let multiply: (A, R) -> A } public enum RightModules { public static let int = RightModule<Int, Int>(multiply: *) public static let int8 = RightModule<Int8, Int>(multiply: { $0 * Int8($1) }) public static let int16 = RightModule<Int16, Int>(multiply: { $0 * Int16($1) }) public static let int32 = RightModule<Int32, Int>(multiply: { $0 * Int32($1) }) public static let int64 = RightModule<Int64, Int>(multiply: { $0 * Int64($1) }) } /// A bimodule is a module with compatible left and right operations. public struct Bimodule<R: Semiring, A: Additive> { public let left: LeftModule<R, A> public let right: RightModule<A, R> } enum Bimodules { public static let int = Bimodule(left: LeftModules.int, right: RightModules.int) public static let int8 = Bimodule(left: LeftModules.int8, right: RightModules.int8) public static let int16 = Bimodule(left: LeftModules.int16, right: RightModules.int16) public static let int32 = Bimodule(left: LeftModules.int32, right: RightModules.int32) public static let int64 = Bimodule(left: LeftModules.int64, right: RightModules.int64) }
6da0421721fb3c3ee70c18f9025d78e0
45.204545
101
0.684211
false
false
false
false
Johennes/firefox-ios
refs/heads/master
Client/Frontend/Browser/WindowCloseHelper.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit protocol WindowCloseHelperDelegate: class { func windowCloseHelper(windowCloseHelper: WindowCloseHelper, didRequestToCloseTab tab: Tab) } class WindowCloseHelper: TabHelper { weak var delegate: WindowCloseHelperDelegate? private weak var tab: Tab? required init(tab: Tab) { self.tab = tab if let path = NSBundle.mainBundle().pathForResource("WindowCloseHelper", ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } } func scriptMessageHandlerName() -> String? { return "windowCloseHelper" } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let tab = tab { dispatch_async(dispatch_get_main_queue()) { self.delegate?.windowCloseHelper(self, didRequestToCloseTab: tab) } } } class func name() -> String { return "WindowCloseHelper" } }
76c0688e6e04b4b24106e6bb712d5aec
35.97561
141
0.687335
false
false
false
false
slavapestov/swift
refs/heads/master
stdlib/public/core/AssertCommon.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Implementation Note: this file intentionally uses very LOW-LEVEL // CONSTRUCTS, so that assert and fatal may be used liberally in // building library abstractions without fear of infinite recursion. // // FIXME: We could go farther with this simplification, e.g. avoiding // UnsafeMutablePointer @_transparent @warn_unused_result public // @testable func _isDebugAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 0 } @_transparent @warn_unused_result internal func _isReleaseAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 1 } @_transparent @warn_unused_result public // @testable func _isFastAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 2 } @_transparent @warn_unused_result public // @testable func _isStdlibInternalChecksEnabled() -> Bool { #if INTERNAL_CHECKS_ENABLED return true #else return false #endif } @_transparent @warn_unused_result internal func _fatalErrorFlags() -> UInt32 { // The current flags are: // (1 << 0): Report backtrace on fatal error #if os(iOS) || os(tvOS) || os(watchOS) return 0 #else return _isDebugAssertConfiguration() ? 1 : 0 #endif } @_silgen_name("_swift_stdlib_reportFatalErrorInFile") func _reportFatalErrorInFile( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportFatalError") func _reportFatalError( prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportUnimplementedInitializerInFile") func _reportUnimplementedInitializerInFile( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, _ column: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportUnimplementedInitializer") func _reportUnimplementedInitializer( className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, flags: UInt32) /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in message.withUTF8Buffer { (message) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line, flags: flags) Builtin.int_trap() } } } Builtin.int_trap() } /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( prefix: StaticString, _ message: String, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in let messageUTF8 = message.nulTerminatedUTF8 messageUTF8.withUnsafeBufferPointer { (messageUTF8) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), messageUTF8.baseAddress, UInt(messageUTF8.count), file.baseAddress, UInt(file.count), line, flags: flags) } } } Builtin.int_trap() } /// This function should be used only in the implementation of stdlib /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @noreturn @inline(never) @_semantics("stdlib_binary_only") @_semantics("arc.programtermination_point") func _fatalErrorMessage( prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { #if INTERNAL_CHECKS_ENABLED prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in file.withUTF8Buffer { (file) in _reportFatalErrorInFile( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), file.baseAddress, UInt(file.count), line, flags: flags) } } } #else prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in _reportFatalError( prefix.baseAddress, UInt(prefix.count), message.baseAddress, UInt(message.count), flags: flags) } } #endif Builtin.int_trap() } /// Prints a fatal error message when an unimplemented initializer gets /// called by the Objective-C runtime. @_transparent @noreturn public // COMPILER_INTRINSIC func _unimplemented_initializer(className: StaticString, initName: StaticString = #function, file: StaticString = #file, line: UInt = #line, column: UInt = #column) { // This function is marked @_transparent so that it is inlined into the caller // (the initializer stub), and, depending on the build configuration, // redundant parameter values (#file etc.) are eliminated, and don't leak // information about the user's source. if _isDebugAssertConfiguration() { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in file.withUTF8Buffer { (file) in _reportUnimplementedInitializerInFile( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count), file.baseAddress, UInt(file.count), line, column, flags: 0) } } } } else { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in _reportUnimplementedInitializer( className.baseAddress, UInt(className.count), initName.baseAddress, UInt(initName.count), flags: 0) } } } Builtin.int_trap() } @noreturn public // COMPILER_INTRINSIC func _undefined<T>( @autoclosure message: () -> String = String(), file: StaticString = #file, line: UInt = #line ) -> T { _assertionFailed("fatal error", message(), file, line, flags: 0) }
fb4ac4e555f5dce842848ce28898a74a
28.1341
80
0.657943
false
false
false
false
sssbohdan/Design-Patterns-In-Swift
refs/heads/master
Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
gpl-3.0
2
//: Behavioral | //: [Creational](Creational) | //: [Structural](Structural) /*: Behavioral ========== >In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication. > >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern) */ import Swift import Foundation /*: 🐝 Chain Of Responsibility -------------------------- The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler. ### Example: */ class MoneyPile { let value: Int var quantity: Int var nextPile: MoneyPile? init(value: Int, quantity: Int, nextPile: MoneyPile?) { self.value = value self.quantity = quantity self.nextPile = nextPile } func canWithdraw(v: Int) -> Bool { var v = v func canTakeSomeBill(want: Int) -> Bool { return (want / self.value) > 0 } var q = self.quantity while canTakeSomeBill(v) { if q == 0 { break } v -= self.value q -= 1 } if v == 0 { return true } else if let next = self.nextPile { return next.canWithdraw(v) } return false } } class ATM { private var hundred: MoneyPile private var fifty: MoneyPile private var twenty: MoneyPile private var ten: MoneyPile private var startPile: MoneyPile { return self.hundred } init(hundred: MoneyPile, fifty: MoneyPile, twenty: MoneyPile, ten: MoneyPile) { self.hundred = hundred self.fifty = fifty self.twenty = twenty self.ten = ten } func canWithdraw(value: Int) -> String { return "Can withdraw: \(self.startPile.canWithdraw(value))" } } /*: ### Usage */ // Create piles of money and link them together 10 < 20 < 50 < 100.** let ten = MoneyPile(value: 10, quantity: 6, nextPile: nil) let twenty = MoneyPile(value: 20, quantity: 2, nextPile: ten) let fifty = MoneyPile(value: 50, quantity: 2, nextPile: twenty) let hundred = MoneyPile(value: 100, quantity: 1, nextPile: fifty) // Build ATM. var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten) atm.canWithdraw(310) // Cannot because ATM has only 300 atm.canWithdraw(100) // Can withdraw - 1x100 atm.canWithdraw(165) // Cannot withdraw because ATM doesn't has bill with value of 5 atm.canWithdraw(30) // Can withdraw - 1x20, 2x10 /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility) */ /*: 👫 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() /*: 🎶 Interpreter -------------- The interpreter pattern is used to evaluate sentences in a language. ### Example */ protocol IntegerExp { func evaluate(context: IntegerContext) -> Int func replace(character: Character, integerExp: IntegerExp) -> IntegerExp func copy() -> IntegerExp } class IntegerContext { private var data: [Character:Int] = [:] func lookup(name: Character) -> Int { return self.data[name]! } func assign(integerVarExp: IntegerVarExp, value: Int) { self.data[integerVarExp.name] = value } } class IntegerVarExp: IntegerExp { let name: Character init(name: Character) { self.name = name } func evaluate(context: IntegerContext) -> Int { return context.lookup(self.name) } func replace(name: Character, integerExp: IntegerExp) -> IntegerExp { if name == self.name { return integerExp.copy() } else { return IntegerVarExp(name: self.name) } } func copy() -> IntegerExp { return IntegerVarExp(name: self.name) } } class AddExp: IntegerExp { private var operand1: IntegerExp private var operand2: IntegerExp init(op1: IntegerExp, op2: IntegerExp) { self.operand1 = op1 self.operand2 = op2 } func evaluate(context: IntegerContext) -> Int { return self.operand1.evaluate(context) + self.operand2.evaluate(context) } func replace(character: Character, integerExp: IntegerExp) -> IntegerExp { return AddExp(op1: operand1.replace(character, integerExp: integerExp), op2: operand2.replace(character, integerExp: integerExp)) } func copy() -> IntegerExp { return AddExp(op1: self.operand1, op2: self.operand2) } } /*: ### Usage */ var expression: IntegerExp? var intContext = IntegerContext() var a = IntegerVarExp(name: "A") var b = IntegerVarExp(name: "B") var c = IntegerVarExp(name: "C") expression = AddExp(op1: a, op2: AddExp(op1: b, op2: c)) // a + (b + c) intContext.assign(a, value: 2) intContext.assign(b, value: 1) intContext.assign(c, value: 3) var result = expression?.evaluate(intContext) /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Interpreter) */ /*: 🍫 Iterator ----------- The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure. ### Example: */ struct NovellasCollection<T> { let novellas: [T] } extension NovellasCollection: SequenceType { typealias Generator = AnyGenerator<T> func generate() -> AnyGenerator<T> { var i = 0 return AnyGenerator { i += 1; return i >= self.novellas.count ? nil : self.novellas[i] } } } /*: ### Usage */ let greatNovellas = NovellasCollection(novellas:["Mist"]) for novella in greatNovellas { print("I've read: \(novella)") } /*: 💐 Mediator ----------- The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object. ### Example */ class Colleague { let name: String let mediator: Mediator init(name: String, mediator: Mediator) { self.name = name self.mediator = mediator } func send(message: String) { mediator.send(message, colleague: self) } func receive(message: String) { assert(false, "Method should be overriden") } } protocol Mediator { func send(message: String, colleague: Colleague) } class MessageMediator: Mediator { private var colleagues: [Colleague] = [] func addColleague(colleague: Colleague) { colleagues.append(colleague) } func send(message: String, colleague: Colleague) { for c in colleagues { if c !== colleague { //for simplicity we compare object references c.receive(message) } } } } class ConcreteColleague: Colleague { override func receive(message: String) { print("Colleague \(name) received: \(message)") } } /*: ### Usage */ let messagesMediator = MessageMediator() let user0 = ConcreteColleague(name: "0", mediator: messagesMediator) let user1 = ConcreteColleague(name: "1", mediator: messagesMediator) messagesMediator.addColleague(user0) messagesMediator.addColleague(user1) user0.send("Hello") // user1 receives message /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator) */ /*: 💾 Memento ---------- The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation. ### Example */ typealias Memento = Dictionary<NSObject, AnyObject> let DPMementoKeyChapter = "com.valve.halflife.chapter" let DPMementoKeyWeapon = "com.valve.halflife.weapon" let DPMementoGameState = "com.valve.halflife.state" /*: Originator */ class GameState { var chapter: String = "" var weapon: String = "" func toMemento() -> Memento { return [ DPMementoKeyChapter:chapter, DPMementoKeyWeapon:weapon ] } func restoreFromMemento(memento: Memento) { chapter = memento[DPMementoKeyChapter] as? String ?? "n/a" weapon = memento[DPMementoKeyWeapon] as? String ?? "n/a" } } /*: Caretaker */ enum CheckPoint { static func saveState(memento: Memento, keyName: String = DPMementoGameState) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(memento, forKey: keyName) defaults.synchronize() } static func restorePreviousState(keyName keyName: String = DPMementoGameState) -> Memento { let defaults = NSUserDefaults.standardUserDefaults() return defaults.objectForKey(keyName) as? Memento ?? Memento() } } /*: ### Usage */ var gameState = GameState() gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Black Mesa Inbound" gameState.weapon = "Crowbar" CheckPoint.saveState(gameState.toMemento()) gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.saveState(gameState.toMemento(), keyName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.saveState(gameState.toMemento()) gameState.restoreFromMemento(CheckPoint.restorePreviousState(keyName: "gameState2")) /*: 👓 Observer ----------- The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes. ### Example */ protocol PropertyObserver : class { func willChangePropertyName(propertyName:String, newPropertyValue:AnyObject?) func didChangePropertyName(propertyName:String, oldPropertyValue:AnyObject?) } class TestChambers { weak var observer:PropertyObserver? var testChamberNumber: Int = 0 { willSet(newValue) { observer?.willChangePropertyName("testChamberNumber", newPropertyValue:newValue) } didSet { observer?.didChangePropertyName("testChamberNumber", oldPropertyValue:oldValue) } } } class Observer : PropertyObserver { func willChangePropertyName(propertyName: String, newPropertyValue: AnyObject?) { if newPropertyValue as? Int == 1 { print("Okay. Look. We both said a lot of things that you're going to regret.") } } func didChangePropertyName(propertyName: String, oldPropertyValue: AnyObject?) { if oldPropertyValue as? Int == 0 { print("Sorry about the mess. I've really let the place go since you killed me.") } } } /*: ### Usage */ var observerInstance = Observer() var testChambers = TestChambers() testChambers.observer = observerInstance testChambers.testChamberNumber++ /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Observer) */ /*: 🐉 State --------- The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time. ### Example */ class Context { private var state: State = UnauthorizedState() var isAuthorized: Bool { get { return state.isAuthorized(self) } } var userId: String? { get { return state.userId(self) } } func changeStateToAuthorized(userId userId: String) { state = AuthorizedState(userId: userId) } func changeStateToUnauthorized() { state = UnauthorizedState() } } protocol State { func isAuthorized(context: Context) -> Bool func userId(context: Context) -> String? } class UnauthorizedState: State { func isAuthorized(context: Context) -> Bool { return false } func userId(context: Context) -> String? { return nil } } class AuthorizedState: State { let userId: String init(userId: String) { self.userId = userId } func isAuthorized(context: Context) -> Bool { return true } func userId(context: Context) -> String? { return userId } } /*: ### Usage */ let context = Context() (context.isAuthorized, context.userId) context.changeStateToAuthorized(userId: "admin") (context.isAuthorized, context.userId) // now logged in as "admin" context.changeStateToUnauthorized() (context.isAuthorized, context.userId) /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-State) */ /*: 💡 Strategy ----------- The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time. ### Example */ protocol PrintStrategy { func printString(string: String) -> String } class Printer { let strategy: PrintStrategy func printString(string: String) -> String { return self.strategy.printString(string) } init(strategy: PrintStrategy) { self.strategy = strategy } } class UpperCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.uppercaseString } } class LowerCaseStrategy : PrintStrategy { func printString(string:String) -> String { return string.lowercaseString } } /*: ### Usage */ var lower = Printer(strategy:LowerCaseStrategy()) lower.printString("O tempora, o mores!") var upper = Printer(strategy:UpperCaseStrategy()) upper.printString("O tempora, o mores!") /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Strategy) */ /*: 🏃 Visitor ---------- The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold. ### Example */ protocol PlanetVisitor { func visit(planet: PlanetAlderaan) func visit(planet: PlanetCoruscant) func visit(planet: PlanetTatooine) } protocol Planet { func accept(visitor: PlanetVisitor) } class PlanetAlderaan: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class PlanetCoruscant: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class PlanetTatooine: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(self) } } class NameVisitor: PlanetVisitor { var name = "" func visit(planet: PlanetAlderaan) { name = "Alderaan" } func visit(planet: PlanetCoruscant) { name = "Coruscant" } func visit(planet: PlanetTatooine) { name = "Tatooine" } } /*: ### Usage */ let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine()] let names = planets.map { (planet: Planet) -> String in let visitor = NameVisitor() planet.accept(visitor) return visitor.name } names /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Visitor) */
e0dba1e230a8147de50864dcd04ded47
24.518167
245
0.672692
false
false
false
false
idomizrachi/Regen
refs/heads/master
regen/Dependencies/Colors/Colors.swift
mit
1
// // Colors.swift // Colors // // Created by Chad Scira on 3/3/15. // // https://github.com/icodeforlove/Colors import Foundation var colorCodes:[String:Int] = [ "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37 ] var bgColorCodes:[String:Int] = [ "blackBackground": 40, "redBackground": 41, "greenBackground": 42, "yellowBackground": 43, "blueBackground": 44, "magentaBackground": 45, "cyanBackground": 46, "whiteBackground": 47 ] var styleCodes:[String:Int] = [ "reset": 0, "bold": 1, "italic": 3, "underline": 4, "inverse": 7, "strikethrough": 9, "boldOff": 22, "italicOff": 23, "underlineOff": 24, "inverseOff": 27, "strikethroughOff": 29 ] func getCode(_ key: String) -> Int? { if colorCodes[key] != nil { return colorCodes[key] } else if bgColorCodes[key] != nil { return bgColorCodes[key] } else if styleCodes[key] != nil { return styleCodes[key] } return nil } func addCodeToCodesArray(_ codes: Array<Int>, code: Int) -> Array<Int> { var result:Array<Int> = codes if colorCodes.values.contains(code) { result = result.filter { !colorCodes.values.contains($0) } } else if bgColorCodes.values.contains(code) { result = result.filter { !bgColorCodes.values.contains($0) } } else if code == 0 { return [] } if !result.contains(code) { result.append(code) } return result } func matchesForRegexInText(_ regex: String!, text: String!, global: Bool = false) -> [String] { let regex = try! NSRegularExpression(pattern: regex, options: []) let nsString = text as NSString let results = regex.matches(in: nsString as String, options: [], range: NSMakeRange(0, nsString.length)) if !global && results.count == 1 { var result:[String] = [] for i in 0..<results[0].numberOfRanges { result.append(nsString.substring(with: results[0].range(at: i))) } return result } else { return results.map { nsString.substring(with: $0.range) } } } struct ANSIGroup { var codes:[Int] var string:String func toString() -> String { let codeStrings = codes.map { String($0) } return "\u{001B}[" + codeStrings.joined(separator: ";") + "m" + string + "\u{001B}[0m" } } func parseExistingANSI(_ string: String) -> [ANSIGroup] { var results:[ANSIGroup] = [] let matches = matchesForRegexInText("\\u001B\\[([^m]*)m(.+?)\\u001B\\[0m", text: string, global: true) for match in matches { var parts = matchesForRegexInText("\\u001B\\[([^m]*)m(.+?)\\u001B\\[0m", text: match), codes = parts[1].split {$0 == ";"}.map { String($0) }, string = parts[2] results.append(ANSIGroup(codes: codes.filter { Int($0) != nil }.map { Int($0)! }, string: string)) } return results } func format(_ string: String, _ command: String) -> String { if (ProcessInfo.processInfo.environment["DEBUG"] != nil && ProcessInfo.processInfo.environment["DEBUG"]! as String == "true" && (ProcessInfo.processInfo.environment["TEST"] == nil || ProcessInfo.processInfo.environment["TEST"]! as String == "false")) { return string } let code = getCode(command) let existingANSI = parseExistingANSI(string) if code == nil { return string } else if existingANSI.count > 0 { return existingANSI.map { return ANSIGroup(codes: addCodeToCodesArray($0.codes, code: code!), string: $0.string).toString() }.joined(separator: "") } else { let group = ANSIGroup(codes: [code!], string: string) return group.toString() } } public extension String { // foregrounds var black: String { return format(self, "black") } var red: String { return format(self, "red") } var green: String { return format(self, "green") } var yellow: String { return format(self, "yellow") } var blue: String { return format(self, "blue") } var magenta: String { return format(self, "magenta") } var cyan: String { return format(self, "cyan") } var white: String { return format(self, "white") } // backgrounds var blackBackground: String { return format(self, "blackBackground") } var redBackground: String { return format(self, "redBackground") } var greenBackground: String { return format(self, "greenBackground") } var yellowBackground: String { return format(self, "yellowBackground") } var blueBackground: String { return format(self, "blueBackground") } var magentaBackground: String { return format(self, "magentaBackground") } var cyanBackground: String { return format(self, "cyanBackground") } var whiteBackground: String { return format(self, "whiteBackground") } // formats var bold: String { return format(self, "bold") } var italic: String { return format(self, "italic") } var underline: String { return format(self, "underline") } var reset: String { return format(self, "reset") } var inverse: String { return format(self, "inverse") } var strikethrough: String { return format(self, "strikethrough") } var boldOff: String { return format(self, "boldOff") } var italicOff: String { return format(self, "italicOff") } var underlineOff: String { return format(self, "underlineOff") } var inverseOff: String { return format(self, "inverseOff") } var strikethroughOff: String { return format(self, "strikethroughOff") } }
082ac9c60b71c9bd8d5661f93288116e
23.812245
256
0.575424
false
false
false
false
jeffreybergier/Hipstapaper
refs/heads/main
Hipstapaper/Packages/V3Style/Sources/V3Style/PropertyWrappers/DetailTable.swift
mit
1
// // Created by Jeffrey Bergier on 2022/07/30. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import SwiftUI import Umbrella @propertyWrapper public struct DetailTable: DynamicProperty { public struct Value { public var date: some ViewModifier = DetailTableDateText() public var url: some ViewModifier = DetailTableURLText() public var title: some ViewModifier = DetailTableTitleText() public var hack_edit: some ActionStyle = ActionStyleImp(labelStyle: .titleOnly) public var hack_done: some ActionStyle = JSBToolbarButtonStyleDone public var columnWidthDate: CGFloat = .dateColumnWidthMax public var columnWidthThumbnail: CGFloat = .thumbnailColumnWidth public func thumbnail(_ data: Data?) -> some View { ThumbnailImage(data) .frame(width: .thumbnailSmall, height: .thumbnailSmall) .cornerRadius(.cornerRadiusSmall) } public func syncIndicator(_ progress: Progress) -> some ViewModifier { SyncIndicator(progress) } } public init() {} public var wrappedValue: Value { Value() } }
9ea1934ad9c817a5c6d81918f8c72f66
39.137931
88
0.690722
false
false
false
false
jaredsinclair/sodes-audio-example
refs/heads/master
Sodes/SodesAudio/ScratchFileInfo.swift
mit
1
// // ScratchFileInfo.swift // SodesAudio // // Created by Jared Sinclair on 8/16/16. // // import Foundation import SwiftableFileHandle import SodesFoundation /// Info for the current scratch file for ResourceLoaderDelegate. class ScratchFileInfo { /// Cache validation info. struct CacheInfo { let contentLength: Int64? let etag: String? let lastModified: Date? } /// The remote URL from which the file should be downloaded. let resourceUrl: URL /// The subdirectory for this scratch file and its metadata. let directory: URL /// The file url to the scratch file itself. let scratchFileUrl: URL /// The file url to the metadata for the scratch file. let metaDataUrl: URL /// The file handle used for reading/writing bytes to the scratch file. let fileHandle: SODSwiftableFileHandle /// The most recent cache validation info. var cacheInfo: CacheInfo /// The byte ranges for the scratch file that have been saved thus far. var loadedByteRanges: [ByteRange] /// Designated initializer. init(resourceUrl: URL, directory: URL, scratchFileUrl: URL, metaDataUrl: URL, fileHandle: SODSwiftableFileHandle, cacheInfo: CacheInfo, loadedByteRanges: [ByteRange]) { self.resourceUrl = resourceUrl self.directory = directory self.scratchFileUrl = scratchFileUrl self.metaDataUrl = metaDataUrl self.fileHandle = fileHandle self.cacheInfo = cacheInfo self.loadedByteRanges = loadedByteRanges } } extension ScratchFileInfo.CacheInfo { static let none = ScratchFileInfo.CacheInfo( contentLength: nil, etag: nil, lastModified: nil ) func isStillValid(comparedTo otherInfo: ScratchFileInfo.CacheInfo) -> Bool { if let old = self.etag, let new = otherInfo.etag { return old == new } else if let old = lastModified, let new = otherInfo.lastModified { return old == new } else { return false } } }
f0b7dc397e8773aa8964cd748897d696
27.213333
172
0.652647
false
false
false
false
carabina/SwiftMock
refs/heads/master
Pod/Classes/MockExpectation.swift
mit
1
// // MockExpectation.swift // SwiftMock // // Created by Matthew Flint on 13/09/2015. // // import Foundation public class MockExpectation { public var functionName: String? var args: [Any?] /// the return value for this expectation, if any public var returnValue: Any? public init() { args = [Any?]() } public func call<T>(value: T) -> MockActionable<T> { return MockActionable(value, self) } /// record the function name and arguments during the expectation-setting phase public func acceptExpected(functionName theFunctionName: String, args theArgs: Any?...) -> Bool { // do we already have a function? if so, we can't accept this call as an expectation let result = functionName == nil if result { functionName = theFunctionName args = theArgs } return result } public func isComplete() -> Bool { return functionName != nil } /// offer this function, and its arguments, to the expectation to see if it matches public func satisfy(functionName theFunctionName: String, args theArgs: Any?...) -> Bool { return functionName == theFunctionName && match(args, theArgs) } func match(firstAnyOptional: Any?, _ secondAnyOptional: Any?) -> Bool { if firstAnyOptional == nil && secondAnyOptional == nil { return true } if firstAnyOptional == nil || secondAnyOptional == nil { return false } let firstAny = firstAnyOptional! let secondAny = secondAnyOptional! // there must be a better way to match two Any? values :-/ var result = false switch(firstAny) { case let firstArray as Array<Any?>: if let secondArray = secondAny as? Array<Any?> { result = matchArraysOfOptionals(firstArray, secondArray) } case let firstArray as Array<Any>: if let secondArray = secondAny as? Array<Any> { result = matchArrays(firstArray, secondArray) } case let first as String: if let second = secondAny as? String { result = first == second } case let first as Int: if let second = secondAny as? Int { result = first == second } case let first as Double: if let second = secondAny as? Double { result = first == second } case let first as Bool: if let second = secondAny as? Bool { result = first == second } default: break } return result } func matchArraysOfOptionals(firstArray: Array<Any?>, _ secondArray: Array<Any?>) -> Bool { var result = true if firstArray.count != secondArray.count { result = false } for var index=0; index<firstArray.count && result; index++ { result = match(firstArray[index], secondArray[index]) } return result } func matchArrays(firstArray: Array<Any>, _ secondArray: Array<Any>) -> Bool { var result = true if firstArray.count != secondArray.count { result = false } for var index=0; index<firstArray.count && result; index++ { result = match(firstArray[index], secondArray[index]) } return result } }
cb6e981cf6b77b96db7efa4f0bbc4ee5
29.655172
101
0.558931
false
false
false
false
salemoh/GoldenQuraniOS
refs/heads/master
GRDB/Core/RowAdapter.swift
mit
2
import Foundation /// LayoutedColumnMapping is a type that supports the RowAdapter protocol. public struct LayoutedColumnMapping { /// An array of (baseIndex, mappedName) pairs, where baseIndex is the index /// of a column in a base row, and mappedName the mapped name of /// that column. public let layoutColumns: [(Int, String)] /// A cache for layoutIndex(ofColumn:) let lowercaseColumnIndexes: [String: Int] // [mappedColumn: layoutColumnIndex] /// Creates an LayoutedColumnMapping from an array of (baseIndex, mappedName) /// pairs. In each pair: /// /// - baseIndex is the index of a column in a base row /// - name is the mapped name of the column /// /// For example, the following LayoutedColumnMapping defines two columns, "foo" /// and "bar", based on the base columns at indexes 1 and 2: /// /// LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")]) /// /// Use it in your custom RowAdapter type: /// /// struct FooBarAdapter : RowAdapter { /// func layoutAdapter(layout: RowLayout) throws -> LayoutedRowAdapter { /// return LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")]) /// } /// } /// /// // <Row foo:"foo" bar: "bar"> /// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter()) public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) { self.layoutColumns = Array(layoutColumns) self.lowercaseColumnIndexes = Dictionary(keyValueSequence: layoutColumns .enumerated() .map { ($1.1.lowercased(), $0) } .reversed()) // reversed() so that the the dictionary caches leftmost indexes } func baseColumnIndex(atMappingIndex index: Int) -> Int { return layoutColumns[index].0 } func columnName(atMappingIndex index: Int) -> String { return layoutColumns[index].1 } } /// LayoutedColumnMapping adopts LayoutedRowAdapter extension LayoutedColumnMapping : LayoutedRowAdapter { /// Part of the LayoutedRowAdapter protocol; returns self. public var mapping: LayoutedColumnMapping { return self } /// Part of the LayoutedRowAdapter protocol; returns the empty dictionary. public var scopes: [String: LayoutedRowAdapter] { return [:] } } extension LayoutedColumnMapping : RowLayout { /// Part of the RowLayout protocol; returns the index of the leftmost column /// named `name`, in a case-insensitive way. public func layoutIndex(ofColumn name: String) -> Int? { if let index = lowercaseColumnIndexes[name] { return index } return lowercaseColumnIndexes[name.lowercased()] } } /// LayoutedRowAdapter is a protocol that supports the RowAdapter protocol. /// /// GRBD ships with a ready-made type that adopts this protocol: /// LayoutedColumnMapping. public protocol LayoutedRowAdapter { /// A LayoutedColumnMapping that defines how to map a column name to a /// column in a base row. var mapping: LayoutedColumnMapping { get } /// The layouted row adapters for each scope. var scopes: [String: LayoutedRowAdapter] { get } } /// RowLayout is a protocol that supports the RowAdapter protocol. It describes /// a layout of a base row. public protocol RowLayout { /// An array of (baseIndex, name) pairs, where baseIndex is the index /// of a column in a base row, and name the name of that column. var layoutColumns: [(Int, String)] { get } /// Returns the index of the leftmost column named `name`, in a /// case-insensitive way. func layoutIndex(ofColumn name: String) -> Int? } extension SelectStatement : RowLayout { /// Part of the RowLayout protocol. public var layoutColumns: [(Int, String)] { return Array(columnNames.enumerated()) } /// Part of the RowLayout protocol. public func layoutIndex(ofColumn name: String) -> Int? { return index(ofColumn: name) } } /// RowAdapter is a protocol that helps two incompatible row interfaces working /// together. /// /// GRDB ships with four concrete types that adopt the RowAdapter protocol: /// /// - ColumnMapping: renames row columns /// - SuffixRowAdapter: hides the first columns of a row /// - RangeRowAdapter: only exposes a range of columns /// - ScopeAdapter: groups several adapters together to define named scopes /// /// To use a row adapter, provide it to any method that fetches: /// /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// /// // <Row baz:3> /// try Row.fetchOne(db, sql, adapter: adapter) public protocol RowAdapter { /// You never call this method directly. It is called for you whenever an /// adapter has to be applied. /// /// The result is a value that adopts LayoutedRowAdapter, such as /// LayoutedColumnMapping. /// /// For example: /// /// // An adapter that turns any row to a row that contains a single /// // column named "foo" whose value is the leftmost value of the /// // base row. /// struct FirstColumnAdapter : RowAdapter { /// func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { /// return LayoutedColumnMapping(layoutColumns: [(0, "foo")]) /// } /// } /// /// // <Row foo:1> /// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter()) func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter } extension RowAdapter { /// Returns an adapter based on self, with added scopes. /// /// If self already defines scopes, the added scopes replace /// eventual existing scopes with the same name. /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter { return ScopeAdapter(mainAdapter: self, scopes: scopes) } } extension RowAdapter { func baseColumnIndex(atIndex index: Int, layout: RowLayout) throws -> Int { return try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index) } } /// ColumnMapping is a row adapter that maps column names. /// /// let adapter = ColumnMapping(["foo": "bar"]) /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz" /// /// // <Row foo:"bar"> /// try Row.fetchOne(db, sql, adapter: adapter) public struct ColumnMapping : RowAdapter { /// A dictionary from mapped column names to column names in a base row. let mapping: [String: String] /// Creates a ColumnMapping with a dictionary from mapped column names to /// column names in a base row. public init(_ mapping: [String: String]) { self.mapping = mapping } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutColumns = try mapping .map { (mappedColumn, baseColumn) -> (Int, String) in guard let index = layout.layoutIndex(ofColumn: baseColumn) else { let columnNames = layout.layoutColumns.map { $0.1 } throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).") } let baseIndex = layout.layoutColumns[index].0 return (baseIndex, mappedColumn) } .sorted { $0.0 < $1.0 } // preserve ordering of base columns return LayoutedColumnMapping(layoutColumns: layoutColumns) } } /// SuffixRowAdapter is a row adapter that hides the first columns in a row. /// /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// /// // <Row baz:3> /// try Row.fetchOne(db, sql, adapter: adapter) public struct SuffixRowAdapter : RowAdapter { /// The suffix index let index: Int /// Creates a SuffixRowAdapter that hides all columns before the /// provided index. /// /// If index is 0, the layout row is identical to the base row. public init(fromIndex index: Int) { GRDBPrecondition(index >= 0, "Negative column index is out of range") self.index = index } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index)) } } /// RangeRowAdapter is a row adapter that only exposes a range of columns. /// /// let adapter = RangeRowAdapter(1..<3) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux" /// /// // <Row bar:2 baz: 3> /// try Row.fetchOne(db, sql, adapter: adapter) public struct RangeRowAdapter : RowAdapter { /// The range let range: CountableRange<Int> /// Creates a RangeRowAdapter that only exposes a range of columns. public init(_ range: CountableRange<Int>) { GRDBPrecondition(range.lowerBound >= 0, "Negative column index is out of range") self.range = range } /// Creates a RangeRowAdapter that only exposes a range of columns. public init(_ range: CountableClosedRange<Int>) { GRDBPrecondition(range.lowerBound >= 0, "Negative column index is out of range") self.range = range.lowerBound..<(range.upperBound + 1) } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range]) } } /// ScopeAdapter is a row adapter that lets you define scopes on rows. /// /// // Two adapters /// let fooAdapter = ColumnMapping(["value": "foo"]) /// let barAdapter = ColumnMapping(["value": "bar"]) /// /// // Define scopes /// let adapter = ScopeAdapter([ /// "foo": fooAdapter, /// "bar": barAdapter]) /// /// // Fetch /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar" /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// /// // Scoped rows: /// if let fooRow = row.scoped(on: "foo") { /// fooRow.value(named: "value") // "foo" /// } /// if let barRow = row.scopeed(on: "bar") { /// barRow.value(named: "value") // "bar" /// } public struct ScopeAdapter : RowAdapter { /// The main adapter let mainAdapter: RowAdapter /// The scope adapters let scopes: [String: RowAdapter] /// Creates a scoped adapter. /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. public init(_ scopes: [String: RowAdapter]) { self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter self.scopes = scopes } init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) { self.mainAdapter = mainAdapter self.scopes = scopes } /// Part of the RowAdapter protocol public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout) var layoutedScopes = layoutedAdapter.scopes for (name, adapter) in scopes { try layoutedScopes[name] = adapter.layoutedAdapter(from: layout) } return LayoutedScopeAdapter( mapping: layoutedAdapter.mapping, scopes: layoutedScopes) } } /// The LayoutedRowAdapter for ScopeAdapter struct LayoutedScopeAdapter : LayoutedRowAdapter { let mapping: LayoutedColumnMapping let scopes: [String: LayoutedRowAdapter] } struct ChainedAdapter : RowAdapter { let first: RowAdapter let second: RowAdapter func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping) } } extension Row { /// Creates a row from a base row and a statement adapter convenience init(base: Row, adapter: LayoutedRowAdapter) { self.init(impl: AdapterRowImpl(base: base, adapter: adapter)) } /// Returns self if adapter is nil func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row { guard let adapter = adapter else { return self } return try Row(base: self, adapter: adapter.layoutedAdapter(from: layout)) } } struct AdapterRowImpl : RowImpl { let base: Row let adapter: LayoutedRowAdapter let mapping: LayoutedColumnMapping init(base: Row, adapter: LayoutedRowAdapter) { self.base = base self.adapter = adapter self.mapping = adapter.mapping } var count: Int { return mapping.layoutColumns.count } var isFetched: Bool { return base.isFetched } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { return base.value(atIndex: mapping.baseColumnIndex(atMappingIndex: index)) } func dataNoCopy(atUncheckedIndex index:Int) -> Data? { return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index)) } func columnName(atUncheckedIndex index: Int) -> String { return mapping.columnName(atMappingIndex: index) } func index(ofColumn name: String) -> Int? { return mapping.layoutIndex(ofColumn: name) } func scoped(on name: String) -> Row? { guard let adapter = adapter.scopes[name] else { return nil } return Row(base: base, adapter: adapter) } var scopeNames: Set<String> { return Set(adapter.scopes.keys) } func copy(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } }
c83828f8c2da5aee76161eb541c1cf32
34.739899
192
0.640359
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
validation-test/stdlib/OpenCLSDKOverlay.swift
apache-2.0
1
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: OS=macosx // Translated from standard OpenCL hello.c program // Abstract: A simple "Hello World" compute example showing basic usage of OpenCL which // calculates the mathematical square (X[i] = pow(X[i],2)) for a buffer of // floating point values. // // // Version: <1.0> // // Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") // in consideration of your agreement to the following terms, and your use, // installation, modification or redistribution of this Apple software // constitutes acceptance of these terms. If you do not agree with these // terms, please do not use, install, modify or redistribute this Apple // software. // // In consideration of your agreement to abide by the following terms, and // subject to these terms, Apple grants you a personal, non - exclusive // license, under Apple's copyrights in this original Apple software ( the // "Apple Software" ), to use, reproduce, modify and redistribute the Apple // Software, with or without modifications, in source and / or binary forms // provided that if you redistribute the Apple Software in its entirety and // without modifications, you must retain this notice and the following text // and disclaimers in all such redistributions of the Apple Software. Neither // the name, trademarks, service marks or logos of Apple Inc. may be used to // endorse or promote products derived from the Apple Software without specific // prior written permission from Apple. Except as expressly stated in this // notice, no other rights or licenses, express or implied, are granted by // Apple herein, including but not limited to any patent rights that may be // infringed by your derivative works or by other works in which the Apple // Software may be incorporated. // // The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO // WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED // WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION // ALONE OR IN COMBINATION WITH YOUR PRODUCTS. // // IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR // CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION // AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER // UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR // OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright ( C ) 2008 Apple Inc. All Rights Reserved. // import OpenCL import StdlibUnittest import Foundation import Darwin let KernelSource = "\n" + "__kernel void square( \n" + " __global float* input, \n" + " __global float* output, \n" + " const unsigned int count) \n" + "{ \n" + " int i = get_global_id(0); \n" + " if(i < count) \n" + " output[i] = input[i] * input[i]; \n" + "} \n" + "\n" let DATA_SIZE = 1024 var tests = TestSuite("MiscSDKOverlay") tests.test("clSetKernelArgsListAPPLE") { var err: cl_int // error code returned from api calls var data = [Float](count: DATA_SIZE, repeatedValue: 0) // original data set given to device var results = [Float](count: DATA_SIZE, repeatedValue: 0) // results returned from device var correct: Int // number of correct results returned var global: size_t // global domain size for our calculation var local: size_t = 0 // local domain size for our calculation var device_id: cl_device_id = nil // compute device id var context: cl_context // compute context var commands: cl_command_queue // compute command queue var program: cl_program // compute program var kernel: cl_kernel // compute kernel var input: cl_mem // device memory used for the input array var output: cl_mem // device memory used for the output array // Fill our data set with random float values // var i = 0 var count = DATA_SIZE for i = 0; i < count; i++ { data[i] = Float(rand()) / Float(RAND_MAX) } // Connect to a compute device // var gpu = 1 err = clGetDeviceIDs(nil, cl_device_type(gpu != 0 ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU), 1, &device_id, nil) if (err != CL_SUCCESS) { print("Error: Failed to create a device group!") exit(EXIT_FAILURE) } // Create a compute context // context = clCreateContext(nil, 1, &device_id, nil, nil, &err) if (context == nil) { print("Error: Failed to create a compute context!") exit(EXIT_FAILURE) } // Create a command commands // commands = clCreateCommandQueue(context, device_id, 0, &err) if (commands == nil) { print("Error: Failed to create a command commands!") exit(EXIT_FAILURE) } // Create the compute program from the source buffer // program = KernelSource.withCString { (s: UnsafePointer<CChar>)->cl_program in var s = s return withUnsafeMutablePointer(&s) { return clCreateProgramWithSource(context, 1, $0, nil, &err) } } if (program == nil) { print("Error: Failed to create compute program!") exit(EXIT_FAILURE) } // Build the program executable // err = clBuildProgram(program, 0, nil, nil, nil, nil) if (err != CL_SUCCESS) { var len: Int = 0 var buffer = [CChar](count:2048, repeatedValue: 0) print("Error: Failed to build program executable!") clGetProgramBuildInfo( program, device_id, cl_program_build_info(CL_PROGRAM_BUILD_LOG), 2048, &buffer, &len) print("\(String.fromCString(buffer)!)") exit(1) } // Create the compute kernel in the program we wish to run // kernel = clCreateKernel(program, "square", &err) if (kernel == nil || err != cl_int(CL_SUCCESS)) { print("Error: Failed to create compute kernel!") exit(1) } // Create the input and output arrays in device memory for our calculation // input = clCreateBuffer(context, cl_mem_flags(CL_MEM_READ_ONLY), sizeof(Float.self) * count, nil, nil) output = clCreateBuffer(context, cl_mem_flags(CL_MEM_WRITE_ONLY), sizeof(Float.self) * count, nil, nil) if (input == nil || output == nil) { print("Error: Failed to allocate device memory!") exit(1) } // Write our data set into the input array in device memory // err = clEnqueueWriteBuffer(commands, input, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, data, 0, nil, nil) if (err != CL_SUCCESS) { print("Error: Failed to write to source array!") exit(1) } // Set the arguments to our compute kernel // err = 0 err = withUnsafePointers(&input, &output, &count) { inputPtr, outputPtr, countPtr in clSetKernelArgsListAPPLE( kernel, 3, 0, sizeof(cl_mem.self), inputPtr, 1, sizeof(cl_mem.self), outputPtr, 2, sizeofValue(count), countPtr) } if (err != CL_SUCCESS) { print("Error: Failed to set kernel arguments! \(err)") exit(1) } // Get the maximum work group size for executing the kernel on the device // err = clGetKernelWorkGroupInfo(kernel, device_id, cl_kernel_work_group_info(CL_KERNEL_WORK_GROUP_SIZE), sizeofValue(local), &local, nil) if (err != CL_SUCCESS) { print("Error: Failed to retrieve kernel work group info! \(err)") exit(1) } // Execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // global = count err = clEnqueueNDRangeKernel(commands, kernel, 1, nil, &global, &local, 0, nil, nil) if (err != 0) { print("Error: Failed to execute kernel!") exit(EXIT_FAILURE) } // Wait for the command commands to get serviced before reading back results // clFinish(commands) // Read back the results from the device to verify the output // err = clEnqueueReadBuffer( commands, output, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, &results, cl_uint(0), nil, nil ) if (err != CL_SUCCESS) { print("Error: Failed to read output array! \(err)") exit(1) } // Validate our results // correct = 0 for(i = 0; i < count; i++) { if(results[i] == data[i] * data[i]){ correct += 1 } } // Print a brief summary detailing the results // print("Computed '\(correct)/\(count)' correct values!") // Shutdown and cleanup // clReleaseMemObject(input) clReleaseMemObject(output) clReleaseProgram(program) clReleaseKernel(kernel) clReleaseCommandQueue(commands) clReleaseContext(context) } runAllTests()
b6a93dc33f6218add594586d512b1ac6
35.775281
138
0.608209
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/CollectionKit-master/Examples/ReloadDataExample/ReloadDataViewController.swift
mit
1
// // ReloadDataViewController.swift // CollectionKit // // Created by yansong li on 2017-09-04. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit import CollectionKit class ReloadDataViewController: CollectionViewController { let dataProvider = ArrayDataProvider<Int>(data: Array(0..<5)) { (_, data) in return "\(data)" } let addButton: UIButton = { let button = UIButton() button.setTitle("+", for: .normal) button.titleLabel?.font = .boldSystemFont(ofSize: 20) button.backgroundColor = UIColor(hue: 0.6, saturation: 0.68, brightness: 0.98, alpha: 1) button.layer.shadowColor = UIColor.black.cgColor button.layer.shadowOffset = CGSize(width: 0, height: -12) button.layer.shadowRadius = 10 button.layer.shadowOpacity = 0.1 return button }() var currentMax: Int = 5 override func viewDidLoad() { super.viewDidLoad() addButton.addTarget(self, action: #selector(add), for: .touchUpInside) view.addSubview(addButton) collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10) let layout = FlowLayout<Int>(lineSpacing: 15, interitemSpacing: 15, justifyContent: .spaceAround, alignItems: .center, alignContent: .center) let presenter = CollectionPresenter() presenter.insertAnimation = .scale presenter.deleteAnimation = .scale presenter.updateAnimation = .normal let provider = CollectionProvider( dataProvider: dataProvider, viewUpdater: { (view: UILabel, data: Int, index: Int) in view.backgroundColor = UIColor(hue: CGFloat(data) / 30, saturation: 0.68, brightness: 0.98, alpha: 1) view.textColor = .white view.textAlignment = .center view.layer.cornerRadius = 4 view.layer.masksToBounds = true view.text = "\(data)" } ) provider.layout = layout provider.sizeProvider = { (index, data, _) in return CGSize(width: 80, height: data % 3 == 0 ? 120 : 80) } provider.presenter = presenter provider.tapHandler = { [weak self] (view, index, _) in self?.dataProvider.data.remove(at: index) } self.provider = provider } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let viewWidth = view.bounds.width let viewHeight = view.bounds.height addButton.frame = CGRect(x: 0, y: viewHeight - 44, width: viewWidth, height: 44) collectionView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight - 44) } @objc func add() { dataProvider.data.append(currentMax) currentMax += 1 // NOTE: Call reloadData() directly will make collectionView update immediately, so that contentSize // of collectionView will be updated. collectionView.reloadData() collectionView.scrollTo(edge: .bottom, animated:true) } }
79b75a141ab1e709aa3fbcedb391a82d
33.303371
104
0.627579
false
false
false
false
SwifterSwift/SwifterSwift
refs/heads/master
Sources/SwifterSwift/UIKit/UITextViewExtensions.swift
mit
1
// UITextViewExtensions.swift - Copyright 2020 SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Methods public extension UITextView { /// SwifterSwift: Clear text. func clear() { text = "" attributedText = NSAttributedString(string: "") } /// SwifterSwift: Scroll to the bottom of text view. func scrollToBottom() { let range = NSRange(location: (text as NSString).length - 1, length: 1) scrollRangeToVisible(range) } /// SwifterSwift: Scroll to the top of text view. func scrollToTop() { let range = NSRange(location: 0, length: 1) scrollRangeToVisible(range) } /// SwifterSwift: Wrap to the content (Text / Attributed Text). func wrapToContent() { contentInset = .zero scrollIndicatorInsets = .zero contentOffset = .zero textContainerInset = .zero textContainer.lineFragmentPadding = 0 sizeToFit() } } #endif
66984a988b0f99fdbcccc6d749824809
24.973684
79
0.632219
false
false
false
false
Khan/swiftz
refs/heads/master
swiftz/TupleExt.swift
bsd-3-clause
2
// // TupleExt.swift // swiftz // // Created by Maxwell Swadling on 7/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation // the standard library has _.1, _.2 functions // these functions are more useful when "doing fp" (point-free-ish forms) public func fst<A, B>(ab: (A, B)) -> A { switch ab { case let (a, _): return a } } public func fst<A, B, C>() -> Lens<(A, C), (B, C), A, B> { return Lens { (x, y) in IxStore(x) { ($0, y) } } } public func snd<A, B>(ab: (A, B)) -> B { switch ab { case let (_, b): return b } } public func snd<A, B, C>() -> Lens<(A, B), (A, C), B, C> { return Lens { (x, y) in IxStore(y) { (x, $0) } } } //Not possible to extend like this currently. //extension () : Equatable {} //extension (T:Equatable, U:Equatable) : Equatable {} public func ==(lhs: (), rhs: ()) -> Bool { return true } public func !=(lhs: (), rhs: ()) -> Bool { return false } // Unlike Python a 1-tuple is just it's contained element. public func == <T:Equatable,U:Equatable>(lhs: (T,U), rhs: (T,U)) -> Bool { let (l0,l1) = lhs let (r0,r1) = rhs return l0 == r0 && l1 == r1 } public func != <T:Equatable,U:Equatable>(lhs: (T,U), rhs: (T,U)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable>(lhs: (T,U,V), rhs: (T,U,V)) -> Bool { let (l0,l1,l2) = lhs let (r0,r1,r2) = rhs return l0 == r0 && l1 == r1 && l2 == r2 } public func != <T:Equatable,U:Equatable,V:Equatable>(lhs: (T,U,V), rhs: (T,U,V)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable>(lhs: (T,U,V,W), rhs: (T,U,V,W)) -> Bool { let (l0,l1,l2,l3) = lhs let (r0,r1,r2,r3) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable>(lhs: (T,U,V,W), rhs: (T,U,V,W)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable>(lhs: (T,U,V,W,X), rhs: (T,U,V,W,X)) -> Bool { let (l0,l1,l2,l3,l4) = lhs let (r0,r1,r2,r3,r4) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 && l4 == r4 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable>(lhs: (T,U,V,W,X), rhs: (T,U,V,W,X)) -> Bool { return !(lhs==rhs) } public func == <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable,Z:Equatable>(lhs: (T,U,V,W,X,Z), rhs: (T,U,V,W,X,Z)) -> Bool { let (l0,l1,l2,l3,l4,l5) = lhs let (r0,r1,r2,r3,r4,r5) = rhs return l0 == r0 && l1 == r1 && l2 == r2 && l3 == r3 && l4 == r4 && l5 == r5 } public func != <T:Equatable,U:Equatable,V:Equatable,W:Equatable,X:Equatable,Z:Equatable>(lhs: (T,U,V,W,X,Z), rhs: (T,U,V,W,X,Z)) -> Bool { return !(lhs==rhs) }
cad0ccd052626db9e2e5a889b773e848
30.755814
138
0.576346
false
false
false
false
HuylensHu/realm-cocoa
refs/heads/master
RealmSwift-swift1.2/RealmConfiguration.swift
apache-2.0
3
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private extension Realm { /** A `Configuration` is used to describe the different options used to create a `Realm` instance. */ public struct Configuration { // MARK: Default Configuration /// Returns the default Configuration used to create Realms when no other /// configuration is explicitly specified (i.e. `Realm()`). public static var defaultConfiguration: Configuration { get { return fromRLMRealmConfiguration(RLMRealmConfiguration.defaultConfiguration()) } set { RLMRealmConfiguration.setDefaultConfiguration(newValue.rlmConfiguration) } } // MARK: Initialization /** Initializes a `Configuration`, suitable for creating new `Realm` instances. :param: path The path to the realm file. :param: inMemoryIdentifier A string used to identify a particular in-memory Realm. :param: encryptionKey 64-byte key to use to encrypt the data. :param: readOnly Whether the Realm is read-only (must be true for read-only files). :param: schemaVersion The current schema version. :param: migrationBlock The block which migrates the Realm to the current version. :returns: An initialized `Configuration`. */ public init(path: String? = RLMRealmConfiguration.defaultRealmPath(), inMemoryIdentifier: String? = nil, encryptionKey: NSData? = nil, readOnly: Bool = false, schemaVersion: UInt64 = 0, migrationBlock: MigrationBlock? = nil) { self.path = path self.inMemoryIdentifier = inMemoryIdentifier self.encryptionKey = encryptionKey self.readOnly = readOnly self.schemaVersion = schemaVersion self.migrationBlock = migrationBlock } // MARK: Configuration Properties /// The path to the realm file. /// Mutually exclusive with `inMemoryIdentifier`. public var path: String? { set { if newValue != nil { inMemoryIdentifier = nil } _path = newValue } get { return _path } } private var _path: String? /// A string used to identify a particular in-memory Realm. /// Mutually exclusive with `path`. public var inMemoryIdentifier: String? { set { if newValue != nil { path = nil } _inMemoryIdentifier = newValue } get { return _inMemoryIdentifier } } private var _inMemoryIdentifier: String? = nil /// 64-byte key to use to encrypt the data. public var encryptionKey: NSData? { set { _encryptionKey = RLMRealmValidatedEncryptionKey(newValue) } get { return _encryptionKey } } private var _encryptionKey: NSData? = nil /// Whether the Realm is read-only (must be true for read-only files). public var readOnly: Bool = false /// The current schema version. public var schemaVersion: UInt64 = 0 /// The block which migrates the Realm to the current version. public var migrationBlock: MigrationBlock? = nil // MARK: Private Methods internal var rlmConfiguration: RLMRealmConfiguration { let configuration = RLMRealmConfiguration() configuration.path = self.path configuration.inMemoryIdentifier = self.inMemoryIdentifier configuration.encryptionKey = self.encryptionKey configuration.readOnly = self.readOnly configuration.schemaVersion = self.schemaVersion configuration.migrationBlock = self.migrationBlock.map { accessorMigrationBlock($0) } return configuration } internal static func fromRLMRealmConfiguration(rlmConfiguration: RLMRealmConfiguration) -> Configuration { return Configuration(path: rlmConfiguration.path, inMemoryIdentifier: rlmConfiguration.inMemoryIdentifier, encryptionKey: rlmConfiguration.encryptionKey, readOnly: rlmConfiguration.readOnly, schemaVersion: UInt64(rlmConfiguration.schemaVersion), migrationBlock: map(rlmConfiguration.migrationBlock) { rlmMigration in return { migration, schemaVersion in rlmMigration(migration.rlmMigration, schemaVersion) } }) } } } // MARK: Printable extension Realm.Configuration: Printable { /// Returns a human-readable description of the configuration. public var description: String { return gsub("\\ARLMRealmConfiguration", "Configuration", rlmConfiguration.description) ?? "" } }
b1db9de2addbd2a918cf47feb9a2dffe
34.428571
112
0.61413
false
true
false
false
luanlzsn/pos
refs/heads/master
pos/Classes/pos/Payment/Controller/MergeBillController.swift
mit
1
// // MergeBillController.swift // pos // // Created by luan on 2017/5/30. // Copyright © 2017年 luan. All rights reserved. // import UIKit class MergeBillController: AntController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { @IBOutlet weak var orderNum: UILabel!//订单号 @IBOutlet weak var orderTableView: UITableView!//点单信息 @IBOutlet weak var billTableView: UITableView!//账单信息 @IBOutlet weak var inputLabel: UILabel!//输入 @IBOutlet weak var subTotal: UILabel!//小计 @IBOutlet weak var discountView: UIView!//折扣信息 @IBOutlet weak var discount: UILabel!//折扣 @IBOutlet weak var afterDiscount: UILabel!//折后价 @IBOutlet weak var taxLabel: UILabel!//税率 @IBOutlet weak var taxTop: NSLayoutConstraint! @IBOutlet weak var taxMoney: UILabel!//税额 @IBOutlet weak var total: UILabel!//总计 @IBOutlet weak var receive: UILabel!//收到 @IBOutlet weak var cashMoney: UILabel!//现金 @IBOutlet weak var cardMoney: UILabel!//卡 @IBOutlet weak var remainingTitle: UILabel!//剩余、找零 @IBOutlet weak var remaining: UILabel!//剩余、找零 @IBOutlet weak var tipMoney: UILabel!//小费 @IBOutlet weak var cardBtn: UIButton!//卡按钮 @IBOutlet weak var cashBtn: UIButton!//现金按钮 @IBOutlet weak var calculatorCollection: UICollectionView! var tableNoArray = [Int]() var modelDic = [Int : OrderModel]()//订单信息 var orderItemDic = [Int : [OrderItemModel]]()//已点数组 let calculatorArray = ["1","2","3","4","5","6","7","8","9","0",".","Back",NSLocalizedString("默认", comment: ""),NSLocalizedString("清空", comment: ""),NSLocalizedString("输入", comment: "")] override func viewDidLoad() { super.viewDidLoad() orderTableView.separatorInset = UIEdgeInsets.zero orderTableView.layoutMargins = UIEdgeInsets.zero orderTableView.rowHeight = UITableViewAutomaticDimension orderTableView.estimatedRowHeight = 60 billTableView.rowHeight = UITableViewAutomaticDimension billTableView.estimatedRowHeight = 60 for tableNo in tableNoArray { getOrderInfo(tableNo: tableNo) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() calculatorCollection.reloadData() billTableView.reloadData() } @IBAction func homeClick() { navigationController?.popToRootViewController(animated: true) } // MARK: 获取订单信息 func getOrderInfo(tableNo: Int) { weak var weakSelf = self AntManage.postRequest(path: "tables/getOrderInfoByTable", params: ["table":tableNo, "type":"D", "access_token":AntManage.userModel!.token], successResult: { (response) in weakSelf?.modelDic[tableNo] = OrderModel.mj_object(withKeyValues: response["Order"]) weakSelf?.orderItemDic[tableNo] = OrderItemModel.mj_objectArray(withKeyValuesArray: response["OrderItem"]) as? [OrderItemModel] weakSelf?.refreshOrderInfo() }, failureResult: { weakSelf?.navigationController?.popViewController(animated: true) }) } // MARK: 应用折扣 func discountApple(orderModel: OrderModel) { UIApplication.shared.keyWindow?.endEditing(true) let discount = orderModel.inputDiscount let type = orderModel.inputDiscountType if !discount.isEmpty { weak var weakSelf = self AntManage.postRequest(path: "discountHandler/addDiscount", params: ["order_no":orderModel.order_no, "access_token":AntManage.userModel!.token, "discountType":type, "discountValue":discount, "cashier_id":AntManage.userModel!.cashier_id], successResult: { (_) in weakSelf?.getOrderInfo(tableNo: orderModel.table_no) }, failureResult: {}) } else { AntManage.showDelayToast(message: NSLocalizedString("请输入折扣。", comment: "")) } } // MARK: 删除折扣 func removeDiscount(orderModel: OrderModel) { weak var weakSelf = self AntManage.postRequest(path: "discountHandler/removeDiscount", params: ["order_no":orderModel.order_no, "access_token":AntManage.userModel!.token], successResult: { (_) in weakSelf?.getOrderInfo(tableNo: orderModel.table_no) }, failureResult: {}) } // MARK: 打印收据 @IBAction func printPayBillClick() { var order_ids = [Int]() for model in modelDic.values { order_ids.append(model.orderId) } AntManage.postRequest(path: "print/printMergeBill", params: ["restaurant_id":AntManage.userModel!.restaurant_id, "order_ids":order_ids, "access_token":AntManage.userModel!.token], successResult: { (_) in AntManage.showDelayToast(message: NSLocalizedString("打印收据成功。", comment: "")) }, failureResult: {}) } // MARK: 选择卡支付 @IBAction func cardClick() { cardBtn.isSelected = true cashBtn.isSelected = false cardBtn.backgroundColor = UIColor.init(rgb: 0xC30E22) cashBtn.backgroundColor = UIColor.init(rgb: 0xF4D6D5) inputLabel.text = "" } // MARK: 选择现金支付 @IBAction func cashClick() { cardBtn.isSelected = false cashBtn.isSelected = true cardBtn.backgroundColor = UIColor.init(rgb: 0xF4D6D5) cashBtn.backgroundColor = UIColor.init(rgb: 0xC30E22) inputLabel.text = "" } // MARK: 确认支付 @IBAction func confirmClick() { if !cardBtn.isSelected, !cashBtn.isSelected { AntManage.showDelayToast(message: NSLocalizedString("请选择卡或现金付款方式。", comment: "")) return } if remainingTitle.text == NSLocalizedString("找零", comment: "") { var order_ids = [Int]() var table_merge = "" for model in modelDic.values { order_ids.append(model.orderId) table_merge += "\(model.table_no)," } table_merge.remove(at: table_merge.index(before: table_merge.endIndex)) let main_order_id = modelDic[tableNoArray.first!]!.orderId var params: [String : Any] = ["order_ids":order_ids, "table":tableNoArray.first!, "cashier_id":AntManage.userModel!.cashier_id, "restaurant_id":AntManage.userModel!.restaurant_id, "access_token":AntManage.userModel!.token, "main_order_id":main_order_id, "table_merge":table_merge] params["paid_by"] = cardBtn.isSelected ? "card" : "cash" params["pay"] = receive.text!.components(separatedBy: "$").last! if remaining.text!.components(separatedBy: "$").last! == "0.00" { params["change"] = "" } else { params["change"] = remaining.text!.components(separatedBy: "$").last! } params["card_val"] = cardMoney.text!.components(separatedBy: "$").last! params["cash_val"] = cashMoney.text!.components(separatedBy: "$").last! if tipMoney.text!.components(separatedBy: "$").last! == "0.00" { params["tip_paid_by"] = "" params["tip_val"] = "" } else { params["tip_paid_by"] = "CARD" params["tip_val"] = tipMoney.text!.components(separatedBy: "$").last! } weak var weakSelf = self AntManage.postRequest(path: "payHandler/completeMergeOrder", params: params, successResult: { (_) in weakSelf?.printMergeReceipt(orderIds: order_ids) }, failureResult: {}) } else { AntManage.showDelayToast(message: NSLocalizedString("金额无效,请检查再次验证。", comment: "")) } } func printMergeReceipt(orderIds: [Int]) { weak var weakSelf = self AntManage.postRequest(path: "print/printMergeReceipt", params: ["restaurant_id":AntManage.userModel!.restaurant_id, "order_ids":orderIds, "access_token":AntManage.userModel!.token], successResult: { (_) in weakSelf?.homeClick() }, failureResult: {}) } func refreshOrderInfo() { var orderNo = ""//订单号 var tableNo = ""//餐桌号 var subtotal = 0.0 var tax = 0 var tax_amount = 0.0 var totalFloat = 0.0 var remainingFloat = 0.0 var discount_value = 0.0 var after_discount = 0.0 for tableNumber in tableNoArray { if let orderModel = modelDic[tableNumber] { orderNo += orderModel.order_no + " " subtotal += orderModel.subtotal tax = orderModel.tax tax_amount += orderModel.tax_amount totalFloat += orderModel.total remainingFloat += orderModel.total discount_value += orderModel.discount_value after_discount += orderModel.after_discount } if tableNumber == tableNoArray.first { tableNo += "#\(tableNumber) " + NSLocalizedString("和", comment: "") } else { tableNo += "#\(tableNumber) " } } orderNo.remove(at: orderNo.index(before: orderNo.endIndex)) let orderNumStr = NSLocalizedString("订单号", comment: "") + " \(orderNo)," + NSLocalizedString("桌", comment: "") + "[[\(NSLocalizedString("堂食", comment: ""))]]\(tableNo)" + NSLocalizedString("合并", comment: "") orderNum.text = orderNumStr subTotal.text = "$" + String(format: "%.2f", subtotal) taxLabel.text = NSLocalizedString("税", comment: "") + "(\(tax)%)" taxMoney.text = "$" + String(format: "%.2f", tax_amount) total.text = "$" + String(format: "%.2f", totalFloat) remaining.text = "$" + String(format: "%.2f", remainingFloat) if discount_value > 0 { taxTop.constant = 61 discountView.isHidden = false discount.text = "$" + String(format: "%.2f", discount_value) afterDiscount.text = "$" + String(format: "%.2f", after_discount) } else { taxTop.constant = 0 discountView.isHidden = true } orderTableView.reloadData() billTableView.reloadData() checkReceiveMoney() } // MARK: 处理收到的金额 func checkReceiveMoney() { let card = (cardMoney.text!.components(separatedBy: "$").last! as NSString).doubleValue let cash = (cashMoney.text!.components(separatedBy: "$").last! as NSString).doubleValue receive.text = "$" + String(format: "%.2f", card + cash) let totalDouble = (total.text!.substring(from: total.text!.index(after: total.text!.startIndex)) as NSString).doubleValue let tip = (String(format: "%.2f", card - totalDouble) as NSString).floatValue if tip >= 0 { tipMoney.text = "$" + String(format: "%.2f", fabs(card - totalDouble)) remainingTitle.text = NSLocalizedString("找零", comment: "") remaining.text = "$" + String(format: "%.2f", cash) } else { tipMoney.text = "$0.00" let remainingF = (String(format: "%.2f", card + cash - totalDouble) as NSString).floatValue if remainingF >= 0 { remainingTitle.text = NSLocalizedString("找零", comment: "") remaining.text = "$" + String(format: "%.2f", fabs(card + cash - totalDouble)) } else { remainingTitle.text = NSLocalizedString("剩余", comment: "") remaining.text = "$" + String(format: "%.2f", totalDouble - (card + cash)) } } } // MARK: UITableViewDelegate,UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return tableNoArray.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == orderTableView { if orderItemDic.keys.contains(tableNoArray[section]) { return orderItemDic[tableNoArray[section]]!.count } else { return 0 } } else { if modelDic.keys.contains(tableNoArray[section]) { return 1 } else { return 0 } } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if tableView == orderTableView { return 30 } else { return 0.01 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if tableView == orderTableView { return 0.01 } else { return 10 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView == orderTableView { return tableView.rowHeight } else { let model = modelDic[tableNoArray[indexPath.section]]! if model.discount_value > 0.0 { return 210 } else { if model.isAddDiscount { return 250 } else { return 160 } } } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if tableView == orderTableView { return "#\(tableNoArray[section]) BILL" } else { return nil } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == orderTableView { let cell: PaymentOrderCell = tableView.dequeueReusableCell(withIdentifier: "PaymentOrderCell", for: indexPath) as! PaymentOrderCell let model = orderItemDic[tableNoArray[indexPath.section]]![indexPath.row] cell.nameLabel.text = model.name_en + "\n" + model.name_xh var extrasStr = "" if model.selected_extras.count > 0 { for extras in model.selected_extras { if extras == model.selected_extras.last { extrasStr += extras.name } else { extrasStr += "\(extras.name)," } } } cell.extrasLabel.text = extrasStr if model.qty > 1 { cell.priceLabel.text = "$\(model.price)x\(model.qty)" } else { cell.priceLabel.text = "$\(model.price)" } return cell } else { let cell: MergeBillCell = tableView.dequeueReusableCell(withIdentifier: "MergeBillCell", for: indexPath) as! MergeBillCell let model = modelDic[tableNoArray[indexPath.section]]! cell.refreshOrderBill(model: model) weak var weakSelf = self cell.checkDiscount = { (type) in if (type as! Int) == 1 { if model.discount_value > 0 { weakSelf?.removeDiscount(orderModel: model) } else { model.isAddDiscount = !model.isAddDiscount tableView.reloadData() } } else { weakSelf?.discountApple(orderModel: model) } } return cell } } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = (collectionView.height - 4.0) / 5.0 let width = (collectionView.width - 2.0) / 3.0 return CGSize(width: width, height: height) } // MARK: UICollectionViewDelegate,UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return calculatorArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: CalculatorCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalculatorCell", for: indexPath) as! CalculatorCell cell.calculatorTitle.text = calculatorArray[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if cardBtn.isSelected || cashBtn.isSelected { if indexPath.row <= 9 { inputLabel.text! += calculatorArray[indexPath.row] } else if indexPath.row == 10 { if !inputLabel.text!.contains(calculatorArray[indexPath.row]) { inputLabel.text! += calculatorArray[indexPath.row] } } else if indexPath.row == 11 { if !inputLabel.text!.isEmpty { inputLabel.text!.remove(at: inputLabel.text!.index(before: inputLabel.text!.endIndex)) } } else if indexPath.row == 12 { let totalDouble = (total.text!.substring(from: total.text!.index(after: total.text!.startIndex)) as NSString).doubleValue inputLabel.text = String(format: "%.2f", totalDouble) } else if indexPath.row == 13 { if cardBtn.isSelected { cardMoney.text = NSLocalizedString("卡", comment: "") + ":$0.00" } else { cashMoney.text = NSLocalizedString("现金", comment: "") + ":$0.00" } inputLabel.text = "" checkReceiveMoney() } else if indexPath.row == 14 { if cardBtn.isSelected { cardMoney.text = NSLocalizedString("卡", comment: "") + String(format: ":$%.2f", (inputLabel.text! as NSString).floatValue) } else { cashMoney.text = NSLocalizedString("现金", comment: "") + String(format: ":$%.2f", (inputLabel.text! as NSString).floatValue) } checkReceiveMoney() } } else { AntManage.showDelayToast(message: NSLocalizedString("请选择支付方式 卡/现金。", comment: "")) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
1c310459b4fb706ba57f3b8633e8b4e3
42.765116
292
0.588235
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Mocks/MockOfferingsManager.swift
mit
1
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // MockOfferingsManager.swift // // Created by Juanpe Catalán on 8/8/21. import Foundation @testable import RevenueCat // swiftlint:disable identifier_name // Note: this class is implicitly `@unchecked Sendable` through its parent // even though it's not actually thread safe. class MockOfferingsManager: OfferingsManager { typealias OfferingsCompletion = @MainActor @Sendable (Result<Offerings, Error>) -> Void var invokedOfferings = false var invokedOfferingsCount = 0 var invokedOfferingsParameters: (appUserID: String, fetchPolicy: FetchPolicy, completion: OfferingsCompletion?)? var invokedOfferingsParametersList = [(appUserID: String, fetchPolicy: FetchPolicy, completion: OfferingsCompletion??)]() var stubbedOfferingsCompletionResult: Result<Offerings, Error>? override func offerings(appUserID: String, fetchPolicy: FetchPolicy, completion: (@MainActor @Sendable (Result<Offerings, Error>) -> Void)?) { self.invokedOfferings = true self.invokedOfferingsCount += 1 self.invokedOfferingsParameters = (appUserID, fetchPolicy, completion) self.invokedOfferingsParametersList.append((appUserID, fetchPolicy, completion)) OperationDispatcher.dispatchOnMainActor { [result = self.stubbedOfferingsCompletionResult] in completion?(result!) } } struct InvokedUpdateOfferingsCacheParameters { let appUserID: String let isAppBackgrounded: Bool let fetchPolicy: OfferingsManager.FetchPolicy let completion: (@MainActor @Sendable (Result<Offerings, Error>) -> Void)? } var invokedUpdateOfferingsCache = false var invokedUpdateOfferingsCacheCount = 0 var invokedUpdateOfferingsCacheParameters: InvokedUpdateOfferingsCacheParameters? var invokedUpdateOfferingsCachesParametersList = [InvokedUpdateOfferingsCacheParameters]() var stubbedUpdateOfferingsCompletionResult: Result<Offerings, Error>? override func updateOfferingsCache( appUserID: String, isAppBackgrounded: Bool, fetchPolicy: OfferingsManager.FetchPolicy, completion: (@MainActor @Sendable (Result<Offerings, Error>) -> Void)? ) { self.invokedUpdateOfferingsCache = true self.invokedUpdateOfferingsCacheCount += 1 let parameters = InvokedUpdateOfferingsCacheParameters( appUserID: appUserID, isAppBackgrounded: isAppBackgrounded, fetchPolicy: fetchPolicy, completion: completion ) self.invokedUpdateOfferingsCacheParameters = parameters self.invokedUpdateOfferingsCachesParametersList.append(parameters) OperationDispatcher.dispatchOnMainActor { [result = self.stubbedUpdateOfferingsCompletionResult] in completion?(result!) } } var invokedInvalidateAndReFetchCachedOfferingsIfAppropiate = false var invokedInvalidateAndReFetchCachedOfferingsIfAppropiateCount = 0 var invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParameters: String? var invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParametersList = [String]() override func invalidateAndReFetchCachedOfferingsIfAppropiate(appUserID: String) { invokedInvalidateAndReFetchCachedOfferingsIfAppropiate = true invokedInvalidateAndReFetchCachedOfferingsIfAppropiateCount += 1 invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParameters = appUserID invokedInvalidateAndReFetchCachedOfferingsIfAppropiateParametersList.append(appUserID) } }
f881208872878065be465af12c80a481
40.649485
107
0.713119
false
false
false
false
JGiola/swift
refs/heads/main
test/Distributed/SIL/distributed_actor_default_init_sil_6.swift
apache-2.0
5
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -module-name default_deinit -primary-file %s -emit-sil -verify -disable-availability-checking -I %t | %FileCheck %s --enable-var-scope --dump-input=fail // REQUIRES: concurrency // REQUIRES: distributed /// The convention in this test is that the Swift declaration comes before its FileCheck lines. import Distributed import FakeDistributedActorSystems typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ---------------------------------------------------------------------------------------------------------------- class SomeClass {} enum Err : Error { case blah } func getSystem() throws -> FakeActorSystem { throw Err.blah } distributed actor MyDistActor { init() throws { self.actorSystem = try getSystem() } // CHECK: sil hidden @$s14default_deinit11MyDistActorCACyKcfc : $@convention(method) (@owned MyDistActor) -> (@owned MyDistActor, @error Error) { // CHECK: bb0([[SELF:%[0-9]+]] : $MyDistActor): // CHECK: builtin "initializeDefaultActor"([[SELF]] : $MyDistActor) // CHECK: try_apply {{%[0-9]+}}() : $@convention(thin) () -> (@owned FakeActorSystem, @error Error), normal [[SUCCESS_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // CHECK: [[SUCCESS_BB]]([[SYSTEM_VAL:%[0-9]+]] : $FakeActorSystem): // *** save system *** // CHECK: [[TP_FIELD1:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.actorSystem // CHECK: store [[SYSTEM_VAL]] to [[TP_FIELD1]] : $*FakeActorSystem // *** obtain an identity *** // CHECK: [[TP_FIELD2:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.actorSystem // CHECK: [[RELOADED_SYS1:%[0-9]+]] = load [[TP_FIELD2]] : $*FakeActorSystem // CHECK: [[SELF_METATYPE:%[0-9]+]] = metatype $@thick MyDistActor.Type // CHECK: [[ASSIGN_ID_FN:%[0-9]+]] = function_ref @$s27FakeDistributedActorSystems0aC6SystemV8assignIDyAA0C7AddressVxm0B00bC0RzAF0G0RtzlF // CHECK: [[ID:%[0-9]+]] = apply [[ASSIGN_ID_FN]]<MyDistActor>([[SELF_METATYPE]], [[RELOADED_SYS1]]) // *** save identity *** // CHECK: [[ID_FIELD:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.id // CHECK: store [[ID]] to [[ID_FIELD]] : $*ActorAddress // *** invoke actorReady *** // CHECK: [[TP_FIELD3:%[0-9]+]] = ref_element_addr [[SELF]] : $MyDistActor, #MyDistActor.actorSystem // CHECK: [[RELOADED_SYS2:%[0-9]+]] = load [[TP_FIELD3]] : $*FakeActorSystem // CHECK: [[READY_FN:%[0-9]+]] = function_ref @$s27FakeDistributedActorSystems0aC6SystemV10actorReadyyyx0B00bC0RzAA0C7AddressV2IDRtzlF // CHECK: = apply [[READY_FN]]<MyDistActor>([[SELF]], [[RELOADED_SYS2]]) // CHECK: return [[SELF]] // CHECK: [[ERROR_BB]]([[ERRVAL:%[0-9]+]] : $Error): // CHECK-NEXT: = metatype $@thick MyDistActor.Type // CHECK-NEXT: = builtin "destroyDefaultActor"([[SELF]] : $MyDistActor) : $() // CHECK-NEXT: dealloc_partial_ref [[SELF]] // CHECK: throw [[ERRVAL]] : $Error // CHECK: } // end sil function '$s14default_deinit11MyDistActorCACyKcfc' }
c574d796743b6cbbb2f7c2a895cd870e
50.369231
222
0.630428
false
false
false
false
Authman2/Pix
refs/heads/0331
CD/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQTitleBarButtonItem.swift
apache-2.0
35
// // IQTitleBarButtonItem.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 private var kIQBarTitleInvocationTarget = "kIQBarTitleInvocationTarget" private var kIQBarTitleInvocationSelector = "kIQBarTitleInvocationSelector" open class IQTitleBarButtonItem: IQBarButtonItem { open var font : UIFont? { didSet { if let unwrappedFont = font { _titleButton?.titleLabel?.font = unwrappedFont } else { _titleButton?.titleLabel?.font = UIFont.systemFont(ofSize: 13) } } } override open var title: String? { didSet { _titleButton?.setTitle(title, for: UIControlState()) } } /** selectableTextColor to be used for displaying button text when button is enabled. */ open var selectableTextColor : UIColor? { didSet { if let color = selectableTextColor { _titleButton?.setTitleColor(color, for:UIControlState()) } else { _titleButton?.setTitleColor(UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1), for:UIControlState()) } } } /** Optional target & action to behave toolbar title button as clickable button @param target Target object. @param action Target Selector. */ open func setTitleTarget(_ target: AnyObject?, action: Selector?) { titleInvocation = (target, action) } /** Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method. */ open var titleInvocation : (target: AnyObject?, action: Selector?) { get { let target: AnyObject? = objc_getAssociatedObject(self, &kIQBarTitleInvocationTarget) as AnyObject? var action : Selector? if let selectorString = objc_getAssociatedObject(self, &kIQBarTitleInvocationSelector) as? String { action = NSSelectorFromString(selectorString) } return (target: target, action: action) } set(newValue) { objc_setAssociatedObject(self, &kIQBarTitleInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let unwrappedSelector = newValue.action { objc_setAssociatedObject(self, &kIQBarTitleInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(self, &kIQBarTitleInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } if (newValue.target == nil || newValue.action == nil) { self.isEnabled = false _titleButton?.isEnabled = false _titleButton?.removeTarget(nil, action: nil, for: .touchUpInside) } else { self.isEnabled = true _titleButton?.isEnabled = true _titleButton?.addTarget(newValue.target, action: newValue.action!, for: .touchUpInside) } } } fileprivate var _titleButton : UIButton? fileprivate var _titleView : UIView? override init() { super.init() } init(title : String?) { self.init(title: nil, style: UIBarButtonItemStyle.plain, target: nil, action: nil) _titleView = UIView() _titleView?.backgroundColor = UIColor.clear _titleView?.autoresizingMask = [.flexibleWidth,.flexibleHeight] _titleButton = UIButton(type: .system) _titleButton?.isEnabled = false _titleButton?.titleLabel?.numberOfLines = 3 _titleButton?.setTitleColor(UIColor.lightGray, for:.disabled) _titleButton?.setTitleColor(UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1), for:UIControlState()) _titleButton?.backgroundColor = UIColor.clear _titleButton?.titleLabel?.textAlignment = .center _titleButton?.setTitle(title, for: UIControlState()) _titleButton?.autoresizingMask = [.flexibleWidth,.flexibleHeight] font = UIFont.systemFont(ofSize: 13.0) _titleButton?.titleLabel?.font = self.font _titleView?.addSubview(_titleButton!) customView = _titleView } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
36cd7c536340f17e038e6f3ac6f086a6
38.8125
177
0.64748
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
brave/src/frontend/sync/SyncCodewordsView.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 Shared class SyncCodewordsView: UIView, UITextViewDelegate { lazy var field: UITextView = { let textView = UITextView() textView.autocapitalizationType = .none textView.autocorrectionType = .yes textView.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightMedium) textView.textColor = BraveUX.GreyJ return textView }() lazy var placeholder: UILabel = { let label = UILabel() label.text = Strings.CodeWordInputHelp label.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightRegular) label.textColor = BraveUX.GreyE label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 return label }() var wordCountChangeCallback: ((_ count: Int) -> Void)? var currentWordCount = 0 convenience init(data: [String]) { self.init() translatesAutoresizingMaskIntoConstraints = false addSubview(field) addSubview(placeholder) setCodewords(data: data) field.snp.makeConstraints { (make) in make.edges.equalTo(self).inset(20) } placeholder.snp.makeConstraints { (make) in make.top.left.right.equalTo(field).inset(UIEdgeInsetsMake(8, 4, 0, 0)) } field.delegate = self } func setCodewords(data: [String]) { field.text = data.count > 0 ? data.joined(separator: " ") : "" updateWordCount() } func codeWords() -> [String] { return field.text.separatedBy(" ").filter { $0.count > 0 } } func wordCount() -> Int { return codeWords().count } func updateWordCount() { placeholder.isHidden = (field.text.count != 0) let wordCount = self.wordCount() if wordCount != currentWordCount { currentWordCount = wordCount wordCountChangeCallback?(wordCount) } } @discardableResult override func becomeFirstResponder() -> Bool { field.becomeFirstResponder() return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return text != "\n" } func textViewDidChange(_ textView: UITextView) { updateWordCount() } }
a3a00ebcf642663382f41f6fb7c3218d
29.447059
198
0.603555
false
false
false
false
ixx1232/FoodTrackerStudy
refs/heads/master
FoodTracker/FoodTracker/MealViewController.swift
mit
1
// // ViewController.swift // FoodTracker // // Created by apple on 15/12/22. // Copyright © 2015年 www.ixx.com. All rights reserved. // import UIKit class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK:Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var ratingControl: RatingControl! @IBOutlet weak var saveButton: UIBarButtonItem! var meal: Meal? override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self if let meal = meal { navigationItem.title = meal.name nameTextField.text = meal.name photoImageView.image = meal.photo ratingControl.rating = meal.rating } checkValidMealName() } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField) { saveButton.enabled = false } func checkValidMealName() { let text = nameTextField.text ?? "" saveButton.enabled = !text.isEmpty } func textFieldDidEndEditing(textField: UITextField) { checkValidMealName() navigationItem.title = textField.text } // MARK:UIImagePickerControllerDelegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage photoImageView.image = selectedImage dismissViewControllerAnimated(true, completion: nil) } @IBAction func cancel(sender: AnyObject) { let isPresentingInAddMealMode = presentingViewController is UINavigationController if isPresentingInAddMealMode { dismissViewControllerAnimated(true, completion: nil) } else { navigationController!.popViewControllerAnimated(true) } } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if saveButton === sender { let name = nameTextField.text ?? "" let photo = photoImageView.image let rating = ratingControl.rating meal = Meal(name: name, photo: photo, rating: rating) } } // MARK: Actions @IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) { nameTextField.resignFirstResponder() let imagePickerController = UIImagePickerController() imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePickerController.delegate = self presentViewController(imagePickerController, animated: true, completion: nil) } }
a4f361e44bc043d9259cdf4e3805836a
27.277311
130
0.633878
false
false
false
false
omaralbeik/SwifterSwift
refs/heads/master
Sources/Extensions/UIKit/UITableViewExtensions.swift
mit
1
// // UITableViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Properties public extension UITableView { /// SwifterSwift: Index path of last row in tableView. public var indexPathForLastRow: IndexPath? { return indexPathForLastRow(inSection: lastSection) } /// SwifterSwift: Index of last section in tableView. public var lastSection: Int { return numberOfSections > 0 ? numberOfSections - 1 : 0 } } // MARK: - Methods public extension UITableView { /// SwifterSwift: Number of all rows in all sections of tableView. /// /// - Returns: The count of all rows in the tableView. public func numberOfRows() -> Int { var section = 0 var rowCount = 0 while section < numberOfSections { rowCount += numberOfRows(inSection: section) section += 1 } return rowCount } /// SwifterSwift: IndexPath for last row in section. /// /// - Parameter section: section to get last row in. /// - Returns: optional last indexPath for last row in section (if applicable). public func indexPathForLastRow(inSection section: Int) -> IndexPath? { guard section >= 0 else { return nil } guard numberOfRows(inSection: section) > 0 else { return IndexPath(row: 0, section: section) } return IndexPath(row: numberOfRows(inSection: section) - 1, section: section) } /// Reload data with a completion handler. /// /// - Parameter completion: completion handler to run after reloadData finishes. public func reloadData(_ completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } /// SwifterSwift: Remove TableFooterView. public func removeTableFooterView() { tableFooterView = nil } /// SwifterSwift: Remove TableHeaderView. public func removeTableHeaderView() { tableHeaderView = nil } /// SwifterSwift: Scroll to bottom of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). public func scrollToBottom(animated: Bool = true) { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) setContentOffset(bottomOffset, animated: animated) } /// SwifterSwift: Scroll to top of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). public func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint.zero, animated: animated) } /// SwifterSwift: Dequeue reusable UITableViewCell using class name /// /// - Parameter name: UITableViewCell type /// - Returns: UITableViewCell object with associated class name. public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name))") } return cell } /// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath /// /// - Parameters: /// - name: UITableViewCell type. /// - indexPath: location of cell in tableView. /// - Returns: UITableViewCell object with associated class name. public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else { fatalError("Couldn't find UITableViewCell for \(String(describing: name))") } return cell } /// SwifterSwift: Dequeue reusable UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type /// - Returns: UITableViewHeaderFooterView object with associated class name. public func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T { guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T else { fatalError("Couldn't find UITableViewHeaderFooterView for \(String(describing: name))") } return headerFooterView } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameters: /// - nib: Nib file used to create the header or footer view. /// - name: UITableViewHeaderFooterView type. public func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) { register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type public func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) { register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameter name: UITableViewCell type public func register<T: UITableViewCell>(cellWithClass name: T.Type) { register(T.self, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameters: /// - nib: Nib file used to create the tableView cell. /// - name: UITableViewCell type. public func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) { register(nib, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell with .xib file using only its corresponding class. /// Assumes that the .xib filename and cell class has the same name. /// /// - Parameters: /// - name: UITableViewCell type. /// - bundleClass: Class in which the Bundle instance will be based on. public func register<T: UITableViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) { let identifier = String(describing: name) var bundle: Bundle? if let bundleName = bundleClass { bundle = Bundle(for: bundleName) } register(UINib(nibName: identifier, bundle: bundle), forCellReuseIdentifier: identifier) } /// SwifterSwift: Check whether IndexPath is valid within the tableView /// /// - Parameter indexPath: An IndexPath to check /// - Returns: Boolean value for valid or invalid IndexPath public func isValidIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section) } /// SwifterSwift: Safely scroll to possibly invalid IndexPath /// /// - Parameters: /// - indexPath: Target IndexPath to scroll to /// - scrollPosition: Scroll position /// - animated: Whether to animate or not public func safeScrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) { guard indexPath.section < numberOfSections else { return } guard indexPath.row < numberOfRows(inSection: indexPath.section) else { return } scrollToRow(at: indexPath, at: scrollPosition, animated: animated) } } #endif
e9bcffc1aa9f6cef4075c8e41758a5f6
38.091837
123
0.670843
false
false
false
false
d-soto11/MaterialTB
refs/heads/master
MaterialTapBar/Helper/Extensions.swift
mit
1
// // Extensions.swift // MaterialTapBar // // Created by Daniel Soto on 9/25/17. // Copyright © 2017 Tres Astronautas. All rights reserved. // import Foundation 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) } } extension UIView { func addNormalShadow() { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) self.layer.shadowOpacity = 0.1 self.layer.shadowPath = shadowPath.cgPath } func addInvertedShadow() { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: -2.0) self.layer.shadowOpacity = 0.1 self.layer.shadowPath = shadowPath.cgPath } func addSpecialShadow(size: CGSize, opacitiy: Float = 0.15) { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = size self.layer.shadowOpacity = opacitiy self.layer.shadowPath = shadowPath.cgPath } func addLightShadow() { self.layoutIfNeeded() let shadowPath = UIBezierPath(rect: self.bounds) self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) self.layer.shadowOpacity = 0.05 self.layer.shadowPath = shadowPath.cgPath } func clearShadows() { self.layer.shadowOpacity = 0.0 } func roundCorners(radius: CGFloat) { self.layer.cornerRadius = radius self.layer.shadowRadius = radius } func bordered(color:UIColor) { self.layer.borderColor = color.cgColor self.layer.borderWidth = 1.0 } func addInnerShadow() { self.layer.borderColor = UIColor(netHex:0x545454).withAlphaComponent(0.3).cgColor self.layer.borderWidth = 1.0 } } extension NSLayoutConstraint { func setMultiplier(multiplier:CGFloat) -> NSLayoutConstraint { let newConstraint = NSLayoutConstraint( item: firstItem!, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant) newConstraint.priority = priority newConstraint.shouldBeArchived = self.shouldBeArchived newConstraint.identifier = self.identifier UIView.animate(withDuration: 0.3) { NSLayoutConstraint.deactivate([self]) NSLayoutConstraint.activate([newConstraint]) } return newConstraint } } extension UIViewController { func canPerformSegue(id: String) -> Bool { let segues = self.value(forKey: "storyboardSegueTemplates") as? [NSObject] let filtered = segues?.filter({ $0.value(forKey: "identifier") as? String == id }) return (filtered?.count ?? 0 > 0) } // Just so you dont have to check all the time func performSpecialSegue(id: String, sender: AnyObject?) -> Void { if canPerformSegue(id: id) { self.performSegue(withIdentifier: id, sender: sender) } } } extension UIImage { func maskWithColor(color: UIColor) -> UIImage? { let maskImage = cgImage! let width = size.width let height = size.height let bounds = CGRect(x: 0, y: 0, width: width, height: height) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! context.clip(to: bounds, mask: maskImage) context.setFillColor(color.cgColor) context.fill(bounds) if let cgImage = context.makeImage() { let coloredImage = UIImage(cgImage: cgImage) return coloredImage } else { return nil } } }
bddc11891a130fd5757a6738b58b23c0
32.258278
172
0.621466
false
false
false
false
AshuMishra/iAppStreetDemo
refs/heads/master
iAppStreet App/Utility/Paginator.swift
mit
1
// // Paginator.swift // iAppStreet App // // Created by Ashutosh Mishra on 19/07/15. // Copyright (c) 2015 Ashutosh Mishra. All rights reserved. // import Foundation import UIKit import IJReachability import Alamofire import SwiftyJSON class Paginator: NSObject { var url: String var parameters: [String:String] private var finalResult: [String] var pageCount = 0 var nextPageToken: NSString? var isCallInProgress:Bool = false var allPagesLoaded:Bool = false typealias RequestCompletionBlock = (result: [String]?, error: NSError?,allPagesLoaded:Bool) -> () init(urlString:NSString,queryParameters:[String:String]?) { url = urlString as String parameters = queryParameters! finalResult = [String]() } func reset() { self.pageCount = 0 self.finalResult = [] } func shouldLoadNext()-> Bool { return !(allPagesLoaded && isCallInProgress) } func loadFirst(completionBlock:RequestCompletionBlock) { //Load the first page of search results var checkInternetConnection:Bool = IJReachability.isConnectedToNetwork() if checkInternetConnection { self.reset() var params = parameters let page = 1 params["page"] = String(page) self.finalResult = [String]() isCallInProgress = false HUDController.sharedController.contentView = HUDContentView.ProgressView() HUDController.sharedController.show() Alamofire.request(.GET, baseURL, parameters: params, encoding: ParameterEncoding.URL).responseJSON { (request, response, data , error) -> Void in if data != nil { let jsonData = JSON(data!) let photos: Array<JSON> = jsonData["photos"].arrayValue for photo in photos { let dict:Dictionary = photo.dictionaryValue var URLString:String = dict["image_url"]!.stringValue self.finalResult.append(URLString) } HUDController.sharedController.hide(animated: true) completionBlock(result: self.finalResult,error: error,allPagesLoaded:false) self.isCallInProgress = false }else { HUDController.sharedController.hide(animated: true) } } }else { // self.showNetworkError() HUDController.sharedController.hide(animated: true) var error = NSError(domain: "Network error", code: 1, userInfo: nil) completionBlock(result: nil, error: error, allPagesLoaded: false) isCallInProgress = false } } func showNetworkError() { UIAlertView(title: "Error", message: "Device is not connected to internet. Please check connection and try again.", delegate: nil, cancelButtonTitle: "OK").show() } func loadNext(completionBlock:RequestCompletionBlock) { if (self.isCallInProgress) {return} var checkInternetConnection:Bool = IJReachability.isConnectedToNetwork() if checkInternetConnection { var params = parameters self.pageCount = self.pageCount + 1 params["page"] = String(self.pageCount) isCallInProgress = true Alamofire.request(.GET, baseURL, parameters: params, encoding: ParameterEncoding.URL).responseJSON { (request, response, data , error) -> Void in let jsonData = JSON(data!) let photos: Array<JSON> = jsonData["photos"].arrayValue for photo in photos { let dict:Dictionary = photo.dictionaryValue var URLString:String = dict["image_url"]!.stringValue self.finalResult.append(URLString) } completionBlock(result: self.finalResult,error: error,allPagesLoaded:false) self.isCallInProgress = false } }else { // self.showNetworkError() completionBlock(result: self.finalResult, error: nil, allPagesLoaded: false) isCallInProgress = false } } }
e02a3a522e1070fe6514bde2c7e6f21c
29.581197
164
0.722952
false
false
false
false
ahayman/RxStream
refs/heads/master
RxStreamTests/ColdTests.swift
mit
1
// // ColdTests.swift // RxStream // // Created by Aaron Hayman on 3/22/17. // Copyright © 2017 Aaron Hayman. All rights reserved. // import XCTest import Rx class ColdTests: XCTestCase { func testRequestSuccess() { var responses = [String]() var errors = [Error]() var terms = [Termination]() let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in response(.success(request + 1)) } let cold = coldTask .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } cold.request(1) XCTAssertEqual(responses, ["2"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) cold.request(2) XCTAssertEqual(responses, ["2", "3"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) cold.request(4) XCTAssertEqual(responses, ["2", "3", "5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["2", "3", "5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) cold.request(5) XCTAssertEqual(responses, ["2", "3", "5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) } func testRequestErrors() { var responses = [String]() var errors = [Error]() var terms = [Termination]() let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in if request % 2 == 0 { response(.success(request + 1)) } else { response(.failure(TestError())) } } let cold = coldTask .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } cold.request(1) XCTAssertEqual(responses, []) XCTAssertEqual(errors.count, 1) XCTAssertEqual(terms, []) cold.request(2) XCTAssertEqual(responses, ["3"]) XCTAssertEqual(errors.count, 1) XCTAssertEqual(terms, []) cold.request(4) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 1) XCTAssertEqual(terms, []) cold.request(7) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 2) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 2) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) cold.request(5) XCTAssertEqual(responses, ["3", "5"]) XCTAssertEqual(errors.count, 2) XCTAssertEqual(terms, [.completed]) XCTAssertEqual(cold.state, .terminated(reason: .completed)) } func testBranchIsolation() { let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in if request % 2 == 0 { response(.success(request + 1)) } else { response(.failure(TestError())) } } var branchAResponses = [String]() var branchAErrors = [Error]() var branchATerms = [Termination]() let branchA = coldTask .map{ "\($0)" } .on{ branchAResponses.append($0) } .onError{ branchAErrors.append($0) } .onTerminate{ branchATerms.append($0) } var branchBResponses = [String]() var branchBErrors = [Error]() var branchBTerms = [Termination]() let branchB = coldTask .map{ "\($0)" } .on{ branchBResponses.append($0) } .onError{ branchBErrors.append($0) } .onTerminate{ branchBTerms.append($0) } branchA.request(2) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 0) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, []) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) branchA.request(3) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, []) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) branchB.request(2) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) branchB.request(3) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, [.completed]) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, [.completed]) } func testBranchSharing() { let coldTask = Cold { (_, request: Int, response: (Result<Int>) -> Void) in if request % 2 == 0 { response(.success(request + 1)) } else { response(.failure(TestError())) } } var branchAResponses = [String]() var branchAErrors = [Error]() var branchATerms = [Termination]() coldTask .map{ "\($0)" } .on{ branchAResponses.append($0) } .onError{ branchAErrors.append($0) } .onTerminate{ branchATerms.append($0) } var branchBResponses = [String]() var branchBErrors = [Error]() var branchBTerms = [Termination]() coldTask .map{ "\($0)" } .on{ branchBResponses.append($0) } .onError{ branchBErrors.append($0) } .onTerminate{ branchBTerms.append($0) } coldTask.request(2, share: true) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 0) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 0) XCTAssertEqual(branchBTerms, []) coldTask.request(3, share: true) XCTAssertEqual(branchAResponses, ["3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, []) coldTask.request(2, share: true) XCTAssertEqual(branchAResponses, ["3", "3"]) XCTAssertEqual(branchAErrors.count, 1) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3", "3"]) XCTAssertEqual(branchBErrors.count, 1) XCTAssertEqual(branchBTerms, []) coldTask.request(3, share: true) XCTAssertEqual(branchAResponses, ["3", "3"]) XCTAssertEqual(branchAErrors.count, 2) XCTAssertEqual(branchATerms, []) XCTAssertEqual(branchBResponses, ["3", "3"]) XCTAssertEqual(branchBErrors.count, 2) XCTAssertEqual(branchBTerms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(branchAResponses, ["3", "3"]) XCTAssertEqual(branchAErrors.count, 2) XCTAssertEqual(branchATerms, [.completed]) XCTAssertEqual(branchBResponses, ["3", "3"]) XCTAssertEqual(branchBErrors.count, 2) XCTAssertEqual(branchBTerms, [.completed]) } func testRequestMapping() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Double, Double> { _, request, respond in respond(.success(request + 0.5)) } let branch = coldTask .mapRequest{ (request: Int) in return Double(request) } .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["1.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(3) XCTAssertEqual(responses, ["1.5", "3.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(10) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testMultipleEventsFromFlatten() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Int, [String]> { _, request, respond in let responses = (0..<request).map{ "\($0)" } respond(.success(responses)) } let branch = coldTask .flatten() .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["0"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] branch.request(3) XCTAssertEqual(responses, ["0", "1", "2"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] branch.request(10) XCTAssertEqual(responses, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, []) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testTieredMultiEventsUsingFlatten() { var responses = [String]() var tier2 = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Int, [String]> { _, request, respond in let responses = (0..<request).map{ "\($0)" } respond(.success(responses)) } let branch = coldTask .flatten() .on{ responses.append($0) } .flatMap{ return [$0, $0] } .on{ tier2.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["0"]) XCTAssertEqual(tier2, ["0", "0"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] tier2 = [] branch.request(3) XCTAssertEqual(responses, ["0", "1", "2"]) XCTAssertEqual(tier2, ["0", "0", "1", "1", "2", "2"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] tier2 = [] branch.request(10) XCTAssertEqual(responses, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]) XCTAssertEqual(tier2, ["0", "0", "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6", "7", "7", "8", "8", "9", "9"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) responses = [] tier2 = [] coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, []) XCTAssertEqual(tier2, []) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testTaskMultipleResponseBlock() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Double, Double> { _, request, respond in respond(.success(request + 0.5)) respond(.success(request + 100)) // Secondary response should be ignored } let branch = coldTask .mapRequest{ (request: Int) in return Double(request) } .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) XCTAssertEqual(responses, ["1.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(3) XCTAssertEqual(responses, ["1.5", "3.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(10) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } func testTaskMultipleResponseAsyncBlock() { var responses = [String]() var terms = [Termination]() var errors = [Error]() let coldTask = Cold<Double, Double> { _, request, respond in respond(.success(request + 0.5)) respond(.success(request + 100)) // Secondary response should be ignored }.dispatch(.async(on: .main)) let branch = coldTask .mapRequest{ (request: Int) in return Double(request) } .map{ "\($0)" } .on{ responses.append($0) } .onError{ errors.append($0) } .onTerminate{ terms.append($0) } branch.request(1) wait(for: 0.01) XCTAssertEqual(responses, ["1.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(3) wait(for: 0.01) XCTAssertEqual(responses, ["1.5", "3.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) branch.request(10) wait(for: 0.01) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, []) coldTask.terminate(withReason: .completed) wait(for: 0.01) XCTAssertEqual(responses, ["1.5", "3.5", "10.5"]) XCTAssertEqual(errors.count, 0) XCTAssertEqual(terms, [.completed]) } }
505ad7eb7fdcc6a5817887535359033d
29.344444
127
0.616697
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Views/Maps Tab/Map/MapImageSizable.swift
mit
1
// // MapImageSizable.swift // MEGameTracker // // Created by Emily Ivie on 12/29/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit public protocol MapImageSizable: class { var map: Map? { get } var mapImageScrollView: UIScrollView? { get } var mapImageScrollHeightConstraint: NSLayoutConstraint? { get set } var mapImageWrapperView: UIView? { get set } var lastMapImageName: String? { get set } func setupMapImage(baseView: UIView?, competingView: UIView?) func resizeMapImage(baseView: UIView?, competingView: UIView?) } extension MapImageSizable { public func setupMapImage(baseView: UIView?, competingView: UIView?) { guard map?.image?.isEmpty == false, let mapImageWrapperView = mapImageWrapper() else { return } self.mapImageWrapperView = mapImageWrapperView // clean old subviews mapImageScrollView?.subviews.forEach { $0.removeFromSuperview() } // size scrollView mapImageScrollView?.contentSize = mapImageWrapperView.bounds.size mapImageScrollView?.addSubview(mapImageWrapperView) // mapImageWrapperView.fillView(mapImageScrollView) // don't do this! sizeMapImage(baseView: baseView, competingView: competingView) shiftMapImage(baseView: baseView, competingView: competingView) } public func resizeMapImage(baseView: UIView?, competingView: UIView?) { sizeMapImage(baseView: baseView, competingView: competingView) shiftMapImage(baseView: baseView, competingView: competingView) } private func sizeMapImage(baseView: UIView?, competingView: UIView?) { if mapImageScrollHeightConstraint == nil { mapImageScrollHeightConstraint = mapImageScrollView?.superview?.heightAnchor .constraint(equalToConstant: 10000) mapImageScrollHeightConstraint?.isActive = true } else { mapImageScrollHeightConstraint?.constant = 10000 } guard let mapImageScrollView = mapImageScrollView, let mapImageScrollHeightConstraint = mapImageScrollHeightConstraint, let _ = mapImageWrapperView else { return } baseView?.layoutIfNeeded() mapImageScrollView.superview?.isHidden = false let maxHeight = (baseView?.bounds.height ?? 0) - (competingView?.bounds.height ?? 0) mapImageScrollHeightConstraint.constant = maxHeight mapImageScrollView.superview?.layoutIfNeeded() mapImageScrollView.minimumZoomScale = currentImageRatio( baseView: baseView, competingView: competingView ) ?? 0.01 mapImageScrollView.maximumZoomScale = 10 mapImageScrollView.zoomScale = mapImageScrollView.minimumZoomScale } private func mapImageWrapper() -> UIView? { if lastMapImageName == map?.image && self.mapImageWrapperView != nil { return self.mapImageWrapperView } else { // clear out old values self.mapImageWrapperView?.subviews.forEach { $0.removeFromSuperview() } } guard let filename = map?.image, let basePath = Bundle.currentAppBundle.path(forResource: "Maps", ofType: nil), let pdfView = UIPDFView(url: URL(fileURLWithPath: basePath).appendingPathComponent(filename)) else { return nil } let mapImageWrapperView = UIView(frame: pdfView.bounds) mapImageWrapperView.accessibilityIdentifier = "Map Image" mapImageWrapperView.addSubview(pdfView) lastMapImageName = map?.image return mapImageWrapperView } private func shiftMapImage(baseView: UIView?, competingView: UIView?) { guard let mapImageScrollView = mapImageScrollView, let mapImageWrapperView = mapImageWrapperView, let currentImageRatio = currentImageRatio(baseView: baseView, competingView: competingView) else { return } // center in window let differenceX: CGFloat = { let x = mapImageScrollView.bounds.width - (mapImageWrapperView.bounds.width * currentImageRatio) return max(0, x) }() mapImageScrollView.contentInset.left = floor(differenceX / 2) mapImageScrollView.contentInset.right = mapImageScrollView.contentInset.left let differenceY: CGFloat = { let y = mapImageScrollView.bounds.height - (mapImageWrapperView.bounds.height * currentImageRatio) return max(0, y) }() mapImageScrollView.contentInset.top = floor(differenceY / 2) mapImageScrollView.contentInset.bottom = mapImageScrollView.contentInset.top } private func currentImageRatio(baseView: UIView?, competingView: UIView?) -> CGFloat? { guard let mapImageWrapperView = self.mapImageWrapperView, mapImageWrapperView.bounds.height > 0 else { return nil } let maxWidth = baseView?.bounds.width ?? 0 let maxHeight = (baseView?.bounds.height ?? 0) - (competingView?.bounds.height ?? 0) return min(maxWidth / mapImageWrapperView.bounds.width, maxHeight / mapImageWrapperView.bounds.height) } }
047486bb8a7dc98a7a0b57b485648582
36.41129
110
0.764173
false
false
false
false
wibosco/WhiteBoardCodingChallenges
refs/heads/main
WhiteBoardCodingChallenges/Challenges/HackerRank/TimeConverter/TimeConverter.swift
mit
1
// // TimeConverter.swift // WhiteBoardCodingChallenges // // Created by Boles on 07/05/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit //https://www.hackerrank.com/challenges/time-conversion class TimeConverter: NSObject { class func convertFrom12HourTo24HourUsingDateManipulation(time: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm:ssa" let date12 = dateFormatter.date(from: time) dateFormatter.dateFormat = "HH:mm:ss" let date24 = dateFormatter.string(from: date12!) return date24 } }
7994afc4635ed5cb4c56d15728e681a5
24.88
87
0.659969
false
false
false
false
luinily/hOme
refs/heads/master
hOme/UI/SequenceViewController.swift
mit
1
// // SequenceViewController.swift // hOme // // Created by Coldefy Yoann on 2016/02/10. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import UIKit class SequenceViewController: UITableViewController { @IBOutlet weak var table: UITableView! private let _sectionProperties = 0 private let _sectionCommands = 1 private let _sectionAddCommand = 2 private var _sequence: Sequence? private var _commands = [(time: Int, command: CommandProtocol)]() override func viewDidLoad() { table.delegate = self table.dataSource = self } func setSequence(_ sequence: Sequence) { _sequence = sequence makeSequenceArray(sequence) } func makeSequenceArray(_ sequence: Sequence) { let commands = sequence.getCommands() var sequenceArray = [(time: Int, command: CommandProtocol)]() commands.forEach { (time, commands) in for command in commands { sequenceArray.append((time, command)) } } _commands = sequenceArray } //MARK: - Table Data Source //MARK: Sections override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case _sectionProperties: return 1 case _sectionCommands: return _commands.count case _sectionAddCommand: return 1 default: return 0 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case _sectionProperties: return "Name" case _sectionCommands: return "Commands" case _sectionAddCommand: return "" default: return "" } } //MARK: Cells override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell? if (indexPath as NSIndexPath).section == _sectionProperties { cell = tableView.dequeueReusableCell(withIdentifier: "SequenceNameCell") if let cell = cell as? NameEditCell { cell.nameAble = _sequence } } else if (indexPath as NSIndexPath).section == _sectionCommands { cell = tableView.dequeueReusableCell(withIdentifier: "SequenceCommandCell") if let cell = cell as? SequenceCommandCell { cell.setCommand(_commands[(indexPath as NSIndexPath).row]) } } else { cell = tableView.dequeueReusableCell(withIdentifier: "AddSequenceCommandCell") if let cell = cell { if let label = cell.textLabel { label.text = "Add New Command..." } } } if let cell = cell { return cell } else { return UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell") } } //MARK: - Table Delegate override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if (indexPath as NSIndexPath).section == _sectionCommands { let delete = UITableViewRowAction(style: .destructive, title: "Delete") { action, indexPath in if let cell = tableView.cellForRow(at: indexPath) as? SequenceCommandCell { if let sequence = self._sequence, let command = cell.command { sequence.removeCommand(time: command.time, commandToRemove: command.command) tableView.reloadData() } } } return [delete] } else { return [] } } }
d71dde6009058cae5ee39cfda8855f23
25.15748
121
0.704094
false
false
false
false
PokeMapCommunity/PokeMap-iOS
refs/heads/master
Pods/Moya/Source/Response.swift
mit
2
import Foundation public final class Response: CustomDebugStringConvertible, Equatable { public let statusCode: Int public let data: NSData public let response: NSURLResponse? public init(statusCode: Int, data: NSData, response: NSURLResponse? = nil) { self.statusCode = statusCode self.data = data self.response = response } public var description: String { return "Status Code: \(statusCode), Data Length: \(data.length)" } public var debugDescription: String { return description } } public func == (lhs: Response, rhs: Response) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } public extension Response { /// Filters out responses that don't fall within the given range, generating errors when others are encountered. public func filterStatusCodes(range: ClosedInterval<Int>) throws -> Response { guard range.contains(statusCode) else { throw Error.StatusCode(self) } return self } public func filterStatusCode(code: Int) throws -> Response { return try filterStatusCodes(code...code) } public func filterSuccessfulStatusCodes() throws -> Response { return try filterStatusCodes(200...299) } public func filterSuccessfulStatusAndRedirectCodes() throws -> Response { return try filterStatusCodes(200...399) } /// Maps data received from the signal into a UIImage. func mapImage() throws -> Image { guard let image = Image(data: data) else { throw Error.ImageMapping(self) } return image } /// Maps data received from the signal into a JSON object. func mapJSON() throws -> AnyObject { do { return try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } catch { throw Error.Underlying(error as NSError) } } /// Maps data received from the signal into a String. func mapString() throws -> String { guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) else { throw Error.StringMapping(self) } return string as String } }
6587d6334fab07f58ee6061214b00c9f
29.426667
116
0.645048
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/Blueprints-master/Example-OSX/Common/Extensions/UIEdgeInsetsExtensions.swift
mit
1
import Cocoa extension NSEdgeInsets { init?(top: String?, left: String?, bottom: String?, right: String?) { guard let topSectionInset = CGFloat(top), let leftSectionInset = CGFloat(left), let bottomSectionInset = CGFloat(bottom), let rightSectionInset = CGFloat(right) else { return nil } self = NSEdgeInsets(top: topSectionInset, left: leftSectionInset, bottom: bottomSectionInset, right: rightSectionInset) } }
9ade4170471a5a05670853a2c0e79cd9
29.65
57
0.522023
false
false
false
false
PANDA-Guide/PandaGuideApp
refs/heads/master
Carthage/Checkouts/SwiftTweaks/SwiftTweaks/UIColor+Tweaks.swift
gpl-3.0
1
// // UIColor+Tweaks.swift // SwiftTweaks // // Created by Bryan Clark on 11/16/15. // Copyright © 2015 Khan Academy. All rights reserved. // import UIKit // info via http://arstechnica.com/apple/2009/02/iphone-development-accessing-uicolor-components/ internal extension UIColor { /// Creates a UIColor with a given hex string (e.g. "#FF00FF") // NOTE: Would use a failable init (e.g. `UIColor(hexString: _)` but have to wait until Swift 2.2.1 https://github.com/Khan/SwiftTweaks/issues/38 internal static func colorWithHexString(_ hexString: String) -> UIColor? { // Strip whitespace, "#", "0x", and make uppercase let hexString = hexString .trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) .trimmingCharacters(in: NSCharacterSet(charactersIn: "#") as CharacterSet) .replacingOccurrences(of: "0x", with: "") .uppercased() // We should have 6 or 8 characters now. let hexStringLength = hexString.characters.count if (hexStringLength != 6) && (hexStringLength != 8) { return nil } // Break the string into its components let hexStringContainsAlpha = (hexStringLength == 8) let colorStrings: [String] = [ hexString[hexString.startIndex...hexString.characters.index(hexString.startIndex, offsetBy: 1)], hexString[hexString.characters.index(hexString.startIndex, offsetBy: 2)...hexString.characters.index(hexString.startIndex, offsetBy: 3)], hexString[hexString.characters.index(hexString.startIndex, offsetBy: 4)...hexString.characters.index(hexString.startIndex, offsetBy: 5)], hexStringContainsAlpha ? hexString[hexString.characters.index(hexString.startIndex, offsetBy: 6)...hexString.characters.index(hexString.startIndex, offsetBy: 7)] : "FF" ] // Convert string components into their CGFloat (r,g,b,a) components let colorFloats: [CGFloat] = colorStrings.map { var componentInt: CUnsignedInt = 0 Scanner(string: $0).scanHexInt32(&componentInt) return CGFloat(componentInt) / CGFloat(255.0) } return UIColor(red: colorFloats[0], green: colorFloats[1], blue: colorFloats[2], alpha: colorFloats[3]) } internal convenience init(hex: UInt32, alpha: CGFloat = 1) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat((hex & 0x0000FF)) / 255.0, alpha: alpha ) } internal var alphaValue: CGFloat { var white: CGFloat = 0 var alpha: CGFloat = 0 getWhite(&white, alpha: &alpha) return alpha } internal var hexString: String { assert(canProvideRGBComponents, "Must be an RGB color to use UIColor.hexValue") var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return String(format: "#%02x%02x%02x", arguments: [ Int(red * 255.0), Int(green * 255.0), Int(blue * 255.0) ]).uppercased() } private var canProvideRGBComponents: Bool { switch self.cgColor.colorSpace!.model { case .rgb, .monochrome: return true default: return false } } }
c1f48eb1693cb9bb0aef37a6f614488b
33.055556
171
0.706036
false
false
false
false
open-telemetry/opentelemetry-swift
refs/heads/main
Sources/OpenTelemetrySdk/Metrics/DoubleObserverMetricHandle.swift
apache-2.0
1
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetryApi class DoubleObserverMetricSdk: DoubleObserverMetric { public private(set) var observerHandles = [LabelSet: DoubleObserverMetricHandleSdk]() let metricName: String var callback: (DoubleObserverMetric) -> Void init(metricName: String, callback: @escaping (DoubleObserverMetric) -> Void) { self.metricName = metricName self.callback = callback } func observe(value: Double, labels: [String: String]) { observe(value: value, labelset: LabelSet(labels: labels)) } func observe(value: Double, labelset: LabelSet) { var boundInstrument = observerHandles[labelset] if boundInstrument == nil { boundInstrument = DoubleObserverMetricHandleSdk() observerHandles[labelset] = boundInstrument } boundInstrument?.observe(value: value) } func invokeCallback() { callback(self) } }
bfc904ca2e81a5e86230a95608d448ff
28.428571
89
0.683495
false
false
false
false
therealbnut/PeekSequence
refs/heads/master
PeekSequence.swift
mit
1
// // PeekSequence.swift // PeekSequence // // Created by Andrew Bennett on 26/01/2016. // Copyright © 2016 Andrew Bennett. All rights reserved. // public struct PeekSequence<T>: SequenceType { public typealias Generator = AnyGenerator<T> private var _sequence: AnySequence<T> private var _peek: T? public init<S: SequenceType where S.Generator.Element == T>( _ sequence: S ) { _sequence = AnySequence(sequence) _peek = nil } public func generate() -> AnyGenerator<T> { var peek = _peek, generator = _sequence.generate() return anyGenerator { let element = peek ?? generator.next() peek = nil return element } } public func underestimateCount() -> Int { return _peek == nil ? 0 : 1 } public mutating func peek() -> T? { if let element = _peek { return element } _peek = _sequence.generate().next() return _peek } } public func nonEmptySequence<S: SequenceType>(sequence: S) -> AnySequence<S.Generator.Element>? { var sequence = PeekSequence(sequence) if sequence.peek() != nil { return AnySequence(sequence) } else { return nil } }
3b635346ce38d6e3fd94ea592cb93350
24.346939
97
0.594203
false
false
false
false
AndreaMiotto/NASApp
refs/heads/master
Alamofire-master/Tests/TLSEvaluationTests.swift
apache-2.0
11
// // TLSEvaluationTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation import XCTest private struct TestCertificates { static let rootCA = TestCertificates.certificate(withFileName: "expired.badssl.com-root-ca") static let intermediateCA1 = TestCertificates.certificate(withFileName: "expired.badssl.com-intermediate-ca-1") static let intermediateCA2 = TestCertificates.certificate(withFileName: "expired.badssl.com-intermediate-ca-2") static let leaf = TestCertificates.certificate(withFileName: "expired.badssl.com-leaf") static func certificate(withFileName fileName: String) -> SecCertificate { class Locater {} let filePath = Bundle(for: Locater.self).path(forResource: fileName, ofType: "cer")! let data = try! Data(contentsOf: URL(fileURLWithPath: filePath)) let certificate = SecCertificateCreateWithData(nil, data as CFData)! return certificate } } // MARK: - private struct TestPublicKeys { static let rootCA = TestPublicKeys.publicKey(for: TestCertificates.rootCA) static let intermediateCA1 = TestPublicKeys.publicKey(for: TestCertificates.intermediateCA1) static let intermediateCA2 = TestPublicKeys.publicKey(for: TestCertificates.intermediateCA2) static let leaf = TestPublicKeys.publicKey(for: TestCertificates.leaf) static func publicKey(for certificate: SecCertificate) -> SecKey { let policy = SecPolicyCreateBasicX509() var trust: SecTrust? SecTrustCreateWithCertificates(certificate, policy, &trust) let publicKey = SecTrustCopyPublicKey(trust!)! return publicKey } } // MARK: - class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase { let urlString = "https://expired.badssl.com/" let host = "expired.badssl.com" var configuration: URLSessionConfiguration! // MARK: Setup and Teardown override func setUp() { super.setUp() configuration = URLSessionConfiguration.ephemeral } // MARK: Default Behavior Tests func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() { // Given weak var expectation = self.expectation(description: "\(urlString)") let manager = SessionManager(configuration: configuration) var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error) if let error = error as? URLError { XCTAssertEqual(error.code, .serverCertificateUntrusted) } else if let error = error as? NSError { XCTAssertEqual(error.domain, kCFErrorDomainCFNetwork as String) XCTAssertEqual(error.code, Int(CFNetworkErrors.cfErrorHTTPSProxyConnectionFailure.rawValue)) } else { XCTFail("error should be a URLError or NSError from CFNetwork") } } // MARK: Server Trust Policy - Perform Default Tests func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() { // Given let policies = [host: ServerTrustPolicy.performDefaultEvaluation(validateHost: true)] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } // MARK: Server Trust Policy - Certificate Pinning Tests func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() { // Given let certificates = [TestCertificates.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() { // Given let certificates = [ TestCertificates.leaf, TestCertificates.intermediateCA1, TestCertificates.intermediateCA2, TestCertificates.rootCA ] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() { // Given let certificates = [TestCertificates.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() { // Given let certificates = [TestCertificates.intermediateCA2] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() { // Given let certificates = [TestCertificates.rootCA] let policies: [String: ServerTrustPolicy] = [ host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then #if os(iOS) || os(macOS) if #available(iOS 10.1, macOS 10.12.0, *) { XCTAssertNotNil(error, "error should not be nil") } else { XCTAssertNil(error, "error should be nil") } #else XCTAssertNil(error, "error should be nil") #endif } // MARK: Server Trust Policy - Public Key Pinning Tests func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.leaf] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.intermediateCA2] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() { // Given let publicKeys = [TestPublicKeys.rootCA] let policies: [String: ServerTrustPolicy] = [ host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true) ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then #if os(iOS) || os(macOS) if #available(iOS 10.1, macOS 10.12.0, *) { XCTAssertNotNil(error, "error should not be nil") } else { XCTAssertNil(error, "error should be nil") } #else XCTAssertNil(error, "error should be nil") #endif } // MARK: Server Trust Policy - Disabling Evaluation Tests func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() { // Given let policies = [host: ServerTrustPolicy.disableEvaluation] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } // MARK: Server Trust Policy - Custom Evaluation Tests func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() { // Given let policies = [ host: ServerTrustPolicy.customEvaluation { _, _ in // Implement a custom evaluation routine here... return true } ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNil(error, "error should be nil") } func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() { // Given let policies = [ host: ServerTrustPolicy.customEvaluation { _, _ in // Implement a custom evaluation routine here... return false } ] let manager = SessionManager( configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies) ) weak var expectation = self.expectation(description: "\(urlString)") var error: Error? // When manager.request(urlString) .response { resp in error = resp.error expectation?.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(error, "error should not be nil") if let error = error as? URLError { XCTAssertEqual(error.code, .cancelled, "code should be cancelled") } else { XCTFail("error should be an URLError") } } }
836a24fc225495791bb41f90865ab008
33.05104
123
0.636429
false
true
false
false
inacioferrarini/glasgow
refs/heads/master
Glasgow/Classes/CoreData/Stack/CoreDataStack.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2017 Inácio Ferrarini // // 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 CoreData /** The `Core Data` stack. */ open class CoreDataStack { // MARK: - Properties /** Name of Core Data model file. */ open let modelFileName: String /** Name of Data Base file. */ open let databaseFileName: String /** Bundle where the model is located. */ open let bundle: Bundle? // MARK: - Initialization /** Convenience init. - parameter modelFileName: `Core Data` model file name. - parameter databaseFileName: `Core Data` database file name. */ public convenience init(modelFileName: String, databaseFileName: String) { self.init(modelFileName: modelFileName, databaseFileName: databaseFileName, bundle: nil) } /** Inits the `Core Data` stack. - parameter modelFileName: `Core Data` model file name. - parameter databaseFileName: `Core Data` database file name. - parameter bundle: Bundle where `Core Data` `model file` is located. */ public init(modelFileName: String, databaseFileName: String, bundle: Bundle?) { self.modelFileName = modelFileName self.databaseFileName = databaseFileName self.bundle = bundle } // MARK: - Lazy Helper Properties lazy var applicationDocumentsDirectory: URL? = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls.last }() lazy var managedObjectModel: NSManagedObjectModel? = { var modelURL = Bundle.main.url(forResource: self.modelFileName, withExtension: "momd") if let bundle = self.bundle { modelURL = bundle.url(forResource: self.modelFileName, withExtension: "momd") } guard let url = modelURL else { return nil } return NSManagedObjectModel(contentsOf: url) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { guard let model = self.managedObjectModel else { return nil } let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) guard let documentsDirectory = self.applicationDocumentsDirectory else { return nil } let url = documentsDirectory.appendingPathComponent("\(self.databaseFileName).sqlite") var failureReason = "There was an error creating or loading the application's saved data." let isRunningUnitTests = NSClassFromString("XCTest") != nil let storeType = isRunningUnitTests ? NSInMemoryStoreType : NSSQLiteStoreType _ = try? coordinator.addPersistentStore(ofType: storeType, configurationName: nil, at: url, options: nil) return coordinator }() /** The `Core Data` `ManagedObjectContext`. */ open lazy var managedObjectContext: NSManagedObjectContext? = { guard let coordinator = self.persistentStoreCoordinator else { return nil } var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support /** Saves the `Core Data` context, if there is changes to be saved. ### If you do not want to handle any exception that may happen, you can use: ### ```` try? coreDataStack.saveContext() ```` ### If you want to handle any exception that may happen, you can use: ### ```` do { try coreDataStack.saveContext() } catch let error as NSError { print("Error: \(error)") } ```` */ open func saveContext() throws { guard let managedObjectContext = self.managedObjectContext else { return } if managedObjectContext.hasChanges { try managedObjectContext.save() } } }
ee1eebec947fec2997a179c6f0701483
33.636986
113
0.671544
false
false
false
false
CosmicMind/MaterialKit
refs/heads/master
Sources/iOS/Device.swift
bsd-3-clause
1
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(DeviceModel) public enum DeviceModel: Int { case iPodTouch5 case iPodTouch6 case iPhone4s case iPhone5 case iPhone5c case iPhone5s case iPhone6 case iPhone6Plus case iPhone6s case iPhone6sPlus case iPhone7 case iPhone7Plus case iPhone8 case iPhone8Plus case iPhoneX case iPhoneSE case iPad2 case iPad3 case iPad4 case iPadAir case iPadAir2 case iPadMini case iPadMini2 case iPadMini3 case iPadMini4 case iPadPro case iPadProLarge case iPad5 case iPadPro2 case iPadProLarge2 case iPad6 case simulator case unknown } public struct Device { /// Gets the Device identifier String. public static var identifier: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { (identifier, element) in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return identifier } /// Gets the model name for the device. public static var model: DeviceModel { switch identifier { case "iPod5,1": return .iPodTouch5 case "iPod7,1": return .iPodTouch6 case "iPhone4,1": return .iPhone4s case "iPhone5,1", "iPhone5,2": return .iPhone5 case "iPhone5,3", "iPhone5,4": return .iPhone5c case "iPhone6,1", "iPhone6,2": return .iPhone5s case "iPhone7,2": return .iPhone6 case "iPhone7,1": return .iPhone6Plus case "iPhone8,1": return .iPhone6s case "iPhone8,2": return .iPhone6sPlus case "iPhone8,3", "iPhone8,4": return .iPhoneSE case "iPhone9,1", "iPhone9,3": return .iPhone7 case "iPhone9,2", "iPhone9,4": return .iPhone7Plus case "iPhone10,1", "iPhone10,4": return .iPhone8 case "iPhone10,2", "iPhone10,5": return .iPhone8Plus case "iPhone10,3","iPhone10,6": return .iPhoneX case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return .iPad2 case "iPad3,1", "iPad3,2", "iPad3,3": return .iPad3 case "iPad3,4", "iPad3,5", "iPad3,6": return .iPad4 case "iPad4,1", "iPad4,2", "iPad4,3": return .iPadAir case "iPad5,3", "iPad5,4": return .iPadAir2 case "iPad2,5", "iPad2,6", "iPad2,7": return .iPadMini case "iPad4,4", "iPad4,5", "iPad4,6": return .iPadMini2 case "iPad4,7", "iPad4,8", "iPad4,9": return .iPadMini3 case "iPad5,1", "iPad5,2": return .iPadMini4 case "iPad6,3", "iPad6,4": return .iPadPro case "iPad6,7", "iPad6,8": return .iPadProLarge case "iPad6,11", "iPad6,12": return .iPad5 case "iPad7,3", "iPad7,4": return .iPadPro2 case "iPad7,1", "iPad7,2": return .iPadProLarge2 case "iPad7,5", "iPad7,6": return .iPad6 case "i386", "x86_64": return .simulator default: return .unknown } } /// Retrieves the current device type. public static var userInterfaceIdiom: UIUserInterfaceIdiom { return UIDevice.current.userInterfaceIdiom } } public func ==(lhs: DeviceModel, rhs: DeviceModel) -> Bool { return lhs.rawValue == rhs.rawValue } public func !=(lhs: DeviceModel, rhs: DeviceModel) -> Bool { return lhs.rawValue != rhs.rawValue }
7bbe0bb281bec0ce7db97bbc4497e849
39.42446
88
0.607048
false
false
false
false
mariedm/PermissionPopup
refs/heads/master
PermissionPopup/PermissionPopup.swift
mit
1
// // PermissionPopup.swift // Stwories // // Created by Marie Denis-Massé on 11/11/2016. // Copyright © 2016 Many. All rights reserved. // import UIKit import AVFoundation import Photos import Contacts /*** DELEGATES ***/ protocol DidAskCameraDelegate{ func didAskForCamera(_ granted:Bool) } protocol DidAskMicDelegate{ func didAskForMic(_ granted:Bool) } protocol DidAskLibraryDelegate{ func didAskForLibrary(_ granted:Bool) } protocol DidAskContactsDelegate{ func didAskForContacts(_ granted:Bool) } protocol DidAskNotificationsDelegate{ func didAskForNotifications(_ granted:Bool) } /*** VIEW CONTROLLER ***/ class PermissionPopup:UIViewController{ //outlets @IBOutlet weak var mainImage: UIImageView! @IBOutlet weak var mainLabel: UILabel! @IBOutlet weak var noButton: UIButton! @IBOutlet weak var yesButton: UIButton! var popupType=PopupType.camera var micDelegate:DidAskMicDelegate? var camDelegate:DidAskCameraDelegate? var libraryDelegate:DidAskLibraryDelegate? var contactsDelegate:DidAskContactsDelegate? var notifDelegate:DidAskNotificationsDelegate? /*** INIT ***/ class func ofType(_ type:PopupType, from viewController:UIViewController)->PermissionPopup{ let popup=UINib(nibName: "PermissionPopup", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! PermissionPopup popup.popupType=type return popup } override func viewDidLoad(){ super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { initUi() } func initUi(){ mainLabel.text=popupType.mainLabel mainImage.image=popupType.mainImage noButton.setTitle(popupType.no, for: .normal) yesButton.setTitle(popupType.yes, for: .normal) setNeedsStatusBarAppearanceUpdate() } /*** SAID YES ***/ @IBAction func saidYes(_ sender: Any){ //ask autho switch popupType{ case .camera: askForCamera() case .mic: askForMic() case .contacts: askForContacts() case .libraryPickup, .librarySave: askForLibrary() case .notifications: askForNotifications() } } func askForCamera(){ AVCaptureDevice.requestAccess(for: AVMediaType.video){granted in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ weak.camDelegate?.didAskForCamera(granted) } } } } func askForContacts(){ CNContactStore().requestAccess(for: .contacts){granted, error in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ weak.contactsDelegate?.didAskForContacts(granted) } } } } func askForLibrary(){ PHPhotoLibrary.requestAuthorization{status in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ if status==PHAuthorizationStatus.authorized{ weak.libraryDelegate?.didAskForLibrary(true) }else{ weak.libraryDelegate?.didAskForLibrary(false) } } } } } func askForMic(){ AVAudioSession.sharedInstance().requestRecordPermission(){granted in DispatchQueue.main.async{[weak self] in guard let weak=self else{return} weak.close{ weak.micDelegate?.didAskForMic(granted) } } } } func askForNotifications(){ //print("ask_notifs") //notif_api.setup_notifications() close{} } /*** SAID NO ***/ @IBAction func saidNo(_ sender: Any){ switch popupType{ case .camera: close{ self.camDelegate?.didAskForCamera(false) } case .contacts: close{ self.contactsDelegate?.didAskForContacts(false) } case .libraryPickup, .librarySave: close{ self.libraryDelegate?.didAskForLibrary(false) } case .mic: close{ self.micDelegate?.didAskForMic(false) } case .notifications: close{ self.notifDelegate?.didAskForNotifications(false) } } } /*** CLOSE ***/ func close(completion:@escaping ()->()){ UIView.animate(withDuration: 0.2, animations: { self.view.alpha=0 }, completion: {_ in self.dismiss(animated: false, completion: completion) }) } override var prefersStatusBarHidden:Bool{ return true } } /*** AUTHORIZATION TYPES ***/ struct UIConfig{ var main_label:String var image:UIImage var no:String var yes:String } enum PopupType:String{ case camera="camera", mic="mic", libraryPickup="libraryPickup", librarySave="librarySave", contacts="contacts", notifications="notifications" var mainLabel:String{ switch self{ case .camera: return "Activate your camera to take a picture." case .mic: return "Activate your mic to record your voice." case .libraryPickup: return "Give access to your library to pick a nice pic." case .librarySave: return "Give access to your library so that we can save images." case .contacts: return "Share your contacts to invite them." case .notifications: return "Receive notifications to get the best experience." } } var mainImage:UIImage{ switch self{ case .camera: return UIImage(named: "popupCamera")! case .mic: return UIImage(named: "popupMic")! case .libraryPickup, .librarySave: return UIImage(named: "popupLibrary")! case .contacts: return UIImage(named: "popupContacts")! case .notifications: return UIImage(named: "popupNotifications")! } } var no:String{ switch self{ case .camera: return "I'm too shy" case .mic: return "Nope" case .libraryPickup, .librarySave: return "No thanks" case .contacts: return "I stay alone" case .notifications: return "Nevermind" } } var yes:String{ switch self{ case .camera: return "Let's do this" case .mic: return "Alright" case .libraryPickup, .librarySave: return "Lets' go" case .contacts: return "Lets' go" case .notifications: return "Yes, sure!" } } }
6b878a292e74ca6993a078180be58c71
29.087336
145
0.589695
false
false
false
false
lynnleelhl/InfinitePageView
refs/heads/master
InfinitePageView/ViewController.swift
mit
1
// // ViewController.swift // InfinitePageView // // Created by hli on 13/02/2017. // Copyright © 2017 hli. All rights reserved. // import UIKit class CustomView: UIInfinitePageView, UIInfinitePageViewDelegate { override init(frame: CGRect) { super.init(frame: frame) } convenience init() { self.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 250)) self.delegate = self //self.isAutoScroll = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func numberOfViews() -> Int { return 3 } func InfinitePageView(viewForIndexAt index: Int) -> UIView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = UIImage(named: "\(index).jpg") return imageView } } class ViewController: UIViewController, UIInfinitePageViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let customView = CustomView() self.view.addSubview(customView) customView.reloadData() let customVerticalView = UIInfinitePageView() customVerticalView.delegate = self customVerticalView.scrollDirection = .vertical customVerticalView.duringTime = 3.0 self.view.addSubview(customVerticalView) customVerticalView.snp.makeConstraints { (make) in make.center.equalToSuperview() make.height.equalTo(32) make.width.equalTo(320) } customVerticalView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // returns the number of pages you have func numberOfViews() -> Int { return 3 } // returns every page in your infinite page view func InfinitePageView(viewForIndexAt index: Int) -> UIView { let label = UILabel() label.textAlignment = .center label.text = "Notice: This is vertical page \(index)" return label } }
5670bd36087b894002547379b19f938b
25.701149
92
0.619027
false
false
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/AssistantV2/Models/RuntimeResponseGenericRuntimeResponseTypeVideo.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2022. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import IBMSwiftSDKCore /** RuntimeResponseGenericRuntimeResponseTypeVideo. Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeVideo: RuntimeResponseGeneric */ public struct RuntimeResponseGenericRuntimeResponseTypeVideo: Codable, Equatable { /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** The `https:` URL of the video. */ public var source: String /** The title or introductory text to show before the response. */ public var title: String? /** The description to show with the the response. */ public var description: String? /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? /** For internal use only. */ public var channelOptions: [String: JSON]? /** Descriptive text that can be used for screen readers or other situations where the video cannot be seen. */ public var altText: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case source = "source" case title = "title" case description = "description" case channels = "channels" case channelOptions = "channel_options" case altText = "alt_text" } }
7f3e130bf486144c2068d8267c561daf
29.526316
114
0.693966
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Camera/Config/CameraConfiguration.swift
mit
1
// // CameraConfiguration.swift // HXPHPicker // // Created by Slience on 2021/8/30. // import UIKit import AVFoundation // MARK: 相机配置类 public class CameraConfiguration: BaseConfiguration { /// 相机类型 public var cameraType: CameraController.CameraType = .normal /// 相机分辨率 public var sessionPreset: Preset = .hd1280x720 /// 摄像头默认位置 public var position: DevicePosition = .back /// 默认闪光灯模式 public var flashMode: AVCaptureDevice.FlashMode = .auto /// 录制视频时设置的 `AVVideoCodecType` /// iPhone7 以下为 `.h264` public var videoCodecType: AVVideoCodecType = .h264 /// 视频最大录制时长 /// takePhotoMode = .click 支持不限制最大时长 (0 - 不限制) /// takePhotoMode = .press 最小 1 public var videoMaximumDuration: TimeInterval = 60 /// 视频最短录制时长 public var videoMinimumDuration: TimeInterval = 1 /// 拍照方式 public var takePhotoMode: TakePhotoMode = .press /// 主题色 public var tintColor: UIColor = .systemTintColor { didSet { #if HXPICKER_ENABLE_EDITOR setupEditorColor() #endif } } /// 摄像头最大缩放比例 public var videoMaxZoomScale: CGFloat = 6 /// 默认滤镜对应滤镜数组的下标,为 -1 默认不加滤镜 public var defaultFilterIndex: Int = -1 /// 切换滤镜显示名称 public var changeFilterShowName: Bool = true /// 拍照时的滤镜数组,请与 videoFilters 效果保持一致 /// 左滑/右滑切换滤镜 public lazy var photoFilters: [CameraFilter] = [ InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] /// 录制视频的滤镜数组,请与 photoFilters 效果保持一致 /// 左滑/右滑切换滤镜 public lazy var videoFilters: [CameraFilter] = [ InstantFilter(), Apply1977Filter(), ToasterFilter(), TransferFilter() ] #if HXPICKER_ENABLE_EDITOR /// 允许编辑 /// true: 拍摄完成后会跳转到编辑界面 public var allowsEditing: Bool = true /// 照片编辑器配置 public lazy var photoEditor: PhotoEditorConfiguration = .init() /// 视频编辑器配置 public lazy var videoEditor: VideoEditorConfiguration = .init() #endif /// 允许启动定位 public var allowLocation: Bool = true public override init() { super.init() /// shouldAutorotate 能够旋转 /// supportedInterfaceOrientations 支持的方向 /// 隐藏状态栏 prefersStatusBarHidden = true appearanceStyle = .normal #if HXPICKER_ENABLE_EDITOR photoEditor.languageType = languageType videoEditor.languageType = languageType photoEditor.indicatorType = indicatorType videoEditor.indicatorType = indicatorType photoEditor.appearanceStyle = appearanceStyle videoEditor.appearanceStyle = appearanceStyle #endif } #if HXPICKER_ENABLE_EDITOR public override var languageType: LanguageType { didSet { photoEditor.languageType = languageType videoEditor.languageType = languageType } } public override var indicatorType: BaseConfiguration.IndicatorType { didSet { photoEditor.indicatorType = indicatorType videoEditor.indicatorType = indicatorType } } public override var appearanceStyle: AppearanceStyle { didSet { photoEditor.appearanceStyle = appearanceStyle videoEditor.appearanceStyle = appearanceStyle } } #endif } extension CameraConfiguration { public enum DevicePosition { /// 后置 case back /// 前置 case front } public enum TakePhotoMode { /// 长按 case press /// 点击(支持不限制最大时长) case click } public enum Preset { case vga640x480 case iFrame960x540 case hd1280x720 case hd1920x1080 case hd4K3840x2160 var system: AVCaptureSession.Preset { switch self { case .vga640x480: return .vga640x480 case .iFrame960x540: return .iFrame960x540 case .hd1280x720: return .hd1280x720 case .hd1920x1080: return .hd1920x1080 case .hd4K3840x2160: return .hd4K3840x2160 } } var size: CGSize { switch self { case .vga640x480: return CGSize(width: 480, height: 640) case .iFrame960x540: return CGSize(width: 540, height: 960) case .hd1280x720: return CGSize(width: 720, height: 1280) case .hd1920x1080: return CGSize(width: 1080, height: 1920) case .hd4K3840x2160: return CGSize(width: 2160, height: 3840) } } } #if HXPICKER_ENABLE_EDITOR fileprivate func setupEditorColor() { videoEditor.cropConfirmView.finishButtonBackgroundColor = tintColor videoEditor.cropConfirmView.finishButtonDarkBackgroundColor = tintColor videoEditor.cropSize.aspectRatioSelectedColor = tintColor videoEditor.toolView.finishButtonBackgroundColor = tintColor videoEditor.toolView.finishButtonDarkBackgroundColor = tintColor videoEditor.toolView.toolSelectedColor = tintColor videoEditor.toolView.musicSelectedColor = tintColor videoEditor.music.tintColor = tintColor videoEditor.text.tintColor = tintColor videoEditor.filter = .init( infos: videoEditor.filter.infos, selectedColor: tintColor ) photoEditor.toolView.toolSelectedColor = tintColor photoEditor.toolView.finishButtonBackgroundColor = tintColor photoEditor.toolView.finishButtonDarkBackgroundColor = tintColor photoEditor.cropConfimView.finishButtonBackgroundColor = tintColor photoEditor.cropConfimView.finishButtonDarkBackgroundColor = tintColor photoEditor.cropping.aspectRatioSelectedColor = tintColor photoEditor.filter = .init( infos: photoEditor.filter.infos, selectedColor: tintColor ) photoEditor.text.tintColor = tintColor } #endif }
22d7d006899754aa5fe07624b0d024c4
28.393365
79
0.618671
false
false
false
false
atrick/swift
refs/heads/main
test/Generics/unify_protocol_composition.swift
apache-2.0
3
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s class C<T> {} protocol P0 {} protocol P1 { associatedtype T where T == C<U> & P0 associatedtype U } protocol P2 { associatedtype T where T == C<Int> & P0 } // CHECK-LABEL: .P3@ // CHECK-NEXT: Requirement signature: <Self where Self.[P3]T : P1, Self.[P3]T : P2> protocol P3 { associatedtype T : P1 & P2 where T.U == Int }
4932b883b373d479036a20bae5601e52
22.5
135
0.671642
false
false
false
false
voloshynslavik/MVx-Patterns-In-Swift
refs/heads/master
MVX Patterns In Swift/Patterns/MVVM/MVVMViewController.swift
mit
1
// // MVVMViewController.swift // MVX Patterns In Swift // // Created by Yaroslav Voloshyn on 17/07/2017. // import UIKit private let cellId = "500px_image_cell" final class MVVMViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! fileprivate var cachedImages: [String: UIImage] = [:] var viewModel: ViewModel! override func viewDidLoad() { super.viewDidLoad() collectionView.register(UINib(nibName: "ImageCell", bundle: nil), forCellWithReuseIdentifier: cellId) viewModel.loadMoreItems() } } // MARK: - UICollectionViewDataSource extension MVVMViewController: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.photosCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? ImageCell else { return UICollectionViewCell() } cell.nameLabel.text = viewModel.getPhotoAuthor(for: indexPath.row) cell.imageView.image = getImage(for: indexPath) return cell } private func getImage(for indexPath: IndexPath) -> UIImage? { let size = collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: indexPath) guard let imageData = viewModel.getPhotoData(for: indexPath.row, width: Int(size.width), height: Int(size.height)) else { return nil } return UIImage(data: imageData) } } // MARK: - UICollectionViewDelegateFlowLayout extension MVVMViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let countOfCollumns: CGFloat = 3 let widthCollectionView = collectionView.frame.width let widthCell = (widthCollectionView - (countOfCollumns - 1.0))/countOfCollumns return CGSize(width: widthCell, height: widthCell) } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { viewModel.stopLoadPhoto(for: indexPath.row, width: Int(cell.frame.width), height: Int(cell.frame.height)) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if (indexPath.row + 1) == viewModel.photosCount { viewModel.loadMoreItems() } } } // MARK: - ViewModelDelegate extension MVVMViewController: ViewModelDelegate { func didLoadingStateChanged(in viewModel: ViewModel, from oldState: Bool, to newState:Bool) { UIApplication.shared.isNetworkActivityIndicatorVisible = newState } func didUpdatedData(in viewModel: ViewModel) { collectionView.reloadData() } func didDownloadPhoto(in viewMode: ViewModel, with index: Int) { let indexPath = IndexPath(row: index, section: 0) collectionView.reloadItems(at: [indexPath]) } }
48d301f2586fa99d2834584799966cd9
33.904255
160
0.721122
false
false
false
false
wwu-pi/md2-framework
refs/heads/master
de.wwu.md2.framework/res/resources/ios/lib/controller/validator/MD2StringRangeValidator.swift
apache-2.0
1
// // MD2StringRangeValidator.swift // md2-ios-library // // Created by Christoph Rieger on 23.07.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /** Validator to check for a given string range. */ class MD2StringRangeValidator: MD2Validator { /// Unique identification string. let identifier: MD2String /// Custom message to display. var message: (() -> MD2String)? /// Default message to display. var defaultMessage: MD2String { get { return MD2String("This value must be between \(minLength) and \(maxLength) characters long!") } } /// The minimum allowed length. var minLength: MD2Integer /// The maximum allowed length. var maxLength: MD2Integer /** Default initializer. :param: identifier The unique validator identifier. :param: message Closure of the custom method to display. :param: minLength The minimum length of a valid string. :param: maxLength The maximum langth of a valid string. */ init(identifier: MD2String, message: (() -> MD2String)?, minLength: MD2Integer, maxLength: MD2Integer) { self.identifier = identifier self.message = message self.minLength = minLength self.maxLength = maxLength } /** Validate a value. :param: value The value to check. :return: Validation result */ func isValid(value: MD2Type) -> Bool { if !(value is MD2String) || !((value as! MD2String).isSet()) || !(maxLength.isSet()) { return false } // Set default minimum length if minLength.isSet() == false { minLength.platformValue = 0 } let stringValue = (value as! MD2String).platformValue! if count(stringValue) >= minLength.platformValue! && count(stringValue) <= maxLength.platformValue! { return true } else { return false } } /** Return the message to display on wrong validation. Use custom method if set or else use default message. */ func getMessage() -> MD2String { if let _ = message { return message!() } else { return defaultMessage } } }
3af24d8ebf5586e828e32be039e0454f
26.011236
108
0.573034
false
false
false
false
Pluto-tv/RxSwift
refs/heads/dev
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxDataSourceStarterKit/Changeset.swift
apache-2.0
20
// // Changeset.swift // RxCocoa // // Created by Krunoslav Zaher on 5/30/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import CoreData #if !RX_NO_MODULE import RxSwift import RxCocoa #endif struct ItemPath : CustomStringConvertible { let sectionIndex: Int let itemIndex: Int var description : String { get { return "(\(sectionIndex), \(itemIndex))" } } } public struct Changeset<S: SectionModelType> : CustomStringConvertible { typealias I = S.Item var finalSections: [S] = [] var insertedSections: [Int] = [] var deletedSections: [Int] = [] var movedSections: [(from: Int, to: Int)] = [] var updatedSections: [Int] = [] var insertedItems: [ItemPath] = [] var deletedItems: [ItemPath] = [] var movedItems: [(from: ItemPath, to: ItemPath)] = [] var updatedItems: [ItemPath] = [] public static func initialValue(sections: [S]) -> Changeset<S> { var initialValue = Changeset<S>() initialValue.insertedSections = Array(0 ..< sections.count) initialValue.finalSections = sections return initialValue } public var description : String { get { let serializedSections = "[\n" + finalSections.map { "\($0)" }.joinWithSeparator(",\n") + "\n]\n" return " >> Final sections" + " \n\(serializedSections)" + (insertedSections.count > 0 || deletedSections.count > 0 || movedSections.count > 0 || updatedSections.count > 0 ? "\nSections:" : "") + (insertedSections.count > 0 ? "\ninsertedSections:\n\t\(insertedSections)" : "") + (deletedSections.count > 0 ? "\ndeletedSections:\n\t\(deletedSections)" : "") + (movedSections.count > 0 ? "\nmovedSections:\n\t\(movedSections)" : "") + (updatedSections.count > 0 ? "\nupdatesSections:\n\t\(updatedSections)" : "") + (insertedItems.count > 0 || deletedItems.count > 0 || movedItems.count > 0 || updatedItems.count > 0 ? "\nItems:" : "") + (insertedItems.count > 0 ? "\ninsertedItems:\n\t\(insertedItems)" : "") + (deletedItems.count > 0 ? "\ndeletedItems:\n\t\(deletedItems)" : "") + (movedItems.count > 0 ? "\nmovedItems:\n\t\(movedItems)" : "") + (updatedItems.count > 0 ? "\nupdatedItems:\n\t\(updatedItems)" : "") } } }
63b7b9e48125180bb33241b33fc6c3b7
35.651515
148
0.592807
false
false
false
false
emenegro/space-cells-ios
refs/heads/master
SpaceCells/Sources/Utils/Collectionable.swift
mit
1
import Foundation typealias Section = Int protocol CollectionableViewModelCellConfigurable { associatedtype CollectionableViewModelType: CollectionableViewModel func configure(viewModel: CollectionableViewModelType?) } protocol CollectionableViewModel { func onRowSelected() } protocol Collectionable { associatedtype Item: CollectionableViewModel func items() -> [Section: [Item]]? func numberOfSections() -> Section func numberOfRows(inSection section: Section) -> Int func viewModelForRowAtIndexPath<Item>(indexPath: IndexPath) -> Item? func rowSelectedAtIndexPath(indexPath: IndexPath) } extension Collectionable { func numberOfSections() -> Section { return items()?.count ?? 0 } func numberOfRows(inSection section: Section) -> Int { return items()?[section]?.count ?? 0 } func viewModelForRowAtIndexPath<Item>(indexPath: IndexPath) -> Item? { let sectionItems = items()?[indexPath.section] return sectionItems?[indexPath.row] as? Item } func rowSelectedAtIndexPath(indexPath: IndexPath) { if let viewModel: Item = viewModelForRowAtIndexPath(indexPath: indexPath) { viewModel.onRowSelected() } } } class AnyCollectionable<Item>: Collectionable where Item: CollectionableViewModel { private let _items: (() -> [Section: [Item]]?) private let _numberOfSections: (() -> Section) private let _numberOfRows: ((_ section: Section) -> Int) private let _viewModelForRowAtIndexPath: ((_ indexPath: IndexPath) -> Item?) private let _rowSelectedAtIndexPath: ((_ indexPath: IndexPath) -> Void) init<C: Collectionable>(_ collectionable: C) where C.Item == Item { _items = collectionable.items _numberOfSections = collectionable.numberOfSections _numberOfRows = collectionable.numberOfRows _viewModelForRowAtIndexPath = collectionable.viewModelForRowAtIndexPath _rowSelectedAtIndexPath = collectionable.rowSelectedAtIndexPath } func items() -> [Section: [Item]]? { return _items() } func numberOfSections() -> Section { return _numberOfSections() } func numberOfRows(inSection section: Section) -> Int { return _numberOfRows(section) } func viewModelForRowAtIndexPath<Item>(indexPath: IndexPath) -> Item? { return _viewModelForRowAtIndexPath(indexPath) as? Item } func rowSelectedAtIndexPath(indexPath: IndexPath) { _rowSelectedAtIndexPath(indexPath) } }
652dd4444e2ab89d52f34fde617eacfc
30.91358
83
0.685106
false
false
false
false
nodekit-io/nodekit-darwin
refs/heads/master
src/nodekit/NKCore/NKCSocket/NKC_SocketTCP.swift
apache-2.0
1
/* * nodekit.io * * Copyright (c) 2016-7 OffGrid Networks. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /* * Creates _tcp javascript value that inherits from EventEmitter * _tcp.on("connection", function(_tcp)) * _tcp.on("afterConnect", function()) * _tcp.on('data', function(chunk)) * _tcp.on('end') * _tcp.writeBytes(data) * _tcp.fd returns {fd} * _tcp.remoteAddress returns {String addr, int port} * _tcp.localAddress returns {String addr, int port} * _tcp.bind(String addr, int port) * _tcp.listen(int backlog) * _tcp.connect(String addr, int port) * _tcp.close() * */ class NKC_SocketTCP: NSObject, NKScriptExport { // NKScripting class func attachTo(context: NKScriptContext) { context.loadPlugin(NKC_SocketTCP.self, namespace: "io.nodekit.platform.TCP", options: [String:AnyObject]()) } class func rewriteGeneratedStub(stub: String, forKey: String) -> String { switch (forKey) { case ".global": return NKStorage.getPluginWithStub(stub, "lib-core.nkar/lib-core/platform/tcp.js", NKC_SocketTCP.self) default: return stub } } private static let exclusion: Set<String> = { var methods = NKInstanceMethods(forProtocol: NKC_SwiftSocketProtocol.self) return Set<String>(methods.union([ ]).map({selector in return selector.description })) }() class func isExcludedFromScript(selector: String) -> Bool { return exclusion.contains(selector) } class func rewriteScriptNameForKey(name: String) -> String? { return (name == "initWithOptions:" ? "" : nil) } // local variables and init private let connections: NSMutableSet = NSMutableSet() private var _socket: NKC_SwiftSocket? private var _server: NKC_SocketTCP? override init() { self._socket = NKC_SwiftSocket(domain: NKC_DomainAddressFamily.INET, type: NKC_SwiftSocketType.Stream, proto: NKC_CommunicationProtocol.TCP) super.init() self._socket!.setDelegate(self, delegateQueue: NKScriptContextFactory.defaultQueue ) } init(options: AnyObject) { self._socket = NKC_SwiftSocket(domain: NKC_DomainAddressFamily.INET, type: NKC_SwiftSocketType.Stream, proto: NKC_CommunicationProtocol.TCP) super.init() self._socket!.setDelegate(self, delegateQueue: NKScriptContextFactory.defaultQueue ) } init(socket: NKC_SwiftSocket, server: NKC_SocketTCP?) { self._socket = socket self._server = server super.init() } // public methods func bindSync(address: String, port: Int) -> Int { do { try self._socket!.bind(host: address, port: Int32(port)) } catch let error as NKC_Error { print("!Socket Bind Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") return error.associated.value as? Int ?? 500 } catch { fatalError() } return 0 } func connect(address: String, port: Int) -> Void { do { try self._socket!.connect(host: address, port: Int32(port)) } catch let error as NKC_Error { print("!Socket Connect Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func listen(backlog: Int) -> Void { do { try self._socket!.listen(Int32(backlog)) } catch let error as NKC_Error { print("!Socket Connect Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func fdSync() -> Int { return Int(self._socket!.fd) } func remoteAddressSync() -> Dictionary<String, AnyObject> { let address: String = self._socket?.connectedHost ?? "" let port: Int = Int(self._socket?.connectedPort ?? 0) return ["address": address, "port": port] } func localAddressSync() -> Dictionary<String, AnyObject> { let address: String = self._socket!.localHost ?? "" let port: Int = Int(self._socket!.localPort ?? 0) return ["address": address, "port": port] } func writeString(string: String) -> Void { guard let data = NSData(base64EncodedString: string, options: NSDataBase64DecodingOptions(rawValue: 0)) else {return;} do { try self._socket?.write(data) } catch let error as NKC_Error { print("!Socket Send Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func close() -> Void { if (self._socket !== nil) { do { try self._socket!.close() } catch let error as NKC_Error { print("!Socket Close Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } if (self._server !== nil) { self._server!.close() } self._socket = nil self._server = nil } } // DELEGATE METHODS FOR NKC_SwiftSocket extension NKC_SocketTCP: NKC_SwiftSocketProtocol { func socket(socket: NKC_SwiftSocket, didAcceptNewSocket newSocket: NKC_SwiftSocket) { let socketConnection = NKC_SocketTCP(socket: newSocket, server: self) connections.addObject(socketConnection) newSocket.setDelegate(socketConnection, delegateQueue: NKScriptContextFactory.defaultQueue ) self.emitConnection(socketConnection) do { try newSocket.beginReceiving(tag: 1) } catch let error as NKC_Error { print("!Socket Accept Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func socket(socket: NKC_SwiftSocket, didConnectToHost host: String!, port: Int32) { self.emitAfterConnect(host, port: Int(port)) do { try socket.beginReceiving(tag: 1) } catch let error as NKC_Error { print("!Socket Connect Receive Error: \(error.associated.value) \(error.associated.label) \(error.associated.posix)") } catch { fatalError() } } func socket(socket: NKC_SwiftSocket, didReceiveData data: NSData!, withTag tag: Int) { self.emitData(data) } func socket(socket: NKC_SwiftSocket, didReceiveData data: NSData!, sender host: String?, port: Int32) { self.emitData(data) } func socket(socket: NKC_SwiftSocket, didDisconnectWithError err: NSError) { self._socket = nil self.emitEnd() if (self._server != nil) { self._server!.connectionDidClose(self) } self._server = nil } // private methods private func connectionDidClose(socketConnection: NKC_SocketTCP) { connections.removeObject(socketConnection) } private func emitConnection(tcp: NKC_SocketTCP) -> Void { self.NKscriptObject?.invokeMethod("emit", withArguments: ["connection", tcp], completionHandler: nil) } private func emitAfterConnect(host: String, port: Int) { self.NKscriptObject?.invokeMethod("emit", withArguments:["afterConnect", host, port], completionHandler: nil) } private func emitData(data: NSData!) { let str: NSString! = data.base64EncodedStringWithOptions([]) self.NKscriptObject?.invokeMethod("emit", withArguments: ["data", str], completionHandler: nil) } private func emitEnd() { self.NKscriptObject?.invokeMethod("emit", withArguments: ["end", ""], completionHandler: nil) } }
9e81a421c9d35df094ce12657254f841
33.312253
148
0.604884
false
false
false
false
gregomni/swift
refs/heads/main
test/SILGen/objc_async.swift
apache-2.0
2
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -I %S/Inputs/custom-modules -disable-availability-checking %s -verify | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-cpu %s // REQUIRES: concurrency // REQUIRES: objc_interop import Foundation import ObjCConcurrency // CHECK-LABEL: sil {{.*}}@${{.*}}14testSlowServer func testSlowServer(slowServer: SlowServer) async throws { // CHECK: [[RESUME_BUF:%.*]] = alloc_stack $Int // CHECK: [[STRINGINIT:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : // CHECK: [[ARG:%.*]] = apply [[STRINGINIT]] // CHECK: [[METHOD:%.*]] = objc_method {{.*}} $@convention(objc_method) (NSString, @convention(block) (Int) -> (), SlowServer) -> () // CHECK: [[CONT:%.*]] = get_async_continuation_addr Int, [[RESUME_BUF]] // CHECK: [[WRAPPED:%.*]] = struct $UnsafeContinuation<Int, Never> ([[CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage UnsafeContinuation<Int, Never> // CHECK: [[CONT_SLOT:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK: store [[WRAPPED]] to [trivial] [[CONT_SLOT]] // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[INT_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<Int, Never>, Int) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] {{.*}}, invoke [[BLOCK_IMPL]] // CHECK: apply [[METHOD]]([[ARG]], [[BLOCK]], %0) // CHECK: [[COPY:%.*]] = copy_value [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: await_async_continuation [[CONT]] {{.*}}, resume [[RESUME:bb[0-9]+]] // CHECK: [[RESUME]]: // CHECK: [[RESULT:%.*]] = load [trivial] [[RESUME_BUF]] // CHECK: fix_lifetime [[COPY]] // CHECK: destroy_value [[COPY]] // CHECK: dealloc_stack [[RESUME_BUF]] let _: Int = await slowServer.doSomethingSlow("mail") let _: Int = await slowServer.doSomethingSlowNullably("mail") // CHECK: [[RESUME_BUF:%.*]] = alloc_stack $String // CHECK: [[METHOD:%.*]] = objc_method {{.*}} $@convention(objc_method) (@convention(block) (Optional<NSString>, Optional<NSError>) -> (), SlowServer) -> () // CHECK: [[CONT:%.*]] = get_async_continuation_addr [throws] String, [[RESUME_BUF]] // CHECK: [[WRAPPED:%.*]] = struct $UnsafeContinuation<String, Error> ([[CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage UnsafeContinuation<String, Error> // CHECK: [[CONT_SLOT:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK: store [[WRAPPED]] to [trivial] [[CONT_SLOT]] // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[STRING_COMPLETION_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<String, Error>, Optional<NSString>, Optional<NSError>) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] {{.*}}, invoke [[BLOCK_IMPL]] // CHECK: apply [[METHOD]]([[BLOCK]], %0) // CHECK: await_async_continuation [[CONT]] {{.*}}, resume [[RESUME:bb[0-9]+]], error [[ERROR:bb[0-9]+]] // CHECK: [[RESUME]]: // CHECK: [[RESULT:%.*]] = load [take] [[RESUME_BUF]] // CHECK: destroy_value [[RESULT]] // CHECK: dealloc_stack [[RESUME_BUF]] let _: String = try await slowServer.findAnswer() // CHECK: objc_method {{.*}} $@convention(objc_method) (NSString, @convention(block) () -> (), SlowServer) -> () // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[VOID_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<(), Never>) -> () await slowServer.serverRestart("somewhere") // CHECK: function_ref @[[STRING_NONZERO_FLAG_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<String, Error>, {{.*}}Bool, Optional<NSString>, Optional<NSError>) -> () let _: String = try await slowServer.doSomethingFlaggy() // CHECK: function_ref @[[STRING_ZERO_FLAG_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<String, Error>, Optional<NSString>, {{.*}}Bool, Optional<NSError>) -> () let _: String = try await slowServer.doSomethingZeroFlaggy() // CHECK: function_ref @[[STRING_STRING_ZERO_FLAG_THROW_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<(String, String), Error>, {{.*}}Bool, Optional<NSString>, Optional<NSError>, Optional<NSString>) -> () let _: (String, String) = try await slowServer.doSomethingMultiResultFlaggy() // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[NSSTRING_INT_THROW_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<(String, Int), Error>, Optional<NSString>, Int, Optional<NSError>) -> () let (_, _): (String, Int) = try await slowServer.findMultipleAnswers() let (_, _): (Bool, Bool) = try await slowServer.findDifferentlyFlavoredBooleans() // CHECK: [[ERROR]]([[ERROR_VALUE:%.*]] : @owned $Error): // CHECK: dealloc_stack [[RESUME_BUF]] // CHECK: br [[THROWBB:bb[0-9]+]]([[ERROR_VALUE]] // CHECK: [[THROWBB]]([[ERROR_VALUE:%.*]] : @owned $Error): // CHECK: throw [[ERROR_VALUE]] let _: String = await slowServer.findAnswerNullably("foo") let _: String = try await slowServer.doSomethingDangerousNullably("foo") let _: NSObject? = try await slowServer.stopRecording() let _: NSObject = try await slowServer.someObject() let _: () -> Void = await slowServer.performVoid2Void() let _: (Any) -> Void = await slowServer.performId2Void() let _: (Any) -> Any = await slowServer.performId2Id() let _: (String) -> String = await slowServer.performNSString2NSString() let _: ((String) -> String, String) = await slowServer.performNSString2NSStringNSString() let _: ((Any) -> Void, (Any) -> Void) = await slowServer.performId2VoidId2Void() let _: String = try await slowServer.findAnswerFailingly() let _: () -> Void = try await slowServer.obtainClosure() let _: Flavor = try await slowServer.iceCreamFlavor() } func testGeneric<T: AnyObject>(x: GenericObject<T>) async throws { let _: T? = try await x.doSomething() let _: GenericObject<T>? = await x.doAnotherThing() } func testGeneric2<T: AnyObject, U>(x: GenericObject<T>, y: U) async throws { let _: T? = try await x.doSomething() let _: GenericObject<T>? = await x.doAnotherThing() } // CHECK: sil{{.*}}@[[INT_COMPLETION_BLOCK]] // CHECK: [[CONT_ADDR:%.*]] = project_block_storage %0 // CHECK: [[CONT:%.*]] = load [trivial] [[CONT_ADDR]] // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $Int // CHECK: store %1 to [trivial] [[RESULT_BUF]] // CHECK: [[RESUME:%.*]] = function_ref @{{.*}}resumeUnsafeContinuation // CHECK: apply [[RESUME]]<Int>([[CONT]], [[RESULT_BUF]]) // CHECK: sil{{.*}}@[[STRING_COMPLETION_THROW_BLOCK]] // CHECK: [[RESUME_IN:%.*]] = copy_value %1 // CHECK: [[ERROR_IN:%.*]] = copy_value %2 // CHECK: [[CONT_ADDR:%.*]] = project_block_storage %0 // CHECK: [[CONT:%.*]] = load [trivial] [[CONT_ADDR]] // CHECK: [[ERROR_IN_B:%.*]] = begin_borrow [[ERROR_IN]] // CHECK: switch_enum [[ERROR_IN_B]] : {{.*}}, case #Optional.some!enumelt: [[ERROR_BB:bb[0-9]+]], case #Optional.none!enumelt: [[RESUME_BB:bb[0-9]+]] // CHECK: [[RESUME_BB]]: // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $String // CHECK: [[RESUME_CP:%.*]] = copy_value [[RESUME_IN]] // CHECK: [[BRIDGE:%.*]] = function_ref @{{.*}}unconditionallyBridgeFromObjectiveC // CHECK: [[BRIDGED_RESULT:%.*]] = apply [[BRIDGE]]([[RESUME_CP]] // CHECK: store [[BRIDGED_RESULT]] to [init] [[RESULT_BUF]] // CHECK: [[RESUME:%.*]] = function_ref @{{.*}}resumeUnsafeThrowingContinuation // CHECK: apply [[RESUME]]<String>([[CONT]], [[RESULT_BUF]]) // CHECK: br [[END_BB:bb[0-9]+]] // CHECK: [[END_BB]]: // CHECK: return // CHECK: [[ERROR_BB]]([[ERROR_IN_UNWRAPPED:%.*]] : @guaranteed $NSError): // CHECK: [[ERROR:%.*]] = init_existential_ref [[ERROR_IN_UNWRAPPED]] // CHECK: [[RESUME_WITH_ERROR:%.*]] = function_ref @{{.*}}resumeUnsafeThrowingContinuationWithError // CHECK: [[ERROR_COPY:%.*]] = copy_value [[ERROR]] // CHECK: apply [[RESUME_WITH_ERROR]]<String>([[CONT]], [[ERROR_COPY]]) // CHECK: br [[END_BB]] // CHECK: sil {{.*}} @[[VOID_COMPLETION_BLOCK]] // CHECK: [[CONT_ADDR:%.*]] = project_block_storage %0 // CHECK: [[CONT:%.*]] = load [trivial] [[CONT_ADDR]] // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $() // CHECK: [[RESUME:%.*]] = function_ref @{{.*}}resumeUnsafeContinuation // CHECK: apply [[RESUME]]<()>([[CONT]], [[RESULT_BUF]]) // CHECK: sil{{.*}}@[[STRING_NONZERO_FLAG_THROW_BLOCK]] // CHECK: [[ZERO:%.*]] = integer_literal {{.*}}, 0 // CHECK: switch_value {{.*}}, case [[ZERO]]: [[ZERO_BB:bb[0-9]+]], default [[NONZERO_BB:bb[0-9]+]] // CHECK: [[ZERO_BB]]: // CHECK: function_ref{{.*}}33_resumeUnsafeThrowingContinuation // CHECK: [[NONZERO_BB]]: // CHECK: function_ref{{.*}}42_resumeUnsafeThrowingContinuationWithError // CHECK: sil{{.*}}@[[STRING_ZERO_FLAG_THROW_BLOCK]] // CHECK: [[ZERO:%.*]] = integer_literal {{.*}}, 0 // CHECK: switch_value {{.*}}, case [[ZERO]]: [[ZERO_BB:bb[0-9]+]], default [[NONZERO_BB:bb[0-9]+]] // CHECK: [[NONZERO_BB]]: // CHECK: function_ref{{.*}}33_resumeUnsafeThrowingContinuation // CHECK: [[ZERO_BB]]: // CHECK: function_ref{{.*}}42_resumeUnsafeThrowingContinuationWithError // CHECK: sil{{.*}}@[[STRING_STRING_ZERO_FLAG_THROW_BLOCK]] // CHECK: [[ZERO:%.*]] = integer_literal {{.*}}, 0 // CHECK: switch_value {{.*}}, case [[ZERO]]: [[ZERO_BB:bb[0-9]+]], default [[NONZERO_BB:bb[0-9]+]] // CHECK: [[NONZERO_BB]]: // CHECK: function_ref{{.*}}33_resumeUnsafeThrowingContinuation // CHECK: [[ZERO_BB]]: // CHECK: function_ref{{.*}}42_resumeUnsafeThrowingContinuationWithError // CHECK: sil{{.*}}@[[NSSTRING_INT_THROW_COMPLETION_BLOCK]] // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $(String, Int) // CHECK: [[RESULT_0_BUF:%.*]] = tuple_element_addr [[RESULT_BUF]] {{.*}}, 0 // CHECK: [[BRIDGE:%.*]] = function_ref @{{.*}}unconditionallyBridgeFromObjectiveC // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE]] // CHECK: store [[BRIDGED]] to [init] [[RESULT_0_BUF]] // CHECK: [[RESULT_1_BUF:%.*]] = tuple_element_addr [[RESULT_BUF]] {{.*}}, 1 // CHECK: store %2 to [trivial] [[RESULT_1_BUF]] // CHECK-LABEL: sil {{.*}}@${{.*}}22testSlowServerFromMain @MainActor func testSlowServerFromMain(slowServer: SlowServer) async throws { // CHECK: hop_to_executor %6 : $MainActor // CHECK: [[RESUME_BUF:%.*]] = alloc_stack $Int // CHECK: [[STRINGINIT:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : // CHECK: [[ARG:%.*]] = apply [[STRINGINIT]] // CHECK: [[METHOD:%.*]] = objc_method {{.*}} $@convention(objc_method) (NSString, @convention(block) (Int) -> (), SlowServer) -> () // CHECK: [[CONT:%.*]] = get_async_continuation_addr Int, [[RESUME_BUF]] // CHECK: [[WRAPPED:%.*]] = struct $UnsafeContinuation<Int, Never> ([[CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage UnsafeContinuation<Int, Never> // CHECK: [[CONT_SLOT:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK: store [[WRAPPED]] to [trivial] [[CONT_SLOT]] // CHECK: [[BLOCK_IMPL:%.*]] = function_ref @[[INT_COMPLETION_BLOCK:.*]] : $@convention(c) (@inout_aliasable @block_storage UnsafeContinuation<Int, Never>, Int) -> () // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] {{.*}}, invoke [[BLOCK_IMPL]] // CHECK: apply [[METHOD]]([[ARG]], [[BLOCK]], %0) // CHECK: [[COPY:%.*]] = copy_value [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: await_async_continuation [[CONT]] {{.*}}, resume [[RESUME:bb[0-9]+]] // CHECK: [[RESUME]]: // CHECK: [[RESULT:%.*]] = load [trivial] [[RESUME_BUF]] // CHECK: hop_to_executor %6 : $MainActor // CHECK: fix_lifetime [[COPY]] // CHECK: destroy_value [[COPY]] // CHECK: dealloc_stack [[RESUME_BUF]] let _: Int = await slowServer.doSomethingSlow("mail") } // CHECK-LABEL: sil {{.*}}@${{.*}}26testThrowingMethodFromMain @MainActor func testThrowingMethodFromMain(slowServer: SlowServer) async -> String { // CHECK: [[RESULT_BUF:%.*]] = alloc_stack $String // CHECK: [[STRING_ARG:%.*]] = apply {{%.*}}({{%.*}}) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: [[METH:%.*]] = objc_method {{%.*}} : $SlowServer, #SlowServer.doSomethingDangerous!foreign // CHECK: [[RAW_CONT:%.*]] = get_async_continuation_addr [throws] String, [[RESULT_BUF]] : $*String // CHECK: [[CONT:%.*]] = struct $UnsafeContinuation<String, Error> ([[RAW_CONT]] : $Builtin.RawUnsafeContinuation) // CHECK: [[STORE_ALLOC:%.*]] = alloc_stack $@block_storage UnsafeContinuation<String, Error> // CHECK: [[PROJECTED:%.*]] = project_block_storage [[STORE_ALLOC]] : $*@block_storage // CHECK: store [[CONT]] to [trivial] [[PROJECTED]] : $*UnsafeContinuation<String, Error> // CHECK: [[INVOKER:%.*]] = function_ref @$sSo8NSStringCSgSo7NSErrorCSgIeyByy_SSTz_ // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[STORE_ALLOC]] {{.*}}, invoke [[INVOKER]] // CHECK: [[OPTIONAL_BLK:%.*]] = enum {{.*}}, #Optional.some!enumelt, [[BLOCK]] // CHECK: %28 = apply [[METH]]([[STRING_ARG]], [[OPTIONAL_BLK]], {{%.*}}) : $@convention(objc_method) (NSString, Optional<@convention(block) (Optional<NSString>, Optional<NSError>) -> ()>, SlowServer) -> () // CHECK: [[STRING_ARG_COPY:%.*]] = copy_value [[STRING_ARG]] : $NSString // CHECK: dealloc_stack [[STORE_ALLOC]] : $*@block_storage UnsafeContinuation<String, Error> // CHECK: destroy_value [[STRING_ARG]] : $NSString // CHECK: await_async_continuation [[RAW_CONT]] : $Builtin.RawUnsafeContinuation, resume [[RESUME:bb[0-9]+]], error [[ERROR:bb[0-9]+]] // CHECK: [[RESUME]] // CHECK: {{.*}} = load [take] [[RESULT_BUF]] : $*String // CHECK: hop_to_executor {{%.*}} : $MainActor // CHECK: fix_lifetime [[STRING_ARG_COPY]] : $NSString // CHECK: destroy_value [[STRING_ARG_COPY]] : $NSString // CHECK: dealloc_stack [[RESULT_BUF]] : $*String // CHECK: [[ERROR]] // CHECK: hop_to_executor {{%.*}} : $MainActor // CHECK: fix_lifetime [[STRING_ARG_COPY]] : $NSString // CHECK: destroy_value [[STRING_ARG_COPY]] : $NSString // CHECK: dealloc_stack [[RESULT_BUF]] : $*String do { return try await slowServer.doSomethingDangerous("run-with-scissors") } catch { return "none" } }
fc00f40c8907bac359a28e5c16a2082e
57.917695
241
0.627226
false
false
false
false
Esri/tips-and-tricks-ios
refs/heads/master
DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/SimulatedLocation/SimulatedLocationVC.swift
apache-2.0
1
// Copyright 2015 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class SimulatedLocationVC: UIViewController { @IBOutlet var mapView: AGSMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let mapUrl = NSURL(string: "http://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer") let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl); self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer") } @IBAction func startSimulation(sender: AnyObject) { // get the path to our GPX file let gpxPath = NSBundle.mainBundle().pathForResource("toughmudder2012", ofType: "gpx") // create our data source let gpxLDS = AGSGPXLocationDisplayDataSource(path: gpxPath) // tell the AGSLocationDisplay to use our data source self.mapView.locationDisplay.dataSource = gpxLDS; // enter nav mode so we can play it back oriented in the same way we would be if it // were happening "live" self.mapView.locationDisplay.autoPanMode = .Default; // we have to start the datasource in order to play it back self.mapView.locationDisplay.startDataSource() } @IBAction func stopSimulation(sender: AnyObject) { self.mapView.locationDisplay.stopDataSource() } }
869cc3fd4f279127021860a19b09136b
35.481481
115
0.687817
false
false
false
false
teaxus/TSAppEninge
refs/heads/master
Source/Tools/InformationManage/DateManage.swift
mit
1
// // DateManage.swift // TSAppEngine // // Created by teaxus on 15/12/7. // Copyright © 2015年 teaxus. All rights reserved. // import Foundation extension Date{ public func changeDateToLocalData(date:Date)->Date{ let zone = NSTimeZone.system let interval = zone.secondsFromGMT(for: date) return date.addingTimeInterval(Double(interval)) } public var age:String{ // 出生日期转换 年月日 var set_calendar = Set<Calendar.Component>() set_calendar.insert(Calendar.Component.year) set_calendar.insert(Calendar.Component.month) set_calendar.insert(Calendar.Component.day) let components1 = Calendar.current.dateComponents(set_calendar, from: self) let brithDateYear = components1.year! let brithDateDay = components1.day! let brithDateMonth = components1.month! let components2 = Calendar.current.dateComponents(set_calendar, from: Date()) let currentDateYear = components2.year! let currentDateDay = components2.day! let currentDateMonth = components2.month! // 计算年龄 var iAge = currentDateYear - brithDateYear - 1; if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) { iAge += 1 } return "\(iAge)" } //两个时间相差的 public func deltaDay(day:NSDate) -> DateComponents{ let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let unit = NSCalendar.Unit(rawValue: NSCalendar.Unit.day.rawValue | NSCalendar.Unit.hour.rawValue | NSCalendar.Unit.minute.rawValue | NSCalendar.Unit.second.rawValue) // return calendar.components(unit, from: self, to: day as Date, options: .WrapComponents) return calendar.components(unit, from: self, to: day as Date, options: NSCalendar.Options.wrapComponents) } public func dateWithformatter(string_formatter:String)->String{ let formatter = DateFormatter() formatter.dateFormat = string_formatter return formatter.string(from: self as Date) } } extension Double{ public var toDate:NSDate{ return NSDate(timeIntervalSince1970: self) } }
d07ddaafb6b9541fe7804fff53c8d640
28.3
124
0.647611
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Base/Vender/TransitionAnimation/PopTipTransitionAnimation.swift
mit
1
// // PopTipTransitionAnimation.swift // TransitionTreasury // // Created by DianQK on 12/29/15. // Copyright © 2016 TransitionTreasury. All rights reserved. // import UIKit //import TransitionTreasury /// Pop Your Tip ViewController. public class PopTipTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning { public var transitionStatus: TransitionStatus public var transitionContext: UIViewControllerContextTransitioning? public var cancelPop: Bool = false public var interacting: Bool = false private var mainVC: UIViewController? lazy private var tapGestureRecognizer: UITapGestureRecognizer = { let tap = UITapGestureRecognizer(target: self, action: #selector(PopTipTransitionAnimation.tapDismiss(_:))) return tap }() lazy private var maskView: UIView = { let view = UIView() view.backgroundColor = UIColor.black return view }() public private(set) var visibleHeight: CGFloat private let bounce: Bool public init(visibleHeight height: CGFloat, bounce: Bool = false, status: TransitionStatus = .present) { transitionStatus = status visibleHeight = height self.bounce = bounce super.init() } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext var fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) var toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) let containView = transitionContext.containerView let screenBounds = UIScreen.main.bounds var startFrame = screenBounds.offsetBy(dx: 0, dy: screenBounds.size.height) var finalFrame = screenBounds.offsetBy(dx: 0, dy: screenBounds.height - visibleHeight) var startOpacity: CGFloat = 0 var finalOpacity: CGFloat = 0.3 containView.addSubview(fromVC!.view) if transitionStatus == .dismiss { swap(&fromVC, &toVC) swap(&startFrame, &finalFrame) swap(&startOpacity, &finalOpacity) } else if transitionStatus == .present { let bottomView = UIView(frame: screenBounds) bottomView.layer.contents = { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(fromVC!.view.bounds.size, true, scale) fromVC!.view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image?.cgImage }() bottomView.addGestureRecognizer(tapGestureRecognizer) containView.addSubview(bottomView) maskView.frame = screenBounds maskView.alpha = startOpacity bottomView.addSubview(maskView) mainVC = fromVC } toVC?.view.layer.frame = startFrame containView.addSubview(toVC!.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: (bounce ? 0.8 : 1), initialSpringVelocity: (bounce ? 0.6 : 1), options: .curveEaseInOut, animations: { toVC?.view.layer.frame = finalFrame self.maskView.alpha = finalOpacity }) { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } func tapDismiss(_ tap: UITapGestureRecognizer) { mainVC?.presentedViewController?.transitioningDelegate = nil mainVC?.dismiss(animated: true, completion: nil) } }
3d2e1da143c30ab6784c9dc8589bd179
37.009524
219
0.662741
false
false
false
false
PerfectlySoft/Perfect-Authentication
refs/heads/master
Sources/LocalAuthentication/Schema/AccessToken.swift
apache-2.0
1
// // AccessToken.swift // Perfect-OAuth2-Server // // Created by Jonathan Guthrie on 2017-02-06. // // import StORM import PostgresStORM import Foundation import SwiftRandom import SwiftMoment public class AccessToken: PostgresStORM { public var accesstoken = "" public var refreshtoken = "" public var userid = "" public var expires = 0 public var scope = "" var _rand = URandom() public override init(){} public init(userid u: String, expiration: Int, scope s: [String] = [String]()) { accesstoken = _rand.secureToken refreshtoken = _rand.secureToken userid = u let th = moment() expires = Int(th.epoch()) + (expiration * 1000) scope = s.isEmpty ? "" : s.joined(separator: " ") } override public func to(_ this: StORMRow) { accesstoken = this.data["accesstoken"] as? String ?? "" refreshtoken = this.data["refreshtoken"] as? String ?? "" userid = this.data["userid"] as? String ?? "" expires = this.data["expires"] as? Int ?? 0 scope = this.data["scope"] as? String ?? "" } func rows() -> [AccessToken] { var rows = [AccessToken]() for i in 0..<self.results.rows.count { let row = AccessToken() row.to(self.results.rows[i]) rows.append(row) } return rows } }
c4ae645ae229372b657455e020adb0d0
22.54717
81
0.645032
false
false
false
false
atomkirk/TouchForms
refs/heads/master
TouchForms/Source/MessageChildFormCell.swift
mit
1
// // MessageChildFormCell.swift // TouchForms // // Created by Adam Kirk on 7/25/15. // Copyright (c) 2015 Adam Kirk. All rights reserved. // import Foundation private let red = UIColor(red: 215.0/255.0, green: 0, blue: 0, alpha: 1) private let green = UIColor(red: 0, green: 215.0/255.0, blue: 0, alpha: 1) class MessageChildFormCell: FormCell { var type: ChildFormElementType = .Loading @IBOutlet weak var messageLabel: UILabel! override func layoutSubviews() { super.layoutSubviews() switch type { case .Error: messageLabel.textColor = red case .ValidationError: messageLabel.textColor = red case .Success: messageLabel.textColor = green default: messageLabel.textColor = UIColor.blackColor() } } override func drawRect(rect: CGRect) { super.drawRect(rect) if type == .Error { let point1 = CGPointMake(20, (self.frame.size.height / 2.0) - 5) let point2 = CGPointMake(30, (self.frame.size.height / 2.0) + 5) let point3 = CGPointMake(20, (self.frame.size.height / 2.0) + 5) let point4 = CGPointMake(30, (self.frame.size.height / 2.0) - 5) let path = UIBezierPath() path.moveToPoint(point1) path.addLineToPoint(point2) path.moveToPoint(point3) path.addLineToPoint(point4) red.setStroke() path.stroke(); } else if type == .ValidationError { let point1 = CGPointMake(25, self.frame.size.height / 2.0) let point2 = CGPointMake(20, point1.y) let point3 = CGPointMake(point2.x, 0) let path = UIBezierPath() path.moveToPoint(point1) path.addLineToPoint(point2) path.addLineToPoint(point3) red.setStroke() path.stroke() } else if type == .Success { let point1 = CGPointMake(22, (self.frame.size.height / 2.0)) let point2 = CGPointMake(point1.x + 4, point1.y + 5) let point3 = CGPointMake(point2.x + 4, point2.y - 12) let path = UIBezierPath() path.moveToPoint(point1) path.addLineToPoint(point2) path.addLineToPoint(point3) green.setStroke() path.stroke() } } }
54628a87616797a09861c2c3d1a2819e
31.876712
76
0.571488
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
refs/heads/master
Playground Collection/Part 3 - Alien Adventure 1/Strings/Strings_Recap.playground/Pages/What are Strings made of_ .xcplaygroundpage/Contents.swift
mit
1
//: ## What are Strings made of? import UIKit //: ### Defining variables and constants using string literals let monkeyString = "I saw a monkey." let thiefString = "He stole my iPhone." //: ### Emojis in Strings var monkeyStringWithEmoji = "I saw a 🐒." var thiefStringWithEmoji = "He stole my 📱." //: ### The characters property of the String struct let gString = "Gary's giraffe gobbled gooseberries greedily" var count = 0 for character in gString.characters { if character == "g" || character == "G" { count += 1 } } //: [Next](@next)
ea1acab2dc6129047a4350043934a6bb
23.347826
62
0.666071
false
false
false
false
glassonion1/R9MIDISequencer
refs/heads/master
Sources/R9MIDISequencer/Sequencer.swift
mit
1
// // Sequencer.swift // R9MIDISequencer // // Created by Taisuke Fujita on 2016/02/03. // Copyright © 2016年 Taisuke Fujita. All rights reserved. // import AVFoundation import CoreMIDI import AudioToolbox @available(iOS 9.0, *) @available(OSX 10.11, *) open class Sequencer { let callBack: @convention(c) (UnsafeMutableRawPointer?, MusicSequence, MusicTrack, MusicTimeStamp, UnsafePointer<MusicEventUserData>, MusicTimeStamp, MusicTimeStamp) -> Void = { (obj, seq, mt, timestamp, userData, timestamp2, timestamp3) in // Cタイプ関数なのでselfを使えません unowned let mySelf: Sequencer = unsafeBitCast(obj, to: Sequencer.self) if mySelf.enableLooping { return } OperationQueue.main.addOperation({ mySelf.delegate?.midiSequenceDidFinish() if let player = mySelf.musicPlayer { MusicPlayerSetTime(player, 0) } }) } var musicSequence: MusicSequence? var musicPlayer: MusicPlayer? var midiClient = MIDIClientRef() var midiDestination = MIDIEndpointRef() public private(set) var lengthInSeconds: TimeInterval = 0.0 // Beats Per Minute public private(set) var bpm: TimeInterval = 0.0 weak public var delegate: MIDIMessageListener? public var enableLooping = false public var currentPositionInSeconds: TimeInterval { get { guard let player = musicPlayer else { return 0.0 } var time: MusicTimeStamp = 0.0 MusicPlayerGetTime(player, &time) return time } } public init() { var result = OSStatus(noErr) result = NewMusicPlayer(&musicPlayer) if result != OSStatus(noErr) { print("error creating player : \(result)") return } let destinationCount = MIDIGetNumberOfDestinations() print("DestinationCount: \(destinationCount)") result = MIDIClientCreateWithBlock("MIDI Client" as CFString, &midiClient) { midiNotification in print(midiNotification) } if result != OSStatus(noErr) { print("error creating client : \(result)") } Thread.sleep(forTimeInterval: 0.2) // スリープを入れないとDestinationのコールバックが呼ばれない createMIDIDestination() } deinit { stop() if let player = musicPlayer { DisposeMusicPlayer(player) } MIDIEndpointDispose(midiDestination) MIDIClientDispose(midiClient) } public func loadMIDIURL(_ midiFileUrl: URL) { // 再生中だったら止める stop() var result = NewMusicSequence(&musicSequence) guard let sequence = musicSequence else { print("error creating sequence : \(result)") return } // MIDIファイルの読み込み MusicSequenceFileLoad(sequence, midiFileUrl as CFURL, .midiType, MusicSequenceLoadFlags.smf_ChannelsToTracks) // bpmの取得 MusicSequenceGetBeatsForSeconds(sequence, 60, &bpm) // シーケンサにEndPointをセットする // trackが決まってからセットしないとだめ result = MusicSequenceSetMIDIEndpoint(sequence, midiDestination); if result != OSStatus(noErr) { print("error creating endpoint : \(result)") } var musicTrack: MusicTrack? = nil var sequenceLength: MusicTimeStamp = 0 var trackCount: UInt32 = 0 MusicSequenceGetTrackCount(sequence, &trackCount) for i in 0 ..< trackCount { var trackLength: MusicTimeStamp = 0 var trackLengthSize: UInt32 = 0 MusicSequenceGetIndTrack(sequence, i, &musicTrack) MusicTrackGetProperty(musicTrack!, kSequenceTrackProperty_TrackLength, &trackLength, &trackLengthSize) if sequenceLength < trackLength { sequenceLength = trackLength } if enableLooping { var loopInfo = MusicTrackLoopInfo(loopDuration: trackLength, numberOfLoops: 0) let lisize: UInt32 = 0 let status = MusicTrackSetProperty(musicTrack!, kSequenceTrackProperty_LoopInfo, &loopInfo, lisize ) if status != OSStatus(noErr) { print("Error setting loopinfo on track \(status)") } } } lengthInSeconds = sequenceLength // 曲の最後にコールバックを仕込む result = MusicSequenceSetUserCallback(sequence, callBack, unsafeBitCast(self, to: UnsafeMutableRawPointer.self)) if result != OSStatus(noErr) { print("error set user callback : \(result)") } let userData: UnsafeMutablePointer<MusicEventUserData> = UnsafeMutablePointer.allocate(capacity: 1) result = MusicTrackNewUserEvent(musicTrack!, sequenceLength, userData) if result != OSStatus(noErr) { print("error new user event : \(result)") } } public func play() { guard let sequence = musicSequence else { return } guard let player = musicPlayer else { return } MusicPlayerSetSequence(player, sequence) MusicPlayerPreroll(player) MusicPlayerStart(player) } public func playWithMIDIURL(_ midiFileUrl: URL) { loadMIDIURL(midiFileUrl) play() } public func stop() { if let sequence = musicSequence { DisposeMusicSequence(sequence) } if let player = musicPlayer { MusicPlayerStop(player) MusicPlayerSetTime(player, 0) } } public func addMIDINoteEvent(trackNumber: UInt32, noteNumber: UInt8, velocity: UInt8, position: MusicTimeStamp, duration: Float32, channel: UInt8 = 0) { guard let sequence = musicSequence else { return } var musicTrack: MusicTrack? = nil var result = MusicSequenceGetIndTrack(sequence, trackNumber, &musicTrack) if result != OSStatus(noErr) { print("error get track index: \(trackNumber) \(result)") } guard let track = musicTrack else { return } var message = MIDINoteMessage(channel: channel, note: noteNumber, velocity: velocity, releaseVelocity: 0, duration: duration) result = MusicTrackNewMIDINoteEvent(track, position, &message) if result != OSStatus(noErr) { print("error creating midi note event \(result)") } } private func createMIDIDestination() { /// This block will be method then memory leak /// @see https://github.com/genedelisa/Swift2MIDI/blob/master/Swift2MIDI/ViewController.swift /// - parameter packet: パケットデータ let handleMIDIMessage = { [weak self] (packet: MIDIPacket) in guard let localSelf = self else { return } let status = UInt8(packet.data.0) let d1 = UInt8(packet.data.1) let d2 = UInt8(packet.data.2) let rawStatus = status & 0xF0 // without channel let channel = UInt8(status & 0x0F) switch rawStatus { case 0x80, 0x90: // weak delegateにしないとメモリリークする OperationQueue.main.addOperation({ [weak delegate = localSelf.delegate] in if rawStatus == 0x90 { delegate?.midiNoteOn(d1, velocity: d2, channel: channel) } else { delegate?.midiNoteOff(d1, channel: channel) } }) case 0xA0: print("Polyphonic Key Pressure (Aftertouch). Channel \(channel) note \(d1) pressure \(d2)") case 0xB0: print("Control Change. Channel \(channel) controller \(d1) value \(d2)") case 0xC0: print("Program Change. Channel \(channel) program \(d1)") case 0xD0: print("Channel Pressure (Aftertouch). Channel \(channel) pressure \(d1)") case 0xE0: print("Pitch Bend Change. Channel \(channel) lsb \(d1) msb \(d2)") default: print("Unhandled message \(status)") } } var result = OSStatus(noErr) let name = R9Constants.midiDestinationName as CFString result = MIDIDestinationCreateWithBlock(midiClient, name, &midiDestination) { (packetList, srcConnRefCon) in let packets = packetList.pointee let packet: MIDIPacket = packets.packet var packetPtr: UnsafeMutablePointer<MIDIPacket> = UnsafeMutablePointer.allocate(capacity: 1) packetPtr.initialize(to: packet) for _ in 0 ..< packets.numPackets { handleMIDIMessage(packetPtr.pointee) packetPtr = MIDIPacketNext(packetPtr) } } if result != OSStatus(noErr) { print("error creating destination : \(result)") } } }
9cdd4394e8b6cee7bc351ab922737da6
34.734848
181
0.569112
false
false
false
false
adriankrupa/swift3D
refs/heads/master
Source/Vector.swift
mit
1
// // Created by Adrian Krupa on 30.11.2015. // Copyright (c) 2015 Adrian Krupa. All rights reserved. // import Foundation import simd public extension float3 { public init(_ v: float4) { self.init(v.x, v.y, v.z) } } public extension float4 { public init(_ v: float3, _ vw: Float) { self.init() x = v.x y = v.y z = v.z w = vw } public init(_ v: float3) { self.init() x = v.x y = v.y z = v.z w = 0 } public init(_ q: quat) { self.init() x = q.x y = q.y z = q.z w = q.w } } public extension double3 { public init(_ v: double4) { self.init(v.x, v.y, v.z) } } public extension double4 { public init(_ v: double3, _ vw: Double) { self.init() x = v.x y = v.y z = v.z w = vw } public init(_ v: double3) { self.init() x = v.x y = v.y z = v.z w = 0 } public init(_ q: dquat) { self.init() x = q.x y = q.y z = q.z w = q.w } } public func ==(a: float4, b: float4) -> Bool { for i in 0..<4 { if(a[i] != b[i]) { return false } } return true } public func !=(a: float4, b: float4) -> Bool { return !(a==b) } public func ==(a: float3, b: float3) -> Bool { for i in 0..<3 { if(a[i] != b[i]) { return false } } return true } public func !=(a: float3, b: float3) -> Bool { return !(a==b) } public func ==(a: float2, b: float2) -> Bool { for i in 0..<2 { if(a[i] != b[i]) { return false } } return true } public func !=(a: float2, b: float2) -> Bool { return !(a==b) } public func ==(a: double4, b: double4) -> Bool { for i in 0..<4 { if(a[i] != b[i]) { return false } } return true } public func !=(a: double4, b: double4) -> Bool { return !(a==b) } public func ==(a: double3, b: double3) -> Bool { for i in 0..<3 { if(a[i] != b[i]) { return false } } return true } public func !=(a: double3, b: double3) -> Bool { return !(a==b) } public func ==(a: double2, b: double2) -> Bool { for i in 0..<2 { if(a[i] != b[i]) { return false } } return true } public func !=(a: double2, b: double2) -> Bool { return !(a==b) }
9a72469baec5e21b3a77d6efcbc52979
15.581699
56
0.428628
false
false
false
false
drewag/Swiftlier
refs/heads/master
Sources/Swiftlier/Errors/GenericSwiftlierError.swift
mit
1
// // GenericSwiftlierError.swift // Swiftlier // // Created by Andrew J Wagner on 7/30/19. // import Foundation /// Basic codable implementation of SwiftlierError public struct GenericSwiftlierError: SwiftlierError { public let title: String public let alertMessage: String public let details: String? public let isInternal: Bool public let backtrace: [String]? public let extraInfo: [String:String] public var description: String { return "\(self.title): \(self.alertMessage)" } public init(title: String, alertMessage: String, details: String?, isInternal: Bool, backtrace: [String]? = Thread.callStackSymbols, extraInfo: [String:String] = [:]) { self.title = title self.alertMessage = alertMessage self.details = details self.isInternal = isInternal self.backtrace = backtrace self.extraInfo = extraInfo } public init<E: SwiftlierError>(_ error: E) { self.title = error.title self.alertMessage = error.alertMessage self.details = error.details self.isInternal = error.isInternal self.backtrace = error.backtrace self.extraInfo = error.getExtraInfo() } public init(while operation: String, reason: String, details: String? = nil, backtrace: [String]? = Thread.callStackSymbols, extraInfo: [String:String] = [:]) { self.title = "Error \(operation.titleCased)" self.alertMessage = "Internal Error. Please try again. If the problem persists please contact support with the following description: \(reason)" self.details = details self.isInternal = true self.backtrace = backtrace self.extraInfo = extraInfo } public init(userErrorWhile operation: String, reason: String, details: String? = nil, backtrace: [String]? = Thread.callStackSymbols, extraInfo: [String:String] = [:]) { self.title = "Error \(operation.titleCased)" self.alertMessage = reason self.details = details self.isInternal = false self.backtrace = backtrace self.extraInfo = extraInfo } public init(_ doing: String, because: String, byUser: Bool = false) { self.title = "Error \(doing.titleCased)" if byUser { self.isInternal = false self.alertMessage = because } else { self.alertMessage = "Internal Error. Please try again. If the problem persists please contact support with the following description: \(because)" self.isInternal = true } self.details = nil self.backtrace = Thread.callStackSymbols self.extraInfo = [:] } public func getExtraInfo() -> [String : String] { return self.extraInfo } } extension GenericSwiftlierError: Codable { enum CodingKeys: String, CodingKey { // Core case title, alertMessage, details, isInternal, backtrace, extraInfo // ReportableError backwards compatability case doing, because, perpitrator, message } struct VariableKey: CodingKey { let stringValue: String let intValue: Int? init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } init?(intValue: Int) { return nil } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let title = try container.decodeIfPresent(String.self, forKey: .title) { // Current Swiftlier Error self.title = title self.alertMessage = try container.decode(String.self, forKey: .alertMessage) self.isInternal = try container.decode(Bool.self, forKey: .isInternal) self.details = try container.decodeIfPresent(String.self, forKey: .details) } else { // ReportableError backwards capatability let perpetrator = try container.decode(String.self, forKey: .perpitrator) let doing = try container.decode(String.self, forKey: .doing) let reason = try container.decode(String.self, forKey: .because) self.title = "Error \(doing.capitalized)" if perpetrator == "system" { self.alertMessage = "Internal Error. Please try again. If the problem persists please contact support with the following description: \(reason)" self.isInternal = true } else { self.alertMessage = reason self.isInternal = false } self.details = nil } self.backtrace = try container.decodeIfPresent([String].self, forKey: .backtrace) self.extraInfo = try container.decodeIfPresent([String:String].self, forKey: .extraInfo) ?? [:] } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.title, forKey: .title) try container.encode(self.alertMessage, forKey: .alertMessage) try container.encode(self.details, forKey: .details) try container.encode(self.isInternal, forKey: .isInternal) try container.encode(self.backtrace, forKey: .backtrace) try container.encode(self.extraInfo, forKey: .extraInfo) // Backwards compatability try container.encode(self.title, forKey: .doing) try container.encode(self.alertMessage, forKey: .because) try container.encode(self.isInternal ? "system" : "user", forKey: .perpitrator) try container.encode(self.description, forKey: .message) var variableContainer = encoder.container(keyedBy: VariableKey.self) for (key, value) in self.extraInfo { guard let key = VariableKey(stringValue: key) else { continue } try variableContainer.encode(value, forKey: key) } } }
6a988718c799a61af627b3b6aababd9d
37.22293
173
0.636894
false
false
false
false
appnexus/mobile-sdk-ios
refs/heads/master
tests/TrackerUITest/IntegrationUITests/VideoAdTests.swift
apache-2.0
1
/* Copyright 2019 APPNEXUS INC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest class VideoAdTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testVastVideoAd(){ let adObject = AdObject(adType: "Video", accessibilityIdentifier: PlacementTestConstants.VideoAd.testRTBVideo, placement: "19065996") let videoAdObject = VideoAdObject(isVideo: false , adObject: adObject) let videoAdObjectString = AdObjectModel.encodeVideoObject(adObject: videoAdObject) let app = XCUIApplication() app.launchArguments.append(PlacementTestConstants.VideoAd.testRTBVideo) app.launchArguments.append(videoAdObjectString) app.launch() let webViewsQuery = app.webViews.element(boundBy: 0) wait(for: webViewsQuery, timeout: 25) wait(2) let webview = webViewsQuery.firstMatch XCTAssertEqual(webview.exists, true) let adDuration = webViewsQuery.staticTexts["1:06"] XCTAssertEqual(adDuration.exists, true) let muteButton = webViewsQuery.buttons[" Mute"] XCTAssertEqual(muteButton.exists, true) muteButton.tap() wait(2) let unmuteButton = webViewsQuery.buttons[" Unmute"] XCTAssertEqual(unmuteButton.exists, true) unmuteButton.tap() wait(2) // let adLearnMoreStaticText = app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"testBannerVideo\"].webViews",".webViews"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.staticTexts["Learn More - Ad"] // XCTAssertEqual(adLearnMoreStaticText.exists, true) // let skipText = webViewsQuery.staticTexts["SKIP"] // XCTAssertEqual(skipText.exists, true) // XCGlobal.screenshotWithTitle(title: PlacementTestConstants.VideoAd.testRTBVideo) // wait(2) } }
39f5c16db6901678b7dae04dbbd9a4aa
35.493976
207
0.666226
false
true
false
false
lanjing99/RxSwiftDemo
refs/heads/master
04-observables-in-practice/final/Combinestagram/MainViewController.swift
mit
1
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import RxSwift class MainViewController: UIViewController { @IBOutlet weak var imagePreview: UIImageView! @IBOutlet weak var buttonClear: UIButton! @IBOutlet weak var buttonSave: UIButton! @IBOutlet weak var itemAdd: UIBarButtonItem! private let bag = DisposeBag() private let images = Variable<[UIImage]>([]) override func viewDidLoad() { super.viewDidLoad() images.asObservable() .subscribe(onNext: { [weak self] photos in guard let preview = self?.imagePreview else { return } preview.image = UIImage.collage(images: photos, size: preview.frame.size) }) .addDisposableTo(bag) images.asObservable() .subscribe(onNext: { [weak self] photos in self?.updateUI(photos: photos) }) .addDisposableTo(bag) } private func updateUI(photos: [UIImage]) { buttonSave.isEnabled = photos.count > 0 && photos.count % 2 == 0 buttonClear.isEnabled = photos.count > 0 itemAdd.isEnabled = photos.count < 6 title = photos.count > 0 ? "\(photos.count) photos" : "Collage" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("resources: \(RxSwift.Resources.total)") } @IBAction func actionClear() { images.value = [] } @IBAction func actionSave() { guard let image = imagePreview.image else { return } PhotoWriter.save(image) .subscribe(onError: { [weak self] error in self?.showMessage("Error", description: error.localizedDescription) }, onCompleted: { [weak self] in self?.showMessage("Saved") self?.actionClear() }) .addDisposableTo(bag) } @IBAction func actionAdd() { //images.value.append(UIImage(named: "IMG_1907.jpg")!) let photosViewController = storyboard!.instantiateViewController( withIdentifier: "PhotosViewController") as! PhotosViewController photosViewController.selectedPhotos .subscribe(onNext: { [weak self] newImage in guard let images = self?.images else { return } images.value.append(newImage) }, onDisposed: { print("completed photo selection") }) .addDisposableTo(photosViewController.bag) navigationController!.pushViewController(photosViewController, animated: true) } func showMessage(_ title: String, description: String? = nil) { let alert = UIAlertController(title: title, message: description, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Close", style: .default, handler: { [weak self] _ in self?.dismiss(animated: true, completion: nil)})) present(alert, animated: true, completion: nil) } }
54b0879b63ff8272e22c7a619270ab25
35.075472
144
0.696391
false
false
false
false
lijuncode/SimpleMemo
refs/heads/master
SimpleMemo/View/MemoCell.swift
mit
2
// // MemoCell.swift // EverMemo // // Created by  李俊 on 15/8/5. // Copyright (c) 2015年  李俊. All rights reserved. // import UIKit import SnapKit import SMKit private let deleteViewWidth: CGFloat = 60 private let UIPanGestureRecognizerStateKeyPath = "state" class MemoCell: UICollectionViewCell { var didSelectedMemoAction: ((_ memo: Memo) -> Void)? var deleteMemoAction: ((_ memo: Memo) -> Void)? var memo: Memo? { didSet { contentLabel.text = memo?.text } } fileprivate var containingView: UICollectionView? { didSet { updateContainingView() } } fileprivate var hasCellShowDeleteBtn = false fileprivate var containingViewPangestureRecognize: UIPanGestureRecognizer? fileprivate let scrollView = UIScrollView() fileprivate let deleteView = DeleteView() fileprivate let contentLabel: MemoLabel = { let label = MemoLabel() label.backgroundColor = .white label.numberOfLines = 0 label.font = UIFont.systemFont(ofSize: 15) label.verticalAlignment = .top label.textColor = SMColor.content label.sizeToFit() return label }() fileprivate var getsureRecognizer: UIGestureRecognizer? override init(frame: CGRect) { super.init(frame: frame) setUI() NotificationCenter.default.addObserver(self, selector: #selector(hiddenDeleteButtonAnimated), name: SMNotification.MemoCellShouldHiddenDeleteBtn, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(receiveMemoCellDidShowDeleteBtnNotification), name: SMNotification.MemoCellDidShowDeleteBtn, object: nil) } override func didMoveToSuperview() { containingView = nil var view: UIView = self while let superview = view.superview { view = superview if let collectionView: UICollectionView = view as? UICollectionView { containingView = collectionView break } } } override func layoutSubviews() { super.layoutSubviews() scrollView.contentSize = CGSize(width: contentView.width + deleteViewWidth, height: contentView.height) deleteView.frame = CGRect(x: contentView.width, y: 0, width: deleteViewWidth, height: contentView.height) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { removeObserver() NotificationCenter.default.removeObserver(self) } @objc fileprivate func topLabel() { if hasCellShowDeleteBtn { NotificationCenter.default.post(name: SMNotification.MemoCellShouldHiddenDeleteBtn, object: nil) hasCellShowDeleteBtn = false return } if let memo = memo { didSelectedMemoAction?(memo) } } @objc fileprivate func deleteMemo() { if let memo = memo { deleteMemoAction?(memo) } } @objc fileprivate func receiveMemoCellDidShowDeleteBtnNotification() { hasCellShowDeleteBtn = true } @objc fileprivate func hiddenDeleteButtonAnimated() { hiddenDeleteButton(withAnimated: true) hasCellShowDeleteBtn = false } override func prepareForReuse() { memo = nil hiddenDeleteButton(withAnimated: false) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == UIPanGestureRecognizerStateKeyPath && containingViewPangestureRecognize == object as? UIPanGestureRecognizer { if containingViewPangestureRecognize?.state == .began { hiddenDeleteButton(withAnimated: true) } } } } // MARK: - UI private extension MemoCell { func updateContainingView() { removeObserver() if let collecionView = containingView { containingViewPangestureRecognize = collecionView.panGestureRecognizer containingViewPangestureRecognize?.addObserver(self, forKeyPath: UIPanGestureRecognizerStateKeyPath, options: .new, context: nil) } } func removeObserver() { containingViewPangestureRecognize?.removeObserver(self, forKeyPath: UIPanGestureRecognizerStateKeyPath) } func setUI() { backgroundColor = UIColor.white scrollView.bounces = false scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false contentView.addSubview(scrollView) scrollView.snp.makeConstraints { (maker) in maker.top.left.bottom.right.equalToSuperview() } getsureRecognizer = UITapGestureRecognizer(target: self, action: #selector(topLabel)) contentLabel.addGestureRecognizer(getsureRecognizer!) contentLabel.isUserInteractionEnabled = true scrollView.addSubview(contentLabel) contentLabel.snp.makeConstraints { (maker) in maker.top.equalTo(scrollView).offset(5) maker.left.equalTo(scrollView).offset(5) maker.bottom.equalTo(contentView).offset(-5) maker.right.lessThanOrEqualTo(contentView).offset(-5) maker.width.equalTo(contentView.width - 10) } deleteView.backgroundColor = SMColor.backgroundGray deleteView.deleteBtn.addTarget(self, action: #selector(deleteMemo), for: .touchUpInside) scrollView.addSubview(deleteView) layer.shadowOffset = CGSize(width: 0, height: 1) layer.shadowOpacity = 0.2 layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale } } extension MemoCell: UIScrollViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if hasCellShowDeleteBtn { NotificationCenter.default.post(name: SMNotification.MemoCellShouldHiddenDeleteBtn, object: nil) hasCellShowDeleteBtn = false } } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.x >= deleteViewWidth { NotificationCenter.default.post(name: SMNotification.MemoCellDidShowDeleteBtn, object: nil) } if scrollView.isTracking { return } automateScroll(scrollView) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { return } automateScroll(scrollView) } func automateScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x let newX = offsetX < deleteViewWidth / 2 ? 0 : deleteViewWidth UIView.animate(withDuration: 0.1) { scrollView.contentOffset = CGPoint(x: newX, y: 0) } } func hiddenDeleteButton(withAnimated animated: Bool = true) { let duration: TimeInterval = animated ? 0.2 : 0 UIView.animate(withDuration: duration) { self.scrollView.contentOffset = CGPoint(x: 0, y: 0) } } } // MARK: - DeleteView private class DeleteView: UIView { let deleteBtn = UIButton(type: .custom) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .gray let image = UIImage(named: "ic_trash")?.withRenderingMode(.alwaysTemplate) deleteBtn.setImage(image, for: .normal) deleteBtn.backgroundColor = SMColor.red deleteBtn.layer.masksToBounds = true deleteBtn.tintColor = SMColor.backgroundGray addSubview(deleteBtn) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate override func layoutSubviews() { super.layoutSubviews() let margin: CGFloat = 12 let btnWidth = width - margin * 2 let btnY = (height - btnWidth) / 2 deleteBtn.frame = CGRect(x: margin, y: btnY, width: btnWidth, height: btnWidth) deleteBtn.layer.cornerRadius = deleteBtn.width / 2 } }
4e734ed6705818beb03f9ecebd6dde1e
29.747934
174
0.722484
false
false
false
false
rlisle/Patriot-iOS
refs/heads/master
Patriot/PhotonManager.swift
bsd-3-clause
1
// // PhotonManager.swift // Patriot // // This class manages the collection of Photon devices // // Discovery will search for all the Photon devices on the network. // When a new device is found, it will be added to the photons collection // and a delegate or notification sent. // This is the anticipated way of updating displays, etc. // // The current activity state will be gleaned from the exposed Activities // properties of one or more Photons initially, but then tracked directly // after initialization by subscribing to particle events. // Subscribing to particle events will also allow detecting new Photons // as they come online and start issuing 'alive' events. // // This file uses the Particle SDK: // https://docs.particle.io/reference/ios/#common-tasks // // Created by Ron Lisle on 11/13/16. // Copyright © 2016, 2017 Ron Lisle. All rights reserved. // import Foundation import Particle_SDK import PromiseKit protocol PhotonDelegate { func device(named: String, hasDevices: Set<String>) func device(named: String, supports: Set<String>) func device(named: String, hasSeenActivities: [String: Int]) } enum ParticleSDKError : Error { case invalidUserPassword case invalidToken } class PhotonManager: NSObject, HwManager { var subscribeHandler: Any? var deviceDelegate: DeviceNotifying? var activityDelegate: ActivityNotifying? var photons: [String: Photon] = [: ] // All the particle devices attached to logged-in user's account let eventName = "patriot" var deviceNames = Set<String>() // Names exposed by the "Devices" variables var supportedNames = Set<String>() // Activity names exposed by the "Supported" variables var currentActivities: [String: Int] = [: ] // List of currently on activities reported by Master /** * Login to the particle.io account * The particle SDK will use the returned token in subsequent calls. * We don't have to save it. */ func login(user: String, password: String) -> Promise<Void> { return Promise { fulfill, reject in ParticleCloud.sharedInstance().login(withUser: user, password: password) { (error) in if let error = error { return reject(error) } return fulfill(()) } } } @discardableResult func discoverDevices() -> Promise<Void> { return getAllPhotonDevices() } /** * Locate all the particle.io devices */ func getAllPhotonDevices() -> Promise<Void> { return Promise { fulfill, reject in ParticleCloud.sharedInstance().getDevices { (devices: [ParticleDevice]?, error: Error?) in if error != nil { print("Error: \(error!)") reject(error!) } else { self.addAllPhotonsToCollection(devices: devices) .then { _ -> Void in print("All photons added to collection") self.activityDelegate?.supportedListChanged() fulfill(()) }.catch { error in reject(error) } } } } } func addAllPhotonsToCollection(devices: [ParticleDevice]?) -> Promise<Void> { self.photons = [: ] var promises = [Promise<Void>]() if let particleDevices = devices { for device in particleDevices { if isValidPhoton(device) { if let name = device.name?.lowercased() { print("Adding photon \(name) to collection") let photon = Photon(device: device) photon.delegate = self self.photons[name] = photon self.deviceDelegate?.deviceFound(name: name) let promise = photon.refresh() promises.append(promise) } } } return when(fulfilled: promises) } return Promise(error: NSError(domain: "No devices", code: 0, userInfo: nil)) } func isValidPhoton(_ device: ParticleDevice) -> Bool { return device.connected } func getPhoton(named: String) -> Photon? { let lowerCaseName = named.lowercased() let photon = photons[lowerCaseName] return photon } func sendCommand(activity: String, percent: Int) { print("sendCommand: \(activity) percent: \(percent)") let data = activity + ":" + String(percent) print("Publishing event: \(eventName) data: \(data)") ParticleCloud.sharedInstance().publishEvent(withName: eventName, data: data, isPrivate: true, ttl: 60) { (error:Error?) in if let e = error { print("Error publishing event \(e.localizedDescription)") } } } func subscribeToEvents() { subscribeHandler = ParticleCloud.sharedInstance().subscribeToMyDevicesEvents(withPrefix: eventName, handler: { (event: ParticleEvent?, error: Error?) in if let _ = error { print("Error subscribing to events") } else { DispatchQueue.main.async(execute: { //print("Subscribe: received event with data \(String(describing: event?.data))") if let eventData = event?.data { let splitArray = eventData.components(separatedBy: ":") let name = splitArray[0].lowercased() if let percent: Int = Int(splitArray[1]), percent >= 0, percent <= 100 { self.activityDelegate?.activityChanged(name: name, percent: percent) } else { // print("Event data is not a valid number") } } }) } }) } } extension PhotonManager { // private func parseSupportedNames(_ supported: String) -> Set<String> // { // print("6. Parsing supported names: \(supported)") // var newSupported: Set<String> = [] // let items = supported.components(separatedBy: ",") // for item in items // { // let lcItem = item.localizedLowercase // print("7. New supported = \(lcItem)") // newSupported.insert(lcItem) // } // // return newSupported // } // func refreshCurrentActivities() // { // print("8. refreshCurrentActivities") // currentActivities = [: ] // for (name, photon) in photons // { // let particleDevice = photon.particleDevice // if particleDevice?.variables["Activities"] != nil // { // print("9. reading Activities variable from \(name)") // particleDevice?.getVariable("Activities") { (result: Any?, error: Error?) in // if error == nil // { // if let activities = result as? String, activities != "" // { // print("10. Activities = \(activities)") // let items = activities.components(separatedBy: ",") // for item in items // { // let parts = item.components(separatedBy: ":") // self.currentActivities[parts[0]] = parts[1] //// self.activityDelegate?.activityChanged(event: item) // } // } // } else { // print("Error reading Supported variable. Skipping this device.") // } // print("11. Updated Supported names = \(self.supportedNames)") // self.activityDelegate?.supportedListChanged() // } // } // } // } } // These methods report the capabilities of each photon asynchronously extension PhotonManager: PhotonDelegate { func device(named: String, hasDevices: Set<String>) { print("device named \(named) hasDevices \(hasDevices)") deviceNames = deviceNames.union(hasDevices) } func device(named: String, supports: Set<String>) { print("device named \(named) supports \(supports)") supportedNames = supportedNames.union(supports) } func device(named: String, hasSeenActivities: [String: Int]) { print("device named \(named) hasSeenActivities \(hasSeenActivities)") hasSeenActivities.forEach { (k,v) in currentActivities[k] = v } } } extension PhotonManager { func readVariable(device: ParticleDevice, name: String) -> Promise<String> { return Promise { fulfill, reject in device.getVariable("Supported") { (result: Any?, error: Error?) in if let variable = result as? String { fulfill(variable) } else { reject(error!) } } } } }
2036437c4655ab8c1e03a6056d5093f9
32.215753
160
0.525003
false
false
false
false
wl879/SwiftyCss
refs/heads/master
SwiftyCss/SwiftyBox/Debug.swift
mit
1
// Created by Wang Liang on 2017/4/8. // Copyright © 2017年 Wang Liang. All rights reserved. import Foundation import QuartzCore public class Debug: CustomStringConvertible { public var timeTotal: Float = 0 public var output: String? = nil public var send: String? = nil private var value : UInt = 0 private var map = [String : (UInt, String)]() private var timestamp = [Int: [TimeInterval]]() private var queue: DispatchQueue? = nil public var async: Bool { get { return self.queue != nil } set { if newValue { self.queue = DispatchQueue(label: "SwiftyBox.Debug") }else{ self.queue = nil } } } public init( tags: [String: String], output: String? = nil, send: String? = nil, file: String = #file, line: Int = #line) { for (tag, val) in tags { self.define(tag: tag, template: val, file: file, line: line) } self.output = output self.send = send } public final func define(tag: String, template: String, file: String = #file, line: Int = #line) { let hash = tag.hashValue if self.map[tag] != nil { fatalError( Debug._format(template: "✕ SwiftyBox.Debgu define tag % already exist: %file, line %line", contents: [tag], usetime: 0, file: file, method: "", line: line) ) } self.map[tag] = (UInt(1 << (map.count+1)), template) self.timestamp[hash] = [] } public final func enable(_ tag: String...){ for g in tag { if g == "all" { value = 0 for (_, v) in map { value += v.0 } return }else if let v = map[g] { if value & v.0 != v.0 { value += v.0 } } } } public final func enabled(_ tag: String) -> Bool { if let v = map[tag] { if value & v.0 == v.0 { return true } } return false } public final func begin(tag: String, id: Int? = nil) { guard self.enabled(tag) else { return } if id != nil { if timestamp[id!] == nil { timestamp[id!] = [CACurrentMediaTime()] } }else{ timestamp[tag.hashValue]!.append(CACurrentMediaTime()) } } public final func end(tag: String, id: Int? = nil, _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) { guard self.enabled(tag) else { return } let hash = tag.hashValue var usetime: Float = 0 if id != nil { if let t = timestamp[id!]?.first { usetime = Float(Int((CACurrentMediaTime() - t)*100000))/100 } timestamp[id!] = nil } else if timestamp[hash]!.count > 0 { usetime = Float(Int((CACurrentMediaTime() - timestamp[hash]!.removeLast())*100000))/100 } timeTotal += usetime let tmp = map[tag]!.1 if self.async { self.queue?.async { self.echo( Debug._format(template: tmp, contents: contents, usetime: usetime, file: file, method: method, line: line) ) } }else{ self.echo( Debug._format(template: tmp, contents: contents, usetime: usetime, file: file, method: method, line: line) ) } } public final func log(tag: String, _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) { guard self.enabled(tag) else { return } let tmp = map[tag]!.1 if self.async { self.queue?.async { self.echo( Debug._format(template: tmp, contents: contents, usetime: 0, file: file, method: method, line: line) ) } }else{ self.echo( Debug._format(template: tmp, contents: contents, usetime: 0, file: file, method: method, line: line) ) } } public final func log(format: String = "%%", _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) { if self.async { self.queue?.async { self.echo( Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line) ) } }else{ self.echo( Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line) ) } } public final func error(format: String = "%%", _ contents: Any?..., file: String = #file, method: String = #function, line: Int = #line) { if self.async { self.queue?.async { let msg = Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line) self.echo(msg) } }else{ let msg = Debug._format(template: format, contents: contents, usetime: 0, file: file, method: method, line: line) self.echo(msg) } } public final func stringify(_ value: @autoclosure @escaping () -> Any?) -> () -> String { return { Debug._stringify( value() ) } } private final func echo(_ text: String) { print( text ) if self.output != nil { self.queue?.async { if let f = FileHandle(forWritingAtPath: self.output! ) { f.seekToEndOfFile() f.write( text.data(using: .utf8, allowLossyConversion: true)! ) f.closeFile() } } } if self.send != nil { // TODO: send to server } } public final var description: String { var names = [String]() for (name, conf) in map { if value & conf.0 == conf.0 { names.append(name) } } return "<SwiftyBox.Debug Enabel: \(names.joined(separator:", "))>" } // MARK: - private static let _format_re = Re("(%ms|%file|%who|%line|%now|%date|%time)\\b|(\\n(?:[^%]*[>:]\\s*|\\s*))?(%\\[\\]|%%|%)") private static func _format(template:String, contents: [Any?], usetime: Float, file: String, method: String, line: Int) -> String { var text = "" var i = 0 var tmp = template while let m = _format_re.match(tmp) { if m.index > 0 { text += tmp.slice(start:0, end: m.index) } tmp = tmp.slice(start: m.lastIndex+1 ) if !m[1]!.isEmpty { switch m[1]! { case "%file": text += file case "%line": text += line.description case "%who": text += method case "%ms": text += usetime.description + "ms" case "%now": let format = DateFormatter() format.dateFormat = "yyyy-MM-dd HH:mm:ss" text += format.string( from: Date() ) + "ms" case "%date": let format = DateFormatter() format.dateFormat = "yyyy-MM-dd" text += format.string( from: Date() ) + "ms" case "%time": let format = DateFormatter() format.dateFormat = "HH:mm:ss" text += format.string( from: Date() ) + "ms" default: continue } }else{ var temp = "" let prefix = m[2]! var indent = prefix.isEmpty ? "" : Re("[^\\s]").replace(prefix, " ") switch m[3]! { case "%[]": if i < contents.count { if let val = contents[i] { if val is [Any] { let arr = val as! [Any] for i in 0 ..< arr.count { if i != 0 { temp += prefix.isEmpty ? "\n" : prefix } temp += _stringify(arr[i]).replacingOccurrences(of: "\n", with: indent) } indent = "" }else{ temp = _stringify(val) } }else{ temp = "nil" } i += 1 } case "%%": while i < contents.count { temp += " " + _stringify(contents[i]) i += 1 } case "%": if i < contents.count { temp = _stringify(contents[i]) i += 1 } default: continue } if !indent.isEmpty { temp = temp.replacingOccurrences(of: "\n", with: indent) } text += prefix + temp } } text += tmp return text } private static func _stringify(_ value: Any?) -> String { guard let value = value else { return "nil" } let str = String(describing: value) if str == "(Function)" { let type = String(describing: type(of: value)) switch type { case "() -> String": return String(describing: (value as! () -> String)()) case "() -> String?": return String(describing: (value as! () -> String?)() ?? "nil") default: return type } } return str } }
b7e3468611bdcbdb21933d9d8164c516
34.804196
181
0.437793
false
false
false
false
CNKCQ/oschina
refs/heads/master
Pods/Foundation+/Foundation+/Date+.swift
mit
1
// // Date.swift // Elegant // // Created by Steve on 2017/5/18. // Copyright © 2017年 KingCQ. All rights reserved. // import Foundation public extension Date { /// Returns the earlier of the receiver and another given date. /// /// - Parameter date: The date with which to compare the receiver. /// - Returns: The earlier of the receiver func earlierDate(_ date: Date) -> Date { let now = Date() return now < date ? now : date } /// Returns the later of the receiver and another given date. /// /// - Parameter date: The date with which to compare the receiver. /// - Returns: The later of the receiver func laterDate(_ date: Date) -> Date { let now = Date() return now < date ? date : now } /// Takes a past Date and creates a string representation of it. /// /// - Parameters: /// - date: Past date you wish to create a string representation for. /// - numericDates: if true, ex: "1 week ago", else ex: "Last week" /// - Returns: String that represents your date. static func timeAgoSinceDate(_ date: Date, numericDates: Bool) -> String { let calendar = Calendar.current let now = Date() let earliest = now.earlierDate(date) let latest = (earliest == now) ? date : now let components = calendar.dateComponents([.minute, .hour, .day, .weekOfYear, .month, .year, .second], from: earliest, to: latest) if components.year! >= 2 { return "\(String(describing: components.year)) years ago" } else if components.year! >= 1 { if numericDates { return "1 year ago" } else { return "Last year" } } else if components.month! >= 2 { return "\(String(describing: components.month)) months ago" } else if components.month! >= 1 { if numericDates { return "1 month ago" } else { return "Last month" } } else if components.weekOfYear! >= 2 { return "\(String(describing: components.weekOfYear)) weeks ago" } else if components.weekOfYear! >= 1 { if numericDates { return "1 week ago" } else { return "Last week" } } else if components.day! >= 2 { return "\(String(describing: components.day)) days ago" } else if components.day! >= 1 { if numericDates { return "1 day ago" } else { return "Yesterday" } } else if components.hour! >= 2 { return "\(String(describing: components.hour)) hours ago" } else if components.hour! >= 1 { if numericDates { return "1 hour ago" } else { return "An hour ago" } } else if components.minute! >= 2 { return "\(String(describing: components.minute)) minutes ago" } else if components.minute! >= 1 { if numericDates { return "1 minute ago" } else { return "A minute ago" } } else if components.second! >= 3 { return "\(String(describing: components.second)) seconds ago" } else { return "just now" } } }
6c1e8fcb66915c50044e27a88d4ec67b
34.185567
137
0.530911
false
false
false
false
einsteinx2/iSub
refs/heads/master
Classes/Data Model/CachedImage.swift
gpl-3.0
1
// // CachedImage.swift // iSub // // Created by Benjamin Baron on 1/4/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation import Nuke enum CachedImageSize { case cell case player case original var pixelSize: Int { switch self { case .cell: return 120 case .player: return 640 case .original: return -1 } } var name: String { switch self { case .cell: return "cell" case .player: return "player" case .original: return "original" } } } struct CachedImage { static let preheater = Preheater() static func request(coverArtId: String, serverId: Int64, size: CachedImageSize) -> Request? { var parameters = ["id": coverArtId] if size != .original { parameters["size"] = "\(size.pixelSize)" } let fragment = "s_\(serverId)_id_\(coverArtId)_size_\(size.name)" if let urlRequest = URLRequest(subsonicAction: .getCoverArt, serverId: serverId, parameters: parameters, fragment: fragment) { var request = Request(urlRequest: urlRequest) request.cacheKey = fragment request.loadKey = fragment return request } return nil } static func preheat(coverArtId: String, serverId: Int64, size: CachedImageSize) { if let request = self.request(coverArtId: coverArtId, serverId: serverId, size: size) { preheater.startPreheating(with: [request]) } } static func cached(coverArtId: String, serverId: Int64, size: CachedImageSize) -> UIImage? { if let request = self.request(coverArtId: coverArtId, serverId: serverId, size: size) { let image = Cache.shared[request] return image } return nil } static func `default`(forSize size: CachedImageSize) -> UIImage { switch size { case .cell: return UIImage(named: "default-album-art-small")! case .player, .original: return UIImage(named: "default-album-art")! } } // static fileprivate func key(forCoverArtId coverArtId: String, serverId: Int, size: CachedImageSize) -> String { // let fragment = "s_\(serverId)_id_\(coverArtId)_size_\(size.name)" // } // // static fileprivate func imageFromDiskCache(coverArtId: String) -> UIImage { // return CacheManager.si.imageCache?.object(forKey: coverArtId) // } }
cfd564dab9b4b02058f3ebde26f5b07b
30.1875
134
0.608016
false
false
false
false
camdenfullmer/UnsplashSwift
refs/heads/master
Source/Extensions.swift
mit
1
// Extensions.swift // // Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension UIColor { static func colorWithHexString(hex: String) -> UIColor { guard hex.hasPrefix("#") else { return UIColor.blackColor() } guard let hexString: String = hex.substringFromIndex(hex.startIndex.advancedBy(1)), var hexValue: UInt32 = 0 where NSScanner(string: hexString).scanHexInt(&hexValue) else { return UIColor.blackColor() } guard hexString.characters.count == 6 else { return UIColor.blackColor() } let divisor = CGFloat(255) let red = CGFloat((hexValue & 0xFF0000) >> 16) / divisor let green = CGFloat((hexValue & 0x00FF00) >> 8) / divisor let blue = CGFloat( hexValue & 0x0000FF ) / divisor return UIColor(red: red, green: green, blue: blue, alpha: 1) } } extension NSURL { var queryPairs : [String : String] { var results = [String: String]() let pairs = self.query?.componentsSeparatedByString("&") ?? [] for pair in pairs { let kv = pair.componentsSeparatedByString("=") results.updateValue(kv[1], forKey: kv[0]) } return results } }
2e8412e422212d02aaa12db037e892f0
39.416667
91
0.657732
false
false
false
false
Ferrari-lee/News-YC---iPhone
refs/heads/master
HN/CustomViews/Cells/Posts/HNPostsCollectionCell.swift
mit
5
// // HNPostsCollectionCell.swift // HN // // Created by Ben Gordon on 9/9/14. // Copyright (c) 2014 bennyguitar. All rights reserved. // import UIKit let HNPostsCollectionCellIdentifier = "HNPostsCollectionCellIdentifier" protocol HNPostsCellDelegate { func didSelectComments(index: Int) } class HNPostsCollectionCell: UITableViewCell { @IBOutlet var cellTitleLabel : UILabel! @IBOutlet var cellAuthorLabel : UILabel! @IBOutlet var cellPointsLabel : UILabel! @IBOutlet weak var cellBottomBar: UIView! @IBOutlet weak var commentBubbleButton: UIButton! @IBOutlet weak var commentCountLabel: UILabel! @IBOutlet weak var commentButtonOverlay: UIButton! var index: Int = -1 var del: HNPostsCellDelegate? = nil override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(false, animated: false) } override func setHighlighted(highlighted: Bool, animated: Bool) { super.setHighlighted(false, animated: false) } func setContentWithPost(post: HNPost?, indexPath: NSIndexPath?, delegate: HNPostsCellDelegate) { index = indexPath!.row del = delegate cellAuthorLabel.attributedText = postSecondaryAttributedString("\(post!.TimeCreatedString) by \(post!.Username)", matches:post!.Username) cellTitleLabel.attributedText = postPrimaryAttributedString(post!.Title) cellBottomBar.backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.Bar) commentBubbleButton.setImage(HNTheme.currentTheme().imageForCommentBubble(), forState: UIControlState.Normal) commentCountLabel.text = "\(post!.CommentCount)" commentBubbleButton.addTarget(self, action: "didSelectCommentsButton", forControlEvents: UIControlEvents.TouchUpInside) commentButtonOverlay.addTarget(self, action: "didSelectCommentsButton", forControlEvents: UIControlEvents.TouchUpInside) // Alphas commentBubbleButton.alpha = 0.25 commentCountLabel.alpha = 1.0 cellTitleLabel.alpha = HNTheme.currentTheme().markAsReadIsActive() && HNManager.sharedManager().hasUserReadPost(post) ? 0.5 : 1.0 //commentCountLabel.textColor = HNOrangeColor // UI Coloring // Show HN posts contain "Show HN:" in the title // Other posts do not. Jobs posts are of type PostType.Jobs let t = NSString(string: post!.Title) if (t.contains("Show HN:")) { // Show HN backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.ShowHNBackground) cellBottomBar.backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.ShowHNBar) } else { // Jobs Post if (post?.Type == PostType.Jobs) { backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.JobsBackground) cellBottomBar.backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.JobsBar) commentBubbleButton.alpha = 0.0 commentCountLabel.alpha = 0.0 cellAuthorLabel.attributedText = postSecondaryAttributedString("HN Jobs", matches: nil) } // Normal else { backgroundColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.BackgroundColor) } } // Backgrounds cellTitleLabel.backgroundColor = backgroundColor cellAuthorLabel.backgroundColor = cellBottomBar.backgroundColor commentCountLabel.textColor = HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.MainFont) // Set Edge Insets if (self.respondsToSelector(Selector("layoutMargins"))) { layoutMargins = UIEdgeInsetsZero } } func postPrimaryAttributedString(t: String!) -> NSAttributedString { return NSAttributedString(string: t, attributes: [NSForegroundColorAttributeName:HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.MainFont),NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSParagraphStyleAttributeName:NSParagraphStyle.defaultParagraphStyle()]) } func postSecondaryAttributedString(text: String!, matches: String?) -> NSAttributedString { return NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName:HNTheme.currentTheme().colorForUIElement(HNTheme.ThemeUIElement.SubFont),NSFontAttributeName:UIFont.systemFontOfSize(11.0)]) } func didSelectCommentsButton() { del?.didSelectComments(index) } }
cc3711cd079a5d44cb5ed1e5419c3362
44.951923
285
0.702867
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Models/TextTransformer.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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 public struct TextTransformer { private static var usernameDetector: NSRegularExpression = { do { return try NSRegularExpression(pattern: " ?(@[a-z][a-z0-9_]{2,59}) ?", options: [.caseInsensitive, .useUnicodeWordBoundaries]) } catch { fatalError("Couldn't instantiate usernameDetector, invalid pattern for regular expression") } }() public static func attributedUsernameString(to string: String?, textColor: UIColor, linkColor: UIColor, font: UIFont) -> NSAttributedString? { guard let string = string else { return nil } let attributedText = NSMutableAttributedString(string: string, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]) // string.count returns the number of rendered characters on a string // but NSAttributedString attributes operate on the utf16 codepoints. // If a string is using clusters such as emoji, the range will mismatch. // A visible side-effect of this miscounted string length was usernames // at the end of strings with emoji not being matched completely. let range = NSRange(location: 0, length: attributedText.string.utf16.count) attributedText.addAttributes([.kern: -0.4], range: range) // Do a link detector first-pass, to avoid creating username links inside URLs that contain an @ sign. let linkDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) let links = linkDetector!.matches(in: attributedText.string, options: [], range: range).reversed() var excludedRanges = [NSRange]() for link in links { excludedRanges.append(link.range) } // It's always good practice to traverse and modify strings from the end to the start. // If any of those changes affect the string length, all the subsequent ranges will be invalidated // causing all sort of hard to diagnose problems. let matches = usernameDetector.matches(in: attributedText.string, options: [], range: range).reversed() for match in matches { let matchRange = match.range(at: 1) // Ignore if our username regex matched inside a URL exclusion range. guard excludedRanges.compactMap({ r -> NSRange? in return matchRange.intersection(r) }).isEmpty else { continue } let attributes: [NSAttributedStringKey: Any] = [ .link: "toshi://username:\((attributedText.string as NSString).substring(with: matchRange))", .foregroundColor: linkColor, .underlineStyle: NSUnderlineStyle.styleSingle.rawValue ] attributedText.addAttributes(attributes, range: matchRange) } return attributedText } }
199c18775006b1d77d274e0fe88b285b
50.376812
168
0.691678
false
false
false
false
JGiola/swift-package-manager
refs/heads/master
Sources/PackageDescription4/Version+StringLiteralConvertible.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright (c) 2018 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ extension Version: ExpressibleByStringLiteral { public init(stringLiteral value: String) { if let version = Version(value) { self.init(version) } else { // If version can't be initialized using the string literal, report // the error and initialize with a dummy value. This is done to // report error to the invoking tool (like swift build) gracefully // rather than just crashing. errors.append("Invalid version string: \(value)") self.init(0, 0, 0) } } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } } extension Version { public init(_ version: Version) { major = version.major minor = version.minor patch = version.patch prereleaseIdentifiers = version.prereleaseIdentifiers buildMetadataIdentifiers = version.buildMetadataIdentifiers } public init?(_ versionString: String) { let prereleaseStartIndex = versionString.index(of: "-") let metadataStartIndex = versionString.index(of: "+") let requiredEndIndex = prereleaseStartIndex ?? metadataStartIndex ?? versionString.endIndex let requiredCharacters = versionString.prefix(upTo: requiredEndIndex) let requiredComponents = requiredCharacters .split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false) .map(String.init) .compactMap({ Int($0) }) .filter({ $0 >= 0 }) guard requiredComponents.count == 3 else { return nil } self.major = requiredComponents[0] self.minor = requiredComponents[1] self.patch = requiredComponents[2] func identifiers(start: String.Index?, end: String.Index) -> [String] { guard let start = start else { return [] } let identifiers = versionString[versionString.index(after: start)..<end] return identifiers.split(separator: ".").map(String.init) } self.prereleaseIdentifiers = identifiers( start: prereleaseStartIndex, end: metadataStartIndex ?? versionString.endIndex) self.buildMetadataIdentifiers = identifiers(start: metadataStartIndex, end: versionString.endIndex) } }
637e0a978d95824f4fde0a3d7a88897c
36.135135
107
0.657569
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/IRGen/class_bounded_generics.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // XFAIL: linux protocol ClassBound : class { func classBoundMethod() } protocol ClassBound2 : class { func classBoundMethod2() } protocol ClassBoundBinary : ClassBound { func classBoundBinaryMethod(_ x: Self) } @objc protocol ObjCClassBound { func objCClassBoundMethod() } @objc protocol ObjCClassBound2 { func objCClassBoundMethod2() } protocol NotClassBound { func notClassBoundMethod() func notClassBoundBinaryMethod(_ x: Self) } struct ClassGenericFieldStruct<T:ClassBound> { var x : Int var y : T var z : Int } struct ClassProtocolFieldStruct { var x : Int var y : ClassBound var z : Int } class ClassGenericFieldClass<T:ClassBound> { final var x : Int = 0 final var y : T final var z : Int = 0 init(t: T) { y = t } } class ClassProtocolFieldClass { var x : Int = 0 var y : ClassBound var z : Int = 0 init(classBound cb: ClassBound) { y = cb } } // CHECK: %T22class_bounded_generics017ClassGenericFieldD0C = type <{ %swift.refcounted, %TSi, %objc_object*, %TSi }> // CHECK: %T22class_bounded_generics23ClassGenericFieldStructV = type <{ %TSi, %objc_object*, %TSi }> // CHECK: %T22class_bounded_generics24ClassProtocolFieldStructV = type <{ %TSi, %T22class_bounded_generics10ClassBoundP, %TSi }> // CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype<T : ClassBound>(_ x: T) -> T { return x } class SomeClass {} class SomeSubclass : SomeClass {} // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics9SomeClassC* @_T022class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC*, %swift.type* %T) func superclass_bounded_archetype<T : SomeClass>(_ x: T) -> T { return x } // CHECK-LABEL: define hidden swiftcc { %T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC* } @_T022class_bounded_generics011superclass_B15_archetype_call{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC*, %T22class_bounded_generics12SomeSubclassC*) func superclass_bounded_archetype_call(_ x: SomeClass, y: SomeSubclass) -> (SomeClass, SomeSubclass) { return (superclass_bounded_archetype(x), superclass_bounded_archetype(y)); // CHECK: [[SOMECLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @_T022class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC* {{%.*}}, {{.*}}) // CHECK: [[SOMESUPERCLASS_IN:%.*]] = bitcast %T22class_bounded_generics12SomeSubclassC* {{%.*}} to %T22class_bounded_generics9SomeClassC* // CHECK: [[SOMESUPERCLASS_RESULT:%.*]] = call swiftcc %T22class_bounded_generics9SomeClassC* @_T022class_bounded_generics011superclass_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_IN]], {{.*}}) // CHECK: bitcast %T22class_bounded_generics9SomeClassC* [[SOMESUPERCLASS_RESULT]] to %T22class_bounded_generics12SomeSubclassC* } // CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics0a1_B17_archetype_method{{[_0-9a-zA-Z]*}}F(%objc_object*, %objc_object*, %swift.type* %T, i8** %T.ClassBoundBinary) func class_bounded_archetype_method<T : ClassBoundBinary>(_ x: T, y: T) { x.classBoundMethod() // CHECK: [[INHERITED:%.*]] = load i8*, i8** %T.ClassBoundBinary, align 8 // CHECK: [[INHERITED_WTBL:%.*]] = bitcast i8* [[INHERITED]] to i8** // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[INHERITED_WTBL]], align 8 // CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**) // CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* swiftself %0, %swift.type* {{.*}}, i8** [[INHERITED_WTBL]]) x.classBoundBinaryMethod(y) // CHECK: [[WITNESS_ENTRY:%.*]] = getelementptr inbounds i8*, i8** %T.ClassBoundBinary, i32 1 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ENTRY]], align 8 // CHECK: [[WITNESS_FUNC:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %objc_object*, %swift.type*, i8**) // CHECK: call %objc_object* @swift_unknownRetain(%objc_object* returned [[Y:%.*]]) // CHECK: call swiftcc void [[WITNESS_FUNC]](%objc_object* [[Y]], %objc_object* swiftself %0, %swift.type* %T, i8** %T.ClassBoundBinary) } // CHECK-LABEL: define hidden swiftcc { %objc_object*, %objc_object* } @_T022class_bounded_generics0a1_B16_archetype_tuple{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype_tuple<T : ClassBound>(_ x: T) -> (T, T) { return (x, x) } class ConcreteClass : ClassBoundBinary, NotClassBound { func classBoundMethod() {} func classBoundBinaryMethod(_ x: ConcreteClass) {} func notClassBoundMethod() {} func notClassBoundBinaryMethod(_ x: ConcreteClass) {} } // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @_T022class_bounded_generics05call_a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics13ConcreteClassC*) {{.*}} { func call_class_bounded_archetype(_ x: ConcreteClass) -> ConcreteClass { return class_bounded_archetype(x) // CHECK: [[IN:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* {{%.*}} to %objc_object* // CHECK: [[OUT_ORIG:%.*]] = call swiftcc %objc_object* @_T022class_bounded_generics0a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%objc_object* [[IN]], {{.*}}) // CHECK: [[OUT:%.*]] = bitcast %objc_object* [[OUT_ORIG]] to %T22class_bounded_generics13ConcreteClassC* // CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]] } // CHECK: define hidden swiftcc void @_T022class_bounded_generics04not_a1_B10_archetype{{[_0-9a-zA-Z]*}}F(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.NotClassBound) func not_class_bounded_archetype<T : NotClassBound>(_ x: T) -> T { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics0a1_b18_archetype_to_not_a1_B0{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound, i8** %T.NotClassBound) {{.*}} { func class_bounded_archetype_to_not_class_bounded <T: ClassBound & NotClassBound>(_ x:T) -> T { // CHECK: alloca %objc_object*, align 8 return not_class_bounded_archetype(x) } /* TODO Abstraction remapping to non-class-bounded witnesses func class_and_not_class_bounded_archetype_methods <T: ClassBound & NotClassBound>(_ x:T, y:T) { x.classBoundMethod() x.classBoundBinaryMethod(y) x.notClassBoundMethod() x.notClassBoundBinaryMethod(y) } */ // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics0a1_B8_erasure{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics13ConcreteClassC*) {{.*}} { func class_bounded_erasure(_ x: ConcreteClass) -> ClassBound { return x // CHECK: [[INSTANCE_OPAQUE:%.*]] = bitcast %T22class_bounded_generics13ConcreteClassC* [[INSTANCE:%.*]] to %objc_object* // CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* [[INSTANCE_OPAQUE]], 0 // CHECK: [[T1:%.*]] = insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @_T022class_bounded_generics13ConcreteClassCAA0E5BoundAAWP, i32 0, i32 0), 1 // CHECK: ret { %objc_object*, i8** } [[T1]] } // CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics0a1_B16_protocol_method{{[_0-9a-zA-Z]*}}F(%objc_object*, i8**) {{.*}} { func class_bounded_protocol_method(_ x: ClassBound) { x.classBoundMethod() // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getObjectType(%objc_object* %0) // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_TABLE:%.*]], align 8 // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] to void (%objc_object*, %swift.type*, i8**) // CHECK: call swiftcc void [[WITNESS_FN]](%objc_object* swiftself %0, %swift.type* [[METADATA]], i8** [[WITNESS_TABLE]]) } // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @_T022class_bounded_generics0a1_B15_archetype_cast{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, i8** %T.ClassBound) func class_bounded_archetype_cast<T : ClassBound>(_ x: T) -> ConcreteClass { return x as! ConcreteClass // CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8* // CHECK: [[T0:%.*]] = call %swift.type* @_T022class_bounded_generics13ConcreteClassCMa() // CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8* // CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]]) // CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC* // CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]] } // CHECK-LABEL: define hidden swiftcc %T22class_bounded_generics13ConcreteClassC* @_T022class_bounded_generics0a1_B14_protocol_cast{{[_0-9a-zA-Z]*}}F(%objc_object*, i8**) func class_bounded_protocol_cast(_ x: ClassBound) -> ConcreteClass { return x as! ConcreteClass // CHECK: [[IN_PTR:%.*]] = bitcast %objc_object* {{%.*}} to i8* // CHECK: [[T0:%.*]] = call %swift.type* @_T022class_bounded_generics13ConcreteClassCMa() // CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to i8* // CHECK: [[OUT_PTR:%.*]] = call i8* @swift_dynamicCastClassUnconditional(i8* [[IN_PTR]], i8* [[T1]]) // CHECK: [[OUT:%.*]] = bitcast i8* [[OUT_PTR]] to %T22class_bounded_generics13ConcreteClassC* // CHECK: ret %T22class_bounded_generics13ConcreteClassC* [[OUT]] } // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics0a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**, i8**) {{.*}} { func class_bounded_protocol_conversion_1(_ x: ClassBound & ClassBound2) -> ClassBound { return x } // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics0a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**, i8**) {{.*}} { func class_bounded_protocol_conversion_2(_ x: ClassBound & ClassBound2) -> ClassBound2 { return x } // CHECK-LABEL: define hidden swiftcc { %objc_object*, i8** } @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**) {{.*}} { func objc_class_bounded_protocol_conversion_1 (_ x: ClassBound & ObjCClassBound) -> ClassBound { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*, i8**) {{.*}} { func objc_class_bounded_protocol_conversion_2 (_ x: ClassBound & ObjCClassBound) -> ObjCClassBound { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*) func objc_class_bounded_protocol_conversion_3 (_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound { return x } // CHECK-LABEL: define hidden swiftcc %objc_object* @_T022class_bounded_generics05objc_a1_B22_protocol_conversion_{{.*}}(%objc_object*) func objc_class_bounded_protocol_conversion_4 (_ x: ObjCClassBound & ObjCClassBound2) -> ObjCClassBound2 { return x } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @_T022class_bounded_generics0A28_generic_field_struct_fields{{[_0-9a-zA-Z]*}}F(i64, %objc_object*, i64, %swift.type* %T, i8** %T.ClassBound) func class_generic_field_struct_fields<T> (_ x:ClassGenericFieldStruct<T>) -> (Int, T, Int) { return (x.x, x.y, x.z) } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @_T022class_bounded_generics0A29_protocol_field_struct_fields{{[_0-9a-zA-Z]*}}F(i64, %objc_object*, i8**, i64) func class_protocol_field_struct_fields (_ x:ClassProtocolFieldStruct) -> (Int, ClassBound, Int) { return (x.x, x.y, x.z) } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i64 } @_T022class_bounded_generics0a15_generic_field_A7_fields{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics017ClassGenericFieldD0C*) func class_generic_field_class_fields<T> (_ x:ClassGenericFieldClass<T>) -> (Int, T, Int) { return (x.x, x.y, x.z) // CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 1 // CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 2 // CHECK: getelementptr inbounds %T22class_bounded_generics017ClassGenericFieldD0C, %T22class_bounded_generics017ClassGenericFieldD0C* %0, i32 0, i32 3 } // CHECK-LABEL: define hidden swiftcc { i64, %objc_object*, i8**, i64 } @_T022class_bounded_generics0a16_protocol_field_A7_fields{{[_0-9a-zA-Z]*}}F(%T22class_bounded_generics018ClassProtocolFieldD0C*) func class_protocol_field_class_fields(_ x: ClassProtocolFieldClass) -> (Int, ClassBound, Int) { return (x.x, x.y, x.z) // CHECK: = call swiftcc i64 %{{[0-9]+}} // CHECK: = call swiftcc { %objc_object*, i8** } %{{[0-9]+}} // CHECK: = call swiftcc i64 %{{[0-9]+}} } class SomeSwiftClass { class func foo() {} } // T must have a Swift layout, so we can load this metatype with a direct access. // CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics0a1_B9_metatype{{[_0-9a-zA-Z]*}}F // CHECK: [[T0:%.*]] = getelementptr inbounds %T22class_bounded_generics14SomeSwiftClassC, %T22class_bounded_generics14SomeSwiftClassC* {{%.*}}, i32 0, i32 0, i32 0 // CHECK-NEXT: [[T1:%.*]] = load %swift.type*, %swift.type** [[T0]], align 8 // CHECK-NEXT: [[T2:%.*]] = bitcast %swift.type* [[T1]] to void (%swift.type*)** // CHECK-NEXT: [[T3:%.*]] = getelementptr inbounds void (%swift.type*)*, void (%swift.type*)** [[T2]], i64 10 // CHECK-NEXT: load void (%swift.type*)*, void (%swift.type*)** [[T3]], align 8 func class_bounded_metatype<T: SomeSwiftClass>(_ t : T) { type(of: t).foo() } class WeakRef<T: AnyObject> { weak var value: T? } class A<T> { required init() {} } class M<T, S: A<T>> { private var s: S init() { // Don't crash generating the reference to 's'. s = S.init() } } // CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type*, %swift.type* %T) func takes_metatype<T>(_: T.Type) {} // CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraintyx1t_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2*, %swift.type* %T) // CHECK: [[ISA_ADDR:%.*]] = bitcast %T22class_bounded_generics1AC.2* %0 to %swift.type** // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type* %T, %swift.type* %T) // CHECK-NEXT: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type** // CHECK-NEXT: [[U_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10 // CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[U_ADDR]] // CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type* %U, %swift.type* %U) // CHECK: ret void func archetype_with_generic_class_constraint<T, U>(t: T) where T : A<U> { takes_metatype(T.self) takes_metatype(U.self) } // CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics029calls_archetype_with_generic_A11_constraintyAA1ACyxG1a_tlF(%T22class_bounded_generics1AC*) #0 { // CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T22class_bounded_generics1AC, %T22class_bounded_generics1AC* %0, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK: [[SELF:%.*]] = bitcast %T22class_bounded_generics1AC* %0 to %T22class_bounded_generics1AC.2* // CHECK-NEXT: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type** // CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]] // CHECK-NEXT: [[A_OF_T:%.*]] = call %swift.type* @_T022class_bounded_generics1ACMa(%swift.type* [[T]]) // CHECK-NEXT: call swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraintyx1t_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2* [[SELF]], %swift.type* [[A_OF_T]]) // CHECK: ret void func calls_archetype_with_generic_class_constraint<T>(a: A<T>) { archetype_with_generic_class_constraint(t: a) }
d4b292bbcb72fc8d4765d6781f167942
52.457792
287
0.685636
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/UIImage+Extensions.swift
apache-2.0
1
// // UIImage+Extensions.swift // Slide for Reddit // // Created by Jonathan Cole on 6/26/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import UIKit extension UIImage { func getCopy(withSize size: CGSize) -> UIImage { let maxWidth = size.width let maxHeight = size.height let imgWidth = self.size.width let imgHeight = self.size.height let widthRatio = maxWidth / imgWidth let heightRatio = maxHeight / imgHeight let bestRatio = min(widthRatio, heightRatio) let newWidth = imgWidth * bestRatio, newHeight = imgHeight * bestRatio let biggerSize = CGSize(width: newWidth, height: newHeight) var newImage: UIImage if #available(iOS 10.0, *) { let renderFormat = UIGraphicsImageRendererFormat.default() renderFormat.opaque = false let renderer = UIGraphicsImageRenderer(size: CGSize(width: biggerSize.width, height: biggerSize.height), format: renderFormat) newImage = renderer.image { (_) in self.draw(in: CGRect(x: 0, y: 0, width: biggerSize.width, height: biggerSize.height)) } } else { UIGraphicsBeginImageContextWithOptions(CGSize(width: biggerSize.width, height: biggerSize.height), false, 0) self.draw(in: CGRect(x: 0, y: 0, width: biggerSize.width, height: biggerSize.height)) newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() } return newImage } func cropImageByAlpha() -> UIImage { let cgImage = self.cgImage let context = createARGBBitmapContextFromImage(inImage: cgImage!) let height = cgImage!.height let width = cgImage!.width var rect: CGRect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)) context?.draw(cgImage!, in: rect) let pixelData = self.cgImage!.dataProvider!.data let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) var minX = width var minY = height var maxX: Int = 0 var maxY: Int = 0 //Filter through data and look for non-transparent pixels. for y in 0..<height { for x in 0..<width { let pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */ if data[Int(pixelIndex)] != 0 { //Alpha value is not zero pixel is not transparent. if x < minX { minX = x } if x > maxX { maxX = x } if y < minY { minY = y } if y > maxY { maxY = y } } } } rect = CGRect( x: CGFloat(minX), y: CGFloat(minY), width: CGFloat(maxX - minX), height: CGFloat(maxY - minY)) let imageScale: CGFloat = self.scale let cgiImage = self.cgImage?.cropping(to: rect) return UIImage(cgImage: cgiImage!, scale: imageScale, orientation: self.imageOrientation) } private func createARGBBitmapContextFromImage(inImage: CGImage) -> CGContext? { let width = cgImage!.width let height = cgImage!.height let bitmapBytesPerRow = width * 4 let bitmapByteCount = bitmapBytesPerRow * height let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapData = malloc(bitmapByteCount) if bitmapData == nil { return nil } let context = CGContext(data: bitmapData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) return context } convenience init?(sfString: SFSymbol, overrideString: String) { if #available(iOS 13, *) { let config = UIImage.SymbolConfiguration(pointSize: 15, weight: UIImage.SymbolWeight.regular, scale: UIImage.SymbolScale.small) self.init(systemName: sfString.rawValue, withConfiguration: config) } else { self.init(named: overrideString) } } convenience init?(sfStringHQ: SFSymbol, overrideString: String) { if #available(iOS 13, *) { let config = UIImage.SymbolConfiguration(pointSize: 30, weight: UIImage.SymbolWeight.regular, scale: UIImage.SymbolScale.large) self.init(systemName: sfStringHQ.rawValue, withConfiguration: config) } else { self.init(named: overrideString) } } func getCopy(withColor color: UIColor) -> UIImage { if #available(iOS 10, *) { let renderer = UIGraphicsImageRenderer(size: size) return renderer.image { context in color.setFill() self.draw(at: .zero) context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height), blendMode: .sourceAtop) } } else { var image = withRenderingMode(.alwaysTemplate) UIGraphicsBeginImageContextWithOptions(size, false, scale) color.set() image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } func getCopy(withSize size: CGSize, withColor color: UIColor) -> UIImage { return self.getCopy(withSize: size).getCopy(withColor: color) } // TODO: - These should make only one copy and do in-place operations on those func navIcon(_ white: Bool = false) -> UIImage { return self.getCopy(withSize: CGSize(width: 25, height: 25), withColor: SettingValues.reduceColor && !white ? ColorUtil.theme.navIconColor : .white) } func smallIcon() -> UIImage { return self.getCopy(withSize: CGSize(width: 12, height: 12), withColor: ColorUtil.theme.navIconColor) } func toolbarIcon() -> UIImage { return self.getCopy(withSize: CGSize(width: 25, height: 25), withColor: ColorUtil.theme.navIconColor) } func menuIcon() -> UIImage { return self.getCopy(withSize: CGSize(width: 20, height: 20), withColor: ColorUtil.theme.navIconColor) } func cropToBounds(image: UIImage, width: Double, height: Double) -> UIImage { let contextImage: UIImage = UIImage(cgImage: image.cgImage!) let contextSize: CGSize = contextImage.size var posX: CGFloat = 0.0 var posY: CGFloat = 0.0 var cgwidth: CGFloat = CGFloat(width) var cgheight: CGFloat = CGFloat(height) // See what size is longer and create the center off of that if contextSize.width > contextSize.height { posX = ((contextSize.width - contextSize.height) / 2) posY = 0 cgwidth = contextSize.height cgheight = contextSize.height } else { posX = 0 posY = ((contextSize.height - contextSize.width) / 2) cgwidth = contextSize.width cgheight = contextSize.width } let rect: CGRect = CGRect.init(x: posX, y: posY, width: cgwidth, height: cgheight) // Create bitmap image from context using the rect let imageRef: CGImage = (contextImage.cgImage?.cropping(to: rect)!)! // Create a new image based on the imageRef and rotate back to the original orientation let image: UIImage = UIImage.init(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation) return image } public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat) -> UIImage { let newWidth = size.width < posX + image.size.width ? posX + image.size.width : size.width let newHeight = size.height < posY + image.size.height ? posY + image.size.height : size.height let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) draw(in: CGRect(origin: CGPoint.zero, size: size)) image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: image.size)) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } class func convertGradientToImage(colors: [UIColor], frame: CGSize) -> UIImage { let rect = CGRect.init(x: 0, y: 0, width: frame.width, height: frame.height) // start with a CAGradientLayer let gradientLayer = CAGradientLayer() gradientLayer.frame = rect // add colors as CGCologRef to a new array and calculate the distances var colorsRef = [CGColor]() var locations = [NSNumber]() for i in 0 ..< colors.count { colorsRef.append(colors[i].cgColor as CGColor) locations.append(NSNumber(value: Float(i) / Float(colors.count - 1))) } gradientLayer.colors = colorsRef let x: CGFloat = 135.0 / 360.0 let a: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.75) / 2.0)), 2.0) let b: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.00) / 2.0)), 2.0) let c: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.25) / 2.0)), 2.0) let d: CGFloat = pow(sin(2.0 * CGFloat.pi * ((x + 0.50) / 2.0)), 2.0) gradientLayer.endPoint = CGPoint(x: c, y: d) gradientLayer.startPoint = CGPoint(x: a, y: b) // now build a UIImage from the gradient UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let gradientImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // return the gradient image return gradientImage! } func areaAverage() -> UIColor { var bitmap = [UInt8](repeating: 0, count: 4) if #available(iOS 9.0, *) { // Get average color. let context = CIContext() let inputImage: CIImage = ciImage ?? CoreImage.CIImage(cgImage: cgImage!) let extent = inputImage.extent let inputExtent = CIVector(x: extent.origin.x, y: extent.origin.y, z: extent.size.width, w: extent.size.height) let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: inputExtent])! let outputImage = filter.outputImage! let outputExtent = outputImage.extent assert(outputExtent.size.width == 1 && outputExtent.size.height == 1) // Render to bitmap. context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: CIFormat.RGBA8, colorSpace: CGColorSpaceCreateDeviceRGB()) } else { // Create 1x1 context that interpolates pixels when drawing to it. let context = CGContext(data: &bitmap, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! let inputImage = cgImage ?? CIContext().createCGImage(ciImage!, from: ciImage!.extent) // Render to bitmap. context.draw(inputImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1)) } // Compute result. let result = UIColor(red: CGFloat(bitmap[0]) / 255.0, green: CGFloat(bitmap[1]) / 255.0, blue: CGFloat(bitmap[2]) / 255.0, alpha: CGFloat(bitmap[3]) / 255.0) return result } /** https://stackoverflow.com/a/62862742/3697225 Rounds corners of UIImage - Parameter proportion: Proportion to minimum paramter (width or height) in order to have the same look of corner radius independetly from aspect ratio and actual size */ func roundCorners(proportion: CGFloat) -> UIImage { let minValue = min(self.size.width, self.size.height) let radius = minValue/proportion let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: self.size) UIGraphicsBeginImageContextWithOptions(self.size, false, 1) UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip() self.draw(in: rect) let image = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return image } } extension UIImage { func withBackground(color: UIColor, opaque: Bool = true) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, opaque, scale) guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self } defer { UIGraphicsEndImageContext() } let rect = CGRect(origin: .zero, size: size) ctx.setFillColor(color.cgColor) ctx.fill(rect) ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)) ctx.draw(image, in: rect) return UIGraphicsGetImageFromCurrentImageContext() ?? self } } extension UIImage { func withPadding(_ padding: CGFloat) -> UIImage? { return withPadding(x: padding, y: padding) } func withPadding(x: CGFloat, y: CGFloat) -> UIImage? { let newWidth = size.width + 2 * x let newHeight = size.height + 2 * y let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContextWithOptions(newSize, false, 0) let origin = CGPoint(x: (newWidth - size.width) / 2, y: (newHeight - size.height) / 2) draw(at: origin) let imageWithPadding = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageWithPadding } }
bc2e2fd9c32c45f2d05df7758b61971d
40.065156
209
0.609547
false
false
false
false
calkinssean/TIY-Assignments
refs/heads/master
Day 37/RealmApp/RealmApp/ViewController.swift
cc0-1.0
1
// // ViewController.swift // RealmApp // // Created by Sean Calkins on 3/23/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit import RealmSwift class ViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! let realm = try! Realm() var currentUser = User() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.usernameTextField.text = "" self.passwordTextField.text = "" } @IBAction func loginTapped(sender: UIButton) { let searchedUsers = realm.objects(User).filter("username == '\(usernameTextField.text!)'") var correctLogin = false for user in searchedUsers { if user.password == passwordTextField.text! { correctLogin = true self.currentUser = user } } if correctLogin == true { print("logged in") performSegueWithIdentifier("loggedInSegue", sender: self) } else { presentAlert("Incorrect username and password.") } } @IBAction func unwindSegue (segue: UIStoryboardSegue) {} override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "loggedInSegue" { let control = segue.destinationViewController as! NotesTableViewController control.currentUser = self.currentUser } } func presentAlert(alertMessage: String) { let alertController = UIAlertController(title: "Oops", message: "\(alertMessage)", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: nil) self.usernameTextField.text = "" self.passwordTextField.text = "" } }
ee96c1f305050df7ad1df93bfb7e304f
26.847059
114
0.584284
false
false
false
false
danielgindi/Charts
refs/heads/master
ChartsDemo-iOS/Swift/Formatters/LargeValueFormatter.swift
apache-2.0
2
// // LargeValueFormatter.swift // ChartsDemo // Copyright © 2016 dcg. All rights reserved. // import Foundation import Charts private let MAX_LENGTH = 5 @objc protocol Testing123 { } public class LargeValueFormatter: NSObject, ValueFormatter, AxisValueFormatter { /// Suffix to be appended after the values. /// /// **default**: suffix: ["", "k", "m", "b", "t"] public var suffix = ["", "k", "m", "b", "t"] /// An appendix text to be added at the end of the formatted value. public var appendix: String? public init(appendix: String? = nil) { self.appendix = appendix } fileprivate func format(value: Double) -> String { var sig = value var length = 0 let maxLength = suffix.count - 1 while sig >= 1000.0 && length < maxLength { sig /= 1000.0 length += 1 } var r = String(format: "%2.f", sig) + suffix[length] if let appendix = appendix { r += appendix } return r } public func stringForValue(_ value: Double, axis: AxisBase?) -> String { return format(value: value) } public func stringForValue( _ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String { return format(value: value) } }
98fa93e58bfc206fae700646c736af02
23.637931
80
0.554934
false
false
false
false
tomomura/PasscodeField
refs/heads/master
PasscodeField/Classes/PasscodeField.swift
mit
1
// // PasscodeField.swift // Pods // // Created by TomomuraRyota on 2016/05/30. // // import UIKit @IBDesignable public class PasscodeField: UIView { // MARK: - Properties @IBInspectable public var length: Int = 6 { didSet { self.progressView.length = self.length } } @IBInspectable public var progress: Int = 0 { didSet { self.progressView.progress = self.progress } } @IBInspectable public var borderHeight: CGFloat = 2.0 { didSet { self.progressView.borderHeight = self.borderHeight } } @IBInspectable public var fillColor: UIColor = UIColor.blackColor() { didSet { self.progressView.fillColor = self.fillColor } } @IBInspectable public var fillSize: CGFloat = 20 { didSet { self.progressView.fillSize = self.fillSize } } private var progressView: ProgressStackView // MARK: - Initializers required public init?(coder aDecoder: NSCoder) { self.progressView = ProgressStackView( length: self.length, progress: self.progress, borderHeight: self.borderHeight, fillSize: self.fillSize, fillColor: self.fillColor ) super.init(coder: aDecoder) self.setupView() } override public init(frame: CGRect) { self.progressView = ProgressStackView( length: self.length, progress: self.progress, borderHeight: self.borderHeight, fillSize: self.fillSize, fillColor: self.fillColor ) super.init(frame: frame) self.setupView() } // MARK: - LifeCycle override public func updateConstraints() { NSLayoutConstraint.activateConstraints([ self.progressView.topAnchor.constraintEqualToAnchor(self.topAnchor), self.progressView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor), self.progressView.leadingAnchor.constraintEqualToAnchor(self.leadingAnchor), self.progressView.trailingAnchor.constraintEqualToAnchor(self.trailingAnchor), ]) super.updateConstraints() } // MARK: - Private Methods private func setupView() { self.addSubview(progressView) } }
4c07d41d2335032f596d64d28ec324d5
24.604167
90
0.588283
false
false
false
false
otakisan/SmartToDo
refs/heads/master
SmartToDo/Views/Cells/ToDoEditorPickerBaseTableViewCell.swift
mit
1
// // ToDoEditorPickerBaseTableViewCell.swift // SmartToDo // // Created by takashi on 2014/11/03. // Copyright (c) 2014年 ti. All rights reserved. // import UIKit class ToDoEditorPickerBaseTableViewCell: ToDoEditorBaseTableViewCell { lazy var dataLists : [[String]] = self.createPickerDataSource() override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func setValueOfCell(value: AnyObject) { if let entityData = value as? String { self.setStringValueOfCell(entityData) } else if let entityDataNumber = value as? NSNumber { self.setStringValueOfCell(String(format: "%f", entityDataNumber.floatValue)) } } func setStringValueOfCell(valueString : String) { } func completeDelegate() -> ((UIView) -> Void)? { return self.didFinishDetailView } func didFinishDetailView(detailView : UIView){ if let view = detailView as? UIPickerView { // 現在の仕様上は、1区分のみ必要のため、固定で先頭区分から取得 // 区分ごとの個別の値を返却する必要が出たら、タプルにして返却する let selectedIndex = view.selectedRowInComponent(0) if selectedIndex >= 0 { let valueString = self.dataLists[0][selectedIndex] self.didFinishPickerView(valueString) } } else if let textField = detailView as? UITextField { self.didFinishPickerView(textField.text ?? "") } } func didFinishPickerView(selectedValue : String) { } override func createDetailView() -> UIViewController? { let vc = self.loadDetailView() vc?.canFreeText = self.canFreeText() vc?.syncSelectionAmongComponents = self.syncSelectionAmongComponents() vc?.setCompleteDeleage(self.completeDelegate()) return vc } func loadDetailView() -> CommonPickerViewController? { let vc = NSBundle.mainBundle().loadNibNamed("CommonPickerViewController", owner: nil, options: nil)[0] as? CommonPickerViewController return vc } override func detailViewController() -> UIViewController? { let vc = super.detailViewController() as? CommonPickerViewController vc?.setDataSource(self.dataSource()) vc?.setViewValue(self.detailViewInitValue()) return vc } func detailViewInitValue() -> AnyObject? { return nil } func dataSource() -> [[String]] { return dataLists } func createPickerDataSource() -> [[String]] { return [[]] } func canFreeText() -> Bool { return false } func syncSelectionAmongComponents() -> Bool { return false } }
efb35ab37ca61a6f2305af01d3f5cf90
26.759259
141
0.612408
false
false
false
false
alessiobrozzi/firefox-ios
refs/heads/master
Extensions/ShareTo/InitialViewController.swift
mpl-2.0
2
/* 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 import Shared import Storage private let LastUsedShareDestinationsKey = "LastUsedShareDestinations" @objc(InitialViewController) class InitialViewController: UIViewController, ShareControllerDelegate { var shareDialogController: ShareDialogController! lazy var profile: Profile = { return BrowserProfile(localName: "profile", app: nil) }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.66) // TODO: Is the correct color documented somewhere? } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in if let item = item, error == nil { DispatchQueue.main.async { guard item.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.finish() }) self.present(alert, animated: true, completion: nil) return } self.presentShareDialog(item) } } else { self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } }) } // func shareControllerDidCancel(_ shareController: ShareDialogController) { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 0.0 }, completion: { (Bool) -> Void in self.dismissShareDialog() self.finish() }) } func finish() { self.profile.shutdown() self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } func shareController(_ shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) { setLastUsedShareDestinations(destinations) UIView.animate(withDuration: 0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 0.0 }, completion: { (Bool) -> Void in self.dismissShareDialog() if destinations.contains(ShareDestinationReadingList) { self.shareToReadingList(item) } if destinations.contains(ShareDestinationBookmarks) { self.shareToBookmarks(item) } self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) }) } // // TODO: use Set. func getLastUsedShareDestinations() -> NSSet { if let destinations = UserDefaults.standard.object(forKey: LastUsedShareDestinationsKey) as? NSArray { return NSSet(array: destinations as [AnyObject]) } return NSSet(object: ShareDestinationBookmarks) } func setLastUsedShareDestinations(_ destinations: NSSet) { UserDefaults.standard.set(destinations.allObjects, forKey: LastUsedShareDestinationsKey) UserDefaults.standard.synchronize() } func presentShareDialog(_ item: ShareItem) { shareDialogController = ShareDialogController() shareDialogController.delegate = self shareDialogController.item = item shareDialogController.initialShareDestinations = getLastUsedShareDestinations() self.addChildViewController(shareDialogController) shareDialogController.view.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(shareDialogController.view) shareDialogController.didMove(toParentViewController: self) // Setup constraints for the dialog. We keep the dialog centered with 16 points of padding on both // sides. The dialog grows to max 380 points wide so that it does not look too big on landscape or // iPad devices. let views: NSDictionary = ["dialog": shareDialogController.view] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(16@751)-[dialog(<=380@1000)]-(16@751)-|", options: NSLayoutFormatOptions(), metrics: nil, views: (views as? [String : AnyObject])!)) let cx = NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0) cx.priority = 1000 // TODO: Why does UILayoutPriorityRequired give a linker error? SDK Bug? view.addConstraint(cx) view.addConstraint(NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0)) // Fade the dialog in shareDialogController.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 1.0 }, completion: nil) } func dismissShareDialog() { shareDialogController.willMove(toParentViewController: nil) shareDialogController.view.removeFromSuperview() shareDialogController.removeFromParentViewController() } // func shareToReadingList(_ item: ShareItem) { profile.readingList?.createRecordWithURL(item.url, title: item.title ?? "", addedBy: UIDevice.current.name) } func shareToBookmarks(_ item: ShareItem) { profile.bookmarks.shareItem(item) } }
5ab0c039cab6b673b57fefef0c432c99
40.857143
147
0.65529
false
false
false
false
dipen30/Qmote
refs/heads/master
KodiRemote/KodiRemote/Controllers/RemoteController.swift
apache-2.0
1
// // RemoteController.swift // Kodi Remote // // Created by Quixom Technology on 18/12/15. // Copyright © 2015 Quixom Technology. All rights reserved. // import Foundation import Kingfisher fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } class RemoteController: ViewController { @IBOutlet var itemName: UILabel! @IBOutlet var otherDetails: UILabel! @IBOutlet var activePlayerImage: UIImageView! @IBOutlet var nothingPlaying: UILabel! @IBOutlet var play: UIButton! @IBOutlet var pause: UIButton! @IBOutlet var timeLabel: UILabel! @IBOutlet var totalTimeLabel: UILabel! @IBOutlet var seekBar: UISlider! var playerId = 0 var player_repeat = "off" var shuffle = false @IBOutlet var musicButtonLeadingSpace: NSLayoutConstraint! @IBOutlet var videoButtonTrailingSpace: NSLayoutConstraint! @IBOutlet var repeatButtonLeadingSpace: NSLayoutConstraint! @IBOutlet var volumUpLeadingSpace: NSLayoutConstraint! @IBOutlet var playerRepeat: UIButton! @IBOutlet var playerShuffle: UIButton! @IBOutlet weak var backgroundImage: UIImageView! var rc: RemoteCalls! override func viewDidLoad() { super.viewDidLoad() self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) } override func viewDidAppear(_ animated: Bool) { self.view.viewWithTag(2)?.isHidden = true self.backgroundImage.layer.opacity = 0.1 self.view.viewWithTag(2)?.layer.opacity = 0.9 self.view.viewWithTag(1)?.layer.opacity = 0.9 let previous_ip = UserDefaults.standard if let ip = previous_ip.string(forKey: "ip"){ global_ipaddress = ip } if let port = previous_ip.string(forKey: "port"){ global_port = port } if global_ipaddress == "" { let discovery = self.storyboard?.instantiateViewController(withIdentifier: "DiscoveryView") as! DiscoveryTableViewController self.navigationController?.pushViewController(discovery, animated: true) } if global_ipaddress != "" { rc = RemoteCalls(ipaddress: global_ipaddress, port: global_port) self.syncPlayer() } } func syncPlayer(){ self.rc.jsonRpcCall("Player.GetActivePlayers"){(response: AnyObject?) in if response!.count == 0 { DispatchQueue.main.async(execute: { self.view.viewWithTag(2)?.isHidden = true self.nothingPlaying.isHidden = false self.backgroundImage.isHidden = true }) return } DispatchQueue.main.async(execute: { self.view.viewWithTag(2)?.isHidden = false self.nothingPlaying.isHidden = true self.backgroundImage.isHidden = false }) let response = (response as! NSArray)[0] as? NSDictionary self.playerId = response!["playerid"] as! Int self.rc.jsonRpcCall("Player.GetProperties", params: "{\"playerid\":\(self.playerId),\"properties\":[\"percentage\",\"time\",\"totaltime\", \"repeat\",\"shuffled\",\"speed\",\"subtitleenabled\"]}"){(response: AnyObject?) in DispatchQueue.main.async(execute: { let response = response as? NSDictionary self.shuffle = response!["shuffled"] as! Bool self.player_repeat = response!["repeat"] as! String let repeateImage = self.player_repeat == "off" ? "Repeat": "RepeatSelected" self.playerRepeat.imageView?.image = UIImage(named: repeateImage) let suffleImage = self.shuffle == true ? "shuffleSelected" : "shuffle" self.playerShuffle.imageView?.image = UIImage(named: suffleImage) if response!["speed"] as! Int == 0 { self.play.isHidden = false self.pause.isHidden = true }else{ self.play.isHidden = true self.pause.isHidden = false } self.timeLabel.text = self.toMinutes(response!["time"] as! NSDictionary) self.totalTimeLabel.text = self.toMinutes(response!["totaltime"] as! NSDictionary) self.seekBar.value = (response!["percentage"] as! Float) / 100 }) self.rc.jsonRpcCall("Player.GetItem", params: "{\"playerid\":\(self.playerId),\"properties\":[\"title\",\"artist\",\"thumbnail\", \"fanart\", \"album\",\"year\"]}"){(response: AnyObject?) in DispatchQueue.main.async(execute: { let response = response as? NSDictionary self.generateResponse(response!) }); } } } // 1 second trigger Time let triggerTime = Int64(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(triggerTime) / Double(NSEC_PER_SEC), execute: { () -> Void in self.syncPlayer() }) } @IBAction func sliderTouchUp(_ sender: UISlider) { // RPC call for seek let value = Int(sender.value * 100) self.seekBar.value = sender.value rc.jsonRpcCall("Player.Seek", params: "{\"playerid\":\(self.playerId), \"value\":\(value)}"){(response: AnyObject?) in } } func generateResponse(_ jsonData: AnyObject){ for(key, value) in jsonData["item"] as! NSDictionary{ if key as! String == "label" { self.itemName.text = value as? String } if key as! String == "artist" { self.otherDetails.text = "" if (value as AnyObject).count != 0 { self.otherDetails.text = (value as! NSArray)[0] as? String } } if key as! String == "thumbnail" { self.activePlayerImage.contentMode = .scaleAspectFit let url = URL(string: getThumbnailUrl(value as! String)) self.activePlayerImage.kf.setImage(with: url!) } if key as! String == "fanart" { self.backgroundImage.contentMode = .scaleAspectFill let url = URL(string: getThumbnailUrl(value as! String)) self.backgroundImage.kf.setImage(with: url!) } } } func toMinutes(_ temps: NSDictionary ) -> String { var seconds = String(temps["seconds"] as! Int) var minutes = String(temps["minutes"] as! Int) var hours = String(temps["hours"] as! Int) if (Int(seconds) < 10) { seconds = "0" + seconds } if (Int(minutes) < 10) { minutes = "0" + minutes } if (Int(hours) < 10) { hours = "0" + hours } var time = minutes + ":" + seconds if Int(hours) != 0 { time = hours + ":" + minutes + ":" + seconds } return time } @IBAction func previousButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"skipprevious\"}"){(response: AnyObject?) in } } @IBAction func fastRewindButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stepback\"}"){(response: AnyObject?) in } } @IBAction func stopButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stop\"}"){(response: AnyObject?) in } } @IBAction func playButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"play\"}"){(response: AnyObject?) in } } @IBAction func pauseButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"pause\"}"){(response: AnyObject?) in } } @IBAction func fastForwardButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stepforward\"}"){(response: AnyObject?) in } } @IBAction func nextButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"skipnext\"}"){(response: AnyObject?) in } } @IBAction func leftButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Left"){(response: AnyObject?) in } } @IBAction func rightButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Right"){(response: AnyObject?) in } } @IBAction func downButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Down"){(response: AnyObject?) in } } @IBAction func upButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Up"){(response: AnyObject?) in } } @IBAction func okButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Select"){(response: AnyObject?) in } } @IBAction func homeButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Home"){(response: AnyObject?) in } } @IBAction func backButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Back"){(response: AnyObject?) in } } @IBAction func tvButton(_ sender: AnyObject) { rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"videos\",\"parameters\":[\"TvShowTitles\"]}"){(response: AnyObject?) in } } @IBAction func moviesButton(_ sender: AnyObject) { rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"video\",\"parameters\":[\"MovieTitles\"]}"){(response: AnyObject?) in } } @IBAction func musicButton(_ sender: AnyObject) { rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"music\"}"){(response: AnyObject?) in } } @IBAction func pictureButton(_ sender: AnyObject) { rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"pictures\"}"){(response: AnyObject?) in } } @IBAction func volumeDownButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"volumedown\"}"){(response: AnyObject?) in } } @IBAction func muteButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"mute\"}"){(response: AnyObject?) in } } @IBAction func volumeUpButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"volumeup\"}"){(response: AnyObject?) in } } @IBAction func repeatButton(_ sender: AnyObject) { let r = self.player_repeat == "off" ? "all" : "off" rc.jsonRpcCall("Player.SetRepeat", params: "{\"playerid\":\(self.playerId), \"repeat\":\"\(r)\"}"){(response: AnyObject?) in } } @IBAction func shuffleButton(_ sender: AnyObject) { let s = self.shuffle == true ? "false": "true" rc.jsonRpcCall("Player.SetShuffle", params: "{\"playerid\":\(self.playerId), \"shuffle\":\(s)}"){(response: AnyObject?) in } } @IBAction func osdButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ShowOSD"){(response: AnyObject?) in } } @IBAction func contextButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.ContextMenu"){(response: AnyObject?) in } } @IBAction func infoButton(_ sender: AnyObject) { rc.jsonRpcCall("Input.Info"){(response: AnyObject?) in } } }
45c61e67886986298521188ce1f7cc13
34.245014
234
0.547005
false
false
false
false
chenxtdo/UPImageMacApp
refs/heads/master
UPImage/AppHelper.swift
mit
1
// // AppHelper.swift // U图床 // // Created by Pro.chen on 16/7/13. // Copyright © 2016年 chenxt. All rights reserved. // import Foundation import AppKit import TMCache public enum Result<Value> { case success(Value) case failure(Value) public func Success( success: (_ value: Value) -> Void) -> Result<Value> { switch self { case .success(let value): success(value) default: break } return self } public func Failure( failure: (_ error: Value) -> Void) -> Result<Value> { switch self { case .failure(let error): failure(error) default: break } return self } } extension NSImage { func scalingImage() { let sW = self.size.width let sH = self.size.height let nW: CGFloat = 100 let nH = nW * sH / sW self.size = CGSize(width: nW, height: nH) } } func NotificationMessage(_ message: String, informative: String? = nil, isSuccess: Bool = false) { let notification = NSUserNotification() let notificationCenter = NSUserNotificationCenter.default notificationCenter.delegate = appDelegate as? NSUserNotificationCenterDelegate notification.title = message notification.informativeText = informative if isSuccess { notification.contentImage = NSImage(named: "success") notification.informativeText = "链接已经保存在剪贴板里,可以直接粘贴" } else { notification.contentImage = NSImage(named: "Failure") } notification.soundName = NSUserNotificationDefaultSoundName; notificationCenter.scheduleNotification(notification) } func arc() -> UInt32 { return arc4random() % 100000 } func timeInterval() -> Int { return Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970) } func getDateString() -> String { let dateformatter = DateFormatter() dateformatter.dateFormat = "YYYYMMdd" let dataString = dateformatter.string(from: Date(timeInterval: 0, since: Date())) return dataString } func checkImageFile(_ pboard: NSPasteboard) -> Bool { guard let pasteboard = pboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray, let path = pasteboard[0] as? String else { return false } let image = NSImage(contentsOfFile: path) guard let _ = image else { return false } return true } func getImageType(_ data: Data) -> String { var c: uint8 = 0 data.copyBytes(to: &c, count: 1) switch c { case 0xFF: return ".jpeg" case 0x89: return ".png" case 0x49: return ".tiff" case 0x4D: return ".tiff" case 0x52: guard data.count > 12, let str = String(data: data.subdata(in: 0..<13), encoding: .ascii), str.hasPrefix("RIFF"), str.hasPrefix("WEBP") else { return "" } return ".webp" default: return "" } } private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8] private let jpgHeaderIF: [UInt8] = [0xFF] private let gifHeader: [UInt8] = [0x47, 0x49, 0x46] enum ImageFormat : String { case unknown = "" case png = ".png" case jpeg = ".jpg" case gif = ".gif" } extension Data { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (self as NSData).getBytes(&buffer, length: 8) if buffer == pngHeader { return .png } else if buffer[0] == jpgHeaderSOI[0] && buffer[1] == jpgHeaderSOI[1] && buffer[2] == jpgHeaderIF[0] { return .jpeg } else if buffer[0] == gifHeader[0] && buffer[1] == gifHeader[1] && buffer[2] == gifHeader[2] { return .gif } return .unknown } }
75a91d7208df52c966890132aff706d9
23.679245
150
0.602701
false
false
false
false
dvSection8/dvSection8
refs/heads/master
dvSection8/Classes/API/DVAPIHelper.swift
mit
1
// // APIHelper.swift // Rush // // Created by MJ Roldan on 05/07/2017. // Copyright © 2017 Mark Joel Roldan. All rights reserved. // import Foundation public struct DVAPIHelper { public static let shared = DVAPIHelper() // Appending of keys and values from parameters public func query(_ parameters: Paremeters) -> String { var components: StringArray = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key] ?? "" components += queryComponents(key: key, value: value) } return components.map {"\($0)=\($1)"}.joined(separator: "&") } // Query components value checker private func queryComponents(key: String, value: Any) -> StringArray { var components: StringArray = [] // dictionary if let dictionary = value as? JSONDictionary { for (nestedKey, value) in dictionary { components += queryComponents(key: "\(key)[\(nestedKey)]", value: value) } } // array else if let array = value as? [Any] { for (value) in array { components += queryComponents(key: "\(key)[]", value: value) } } // nsnumber - boolean value replace into string else if let value = value as? NSNumber { if value.boolValue { components.append((key, "\(value.boolValue ? "1" : "0")")) } else { components.append((key, "\(value)")) } } // boolean value replace into string else if let bool = value as? Bool { if bool { components.append((key, "\(bool ? "1" : "0")")) } else { components.append((key, "\(value)")) } } else { // string value components.append((key, "\(value)")) } return components } }
27be580bb53607a5a5205da6729e5646
29.212121
88
0.510532
false
false
false
false
Pluto-Y/SwiftyEcharts
refs/heads/master
SwiftyEcharts/Models/Type/LineStyle.swift
mit
1
// // LineStyle.swift // SwiftyEcharts // // Created by Pluto Y on 03/01/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // public protocol LineStyleContent: Colorful, Shadowable, Opacitable { var width: Float? { get set } var type: LineType? { get set } } /// 线条样式 public final class LineStyle: Displayable, Shadowable, Colorful, Opacitable, Jsonable { /// 是否显示 public var show: Bool? /// 线的颜色。 public var color: Color? /// 线宽。 public var width: Float? /// 线的类型。 public var type: LineType? /// 图形透明度。支持从 0 到 1 的数字,为 0 时不绘制该图形。 public var opacity: Float? { didSet { validateOpacity() } } // MARK: - Shadowable public var shadowBlur: Float? public var shadowColor: Color? public var shadowOffsetX: Float? public var shadowOffsetY: Float? public var curveness: Float? public init() { } } extension LineStyle: Enumable { public enum Enums { case show(Bool), color(Color), width(Float), type(LineType), shadowBlur(Float), shadowColor(Color), shadowOffsetX(Float), shadowOffsetY(Float), opacity(Float), curveness(Float) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .show(show): self.show = show case let .color(color): self.color = color case let .width(width): self.width = width case let .type(type): self.type = type case let .shadowBlur(blur): self.shadowBlur = blur case let .shadowColor(color): self.shadowColor = color case let .shadowOffsetX(x): self.shadowOffsetX = x case let .shadowOffsetY(y): self.shadowOffsetY = y case let .opacity(opacity): self.opacity = opacity case let .curveness(curveness): self.curveness = curveness } } } } extension LineStyle: Mappable { public func mapping(_ map: Mapper) { map["show"] = show map["color"] = color map["width"] = width map["type"] = type map["shadowBlur"] = shadowBlur map["shadowColor"] = shadowColor map["shadowOffsetX"] = shadowOffsetX map["shadowOffsetY"] = shadowOffsetY map["opacity"] = opacity map["curveness"] = curveness } } public final class EmphasisLineStyle: Emphasisable { public typealias Style = LineStyle public var normal: Style? public var emphasis: Style? public init() { } } extension EmphasisLineStyle: Enumable { public enum Enums { case normal(Style), emphasis(Style) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .normal(normal): self.normal = normal case let .emphasis(emphasis): self.emphasis = emphasis } } } } extension EmphasisLineStyle: Mappable { public func mapping(_ map: Mapper) { map["normal"] = normal map["emphasis"] = emphasis } }
fd93bc6e141013f94acf67584a080778
25.114504
184
0.562701
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
refs/heads/master
Example/Pods/SKPhotoBrowser/SKPhotoBrowser/SKAnimator.swift
apache-2.0
1
// // SKAnimator.swift // SKPhotoBrowser // // Created by keishi suzuki on 2016/08/09. // Copyright © 2016 suzuki_keishi. All rights reserved. // import UIKit @objc public protocol SKPhotoBrowserAnimatorDelegate { func willPresent(_ browser: SKPhotoBrowser) func willDismiss(_ browser: SKPhotoBrowser) } class SKAnimator: NSObject, SKPhotoBrowserAnimatorDelegate { var resizableImageView: UIImageView? var senderOriginImage: UIImage! var senderViewOriginalFrame: CGRect = .zero var senderViewForAnimation: UIView? var finalImageViewFrame: CGRect = .zero var bounceAnimation: Bool = false var animationDuration: TimeInterval { if SKPhotoBrowserOptions.bounceAnimation { return 0.5 } return 0.35 } var animationDamping: CGFloat { if SKPhotoBrowserOptions.bounceAnimation { return 0.8 } return 1 } func willPresent(_ browser: SKPhotoBrowser) { guard let appWindow = UIApplication.shared.delegate?.window else { return } guard let window = appWindow else { return } guard let sender = browser.delegate?.viewForPhoto?(browser, index: browser.initialPageIndex) ?? senderViewForAnimation else { presentAnimation(browser) return } let photo = browser.photoAtIndex(browser.currentPageIndex) let imageFromView = (senderOriginImage ?? browser.getImageFromView(sender)).rotateImageByOrientation() let imageRatio = imageFromView.size.width / imageFromView.size.height senderViewOriginalFrame = calcOriginFrame(sender) finalImageViewFrame = calcFinalFrame(imageRatio) resizableImageView = UIImageView(image: imageFromView) resizableImageView!.frame = senderViewOriginalFrame resizableImageView!.clipsToBounds = true resizableImageView!.contentMode = photo.contentMode if sender.layer.cornerRadius != 0 { let duration = (animationDuration * Double(animationDamping)) resizableImageView!.layer.masksToBounds = true resizableImageView!.addCornerRadiusAnimation(sender.layer.cornerRadius, to: 0, duration: duration) } window.addSubview(resizableImageView!) presentAnimation(browser) } func willDismiss(_ browser: SKPhotoBrowser) { guard let sender = browser.delegate?.viewForPhoto?(browser, index: browser.currentPageIndex), let image = browser.photoAtIndex(browser.currentPageIndex).underlyingImage, let scrollView = browser.pageDisplayedAtIndex(browser.currentPageIndex) else { senderViewForAnimation?.isHidden = false browser.dismissPhotoBrowser(animated: false) return } senderViewForAnimation = sender browser.view.isHidden = true browser.backgroundView.isHidden = false browser.backgroundView.alpha = 1 senderViewOriginalFrame = calcOriginFrame(sender) let photo = browser.photoAtIndex(browser.currentPageIndex) let contentOffset = scrollView.contentOffset let scrollFrame = scrollView.photoImageView.frame let offsetY = scrollView.center.y - (scrollView.bounds.height/2) let frame = CGRect( x: scrollFrame.origin.x - contentOffset.x, y: scrollFrame.origin.y + contentOffset.y + offsetY, width: scrollFrame.width, height: scrollFrame.height) // resizableImageView.image = scrollView.photo?.underlyingImage?.rotateImageByOrientation() resizableImageView!.image = image.rotateImageByOrientation() resizableImageView!.frame = frame resizableImageView!.alpha = 1.0 resizableImageView!.clipsToBounds = true resizableImageView!.contentMode = photo.contentMode if let view = senderViewForAnimation, view.layer.cornerRadius != 0 { let duration = (animationDuration * Double(animationDamping)) resizableImageView!.layer.masksToBounds = true resizableImageView!.addCornerRadiusAnimation(0, to: view.layer.cornerRadius, duration: duration) } dismissAnimation(browser) } } private extension SKAnimator { func calcOriginFrame(_ sender: UIView) -> CGRect { if let senderViewOriginalFrameTemp = sender.superview?.convert(sender.frame, to:nil) { return senderViewOriginalFrameTemp } else if let senderViewOriginalFrameTemp = sender.layer.superlayer?.convert(sender.frame, to: nil) { return senderViewOriginalFrameTemp } else { return .zero } } func calcFinalFrame(_ imageRatio: CGFloat) -> CGRect { if SKMesurement.screenRatio < imageRatio { let width = SKMesurement.screenWidth let height = width / imageRatio let yOffset = (SKMesurement.screenHeight - height) / 2 return CGRect(x: 0, y: yOffset, width: width, height: height) } else { let height = SKMesurement.screenHeight let width = height * imageRatio let xOffset = (SKMesurement.screenWidth - width) / 2 return CGRect(x: xOffset, y: 0, width: width, height: height) } } } private extension SKAnimator { func presentAnimation(_ browser: SKPhotoBrowser, completion: (() -> Void)? = nil) { browser.view.isHidden = true browser.view.alpha = 0.0 UIView.animate( withDuration: animationDuration, delay: 0, usingSpringWithDamping:animationDamping, initialSpringVelocity:0, options:UIViewAnimationOptions(), animations: { browser.showButtons() browser.backgroundView.alpha = 1.0 self.resizableImageView?.frame = self.finalImageViewFrame }, completion: { (_) -> Void in browser.view.isHidden = false browser.view.alpha = 1.0 browser.backgroundView.isHidden = true self.resizableImageView?.alpha = 0.0 }) } func dismissAnimation(_ browser: SKPhotoBrowser, completion: (() -> Void)? = nil) { UIView.animate( withDuration: animationDuration, delay:0, usingSpringWithDamping:animationDamping, initialSpringVelocity:0, options:UIViewAnimationOptions(), animations: { browser.backgroundView.alpha = 0.0 self.resizableImageView?.layer.frame = self.senderViewOriginalFrame }, completion: { (_) -> Void in browser.dismissPhotoBrowser(animated: true) { self.resizableImageView?.removeFromSuperview() } }) } }
3ce3008d5277bfec908ee6bd668f92ff
37.005376
133
0.627953
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Glacier/Glacier_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Glacier public struct GlacierErrorType: AWSErrorType { enum Code: String { case insufficientCapacityException = "InsufficientCapacityException" case invalidParameterValueException = "InvalidParameterValueException" case limitExceededException = "LimitExceededException" case missingParameterValueException = "MissingParameterValueException" case policyEnforcedException = "PolicyEnforcedException" case requestTimeoutException = "RequestTimeoutException" case resourceNotFoundException = "ResourceNotFoundException" case serviceUnavailableException = "ServiceUnavailableException" } private let error: Code public let context: AWSErrorContext? /// initialize Glacier public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Returned if there is insufficient capacity to process this expedited request. This error only applies to expedited retrievals and not to standard or bulk retrievals. public static var insufficientCapacityException: Self { .init(.insufficientCapacityException) } /// Returned if a parameter of the request is incorrectly specified. public static var invalidParameterValueException: Self { .init(.invalidParameterValueException) } /// Returned if the request results in a vault or account limit being exceeded. public static var limitExceededException: Self { .init(.limitExceededException) } /// Returned if a required header or parameter is missing from the request. public static var missingParameterValueException: Self { .init(.missingParameterValueException) } /// Returned if a retrieval job would exceed the current data policy's retrieval rate limit. For more information about data retrieval policies, public static var policyEnforcedException: Self { .init(.policyEnforcedException) } /// Returned if, when uploading an archive, Amazon S3 Glacier times out while receiving the upload. public static var requestTimeoutException: Self { .init(.requestTimeoutException) } /// Returned if the specified resource (such as a vault, upload ID, or job ID) doesn't exist. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// Returned if the service cannot complete the request. public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } } extension GlacierErrorType: Equatable { public static func == (lhs: GlacierErrorType, rhs: GlacierErrorType) -> Bool { lhs.error == rhs.error } } extension GlacierErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
c4312e7a45beb310c7741ef7db988f6e
46.179487
173
0.707609
false
false
false
false
wikimedia/apps-ios-wikipedia
refs/heads/twn
Wikipedia/Code/HintController.swift
mit
1
@objc(WMFHintPresenting) protocol HintPresenting: AnyObject { var hintController: HintController? { get set } } class HintController: NSObject { typealias Context = [String: Any] typealias HintPresentingViewController = UIViewController & HintPresenting private weak var presenter: HintPresentingViewController? private let hintViewController: HintViewController private var containerView = UIView() private var containerViewConstraint: (top: NSLayoutConstraint?, bottom: NSLayoutConstraint?) private var task: DispatchWorkItem? var theme = Theme.standard //if true, hint will extend below safe area to the bottom of the view, and hint content within will align to safe area //must also override extendsUnderSafeArea to true in HintViewController var extendsUnderSafeArea: Bool { return false } init(hintViewController: HintViewController) { self.hintViewController = hintViewController super.init() hintViewController.delegate = self } var isHintHidden: Bool { return containerView.superview == nil } private var hintVisibilityTime: TimeInterval = 13 { didSet { guard hintVisibilityTime != oldValue else { return } dismissHint() } } func dismissHint() { self.task?.cancel() let task = DispatchWorkItem { [weak self] in self?.setHintHidden(true) } DispatchQueue.main.asyncAfter(deadline: .now() + hintVisibilityTime , execute: task) self.task = task } @objc func toggle(presenter: HintPresentingViewController, context: Context?, theme: Theme) { self.presenter = presenter apply(theme: theme) } private func addHint(to presenter: HintPresentingViewController) { guard isHintHidden else { return } containerView.translatesAutoresizingMaskIntoConstraints = false var additionalBottomSpacing: CGFloat = 0 if let wmfVCPresenter = presenter as? WMFViewController { // not ideal, violates encapsulation wmfVCPresenter.view.insertSubview(containerView, belowSubview: wmfVCPresenter.toolbar) additionalBottomSpacing = wmfVCPresenter.toolbar.frame.size.height } else { presenter.view.addSubview(containerView) } var bottomAnchor: NSLayoutYAxisAnchor bottomAnchor = extendsUnderSafeArea ? presenter.view.bottomAnchor : presenter.view.safeAreaLayoutGuide.bottomAnchor // `containerBottomConstraint` is activated when the hint is visible containerViewConstraint.bottom = containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0 - additionalBottomSpacing) // `containerTopConstraint` is activated when the hint is hidden containerViewConstraint.top = containerView.topAnchor.constraint(equalTo: bottomAnchor) let leadingConstraint = containerView.leadingAnchor.constraint(equalTo: presenter.view.leadingAnchor) let trailingConstraint = containerView.trailingAnchor.constraint(equalTo: presenter.view.trailingAnchor) NSLayoutConstraint.activate([containerViewConstraint.top!, leadingConstraint, trailingConstraint]) if presenter.isKind(of: SearchResultsViewController.self){ presenter.wmf_hideKeyboard() } hintViewController.view.setContentHuggingPriority(.required, for: .vertical) hintViewController.view.setContentCompressionResistancePriority(.required, for: .vertical) containerView.setContentHuggingPriority(.required, for: .vertical) containerView.setContentCompressionResistancePriority(.required, for: .vertical) presenter.wmf_add(childController: hintViewController, andConstrainToEdgesOfContainerView: containerView) containerView.superview?.layoutIfNeeded() } private func removeHint() { task?.cancel() hintViewController.willMove(toParent: nil) hintViewController.view.removeFromSuperview() hintViewController.removeFromParent() containerView.removeFromSuperview() resetHint() } func resetHint() { hintVisibilityTime = 13 hintViewController.viewType = .default } func setHintHidden(_ hidden: Bool) { guard isHintHidden != hidden, let presenter = presenter, presenter.presentedViewController == nil else { return } presenter.hintController = self if !hidden { // add hint before animation starts addHint(to: presenter) } self.adjustSpacingIfPresenterHasSecondToolbar(hintHidden: hidden) UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: { if hidden { self.containerViewConstraint.bottom?.isActive = false self.containerViewConstraint.top?.isActive = true } else { self.containerViewConstraint.top?.isActive = false self.containerViewConstraint.bottom?.isActive = true } self.containerView.superview?.layoutIfNeeded() }, completion: { (_) in // remove hint after animation is completed if hidden { self.adjustSpacingIfPresenterHasSecondToolbar(hintHidden: hidden) self.removeHint() } else { self.dismissHint() } }) } @objc func dismissHintDueToUserInteraction() { guard !self.isHintHidden else { return } self.hintVisibilityTime = 0 } private func adjustSpacingIfPresenterHasSecondToolbar(hintHidden: Bool) { guard let viewController = presenter as? WMFViewController, !viewController.isSecondToolbarHidden else { return } let spacing = hintHidden ? 0 : containerView.frame.height viewController.setAdditionalSecondToolbarSpacing(spacing, animated: true) } } extension HintController: HintViewControllerDelegate { func hintViewControllerWillDisappear(_ hintViewController: HintViewController) { setHintHidden(true) } func hintViewControllerHeightDidChange(_ hintViewController: HintViewController) { adjustSpacingIfPresenterHasSecondToolbar(hintHidden: isHintHidden) } func hintViewControllerViewTypeDidChange(_ hintViewController: HintViewController, newViewType: HintViewController.ViewType) { guard newViewType == .confirmation else { return } setHintHidden(false) } func hintViewControllerDidPeformConfirmationAction(_ hintViewController: HintViewController) { setHintHidden(true) } func hintViewControllerDidFailToCompleteDefaultAction(_ hintViewController: HintViewController) { setHintHidden(true) } } extension HintController: Themeable { func apply(theme: Theme) { hintViewController.apply(theme: theme) } }
9d023ccd9c1f2c76ec53067898cdcf84
34
140
0.679412
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/NewVersion/CoreText/ZSDisplayView.swift
mit
1
// // ZSDisplayView.swift // CoreTextDemo // // Created by caony on 2019/7/12. // Copyright © 2019 cj. All rights reserved. // import UIKit import Kingfisher class ZSDisplayView: UIView { // MARK: - Properties var ctFrame: CTFrame? var images: [(image: UIImage, frame: CGRect)] = [] var imageModels:[ZSImageData] = [] // MARK: - Properties var imageIndex: Int! var longPress:UILongPressGestureRecognizer! var originRange = NSRange(location: 0, length: 0) var selectedRange = NSRange(location: 0, length: 0) var attributeString:NSMutableAttributedString = NSMutableAttributedString(string: "") var rects:[CGRect] = [] var leftCursor:ZSTouchAnchorView! var rightCursor:ZSTouchAnchorView! // 移动光标 private var isTouchCursor = false private var touchRightCursor = false private var touchOriginRange = NSRange(location: 0, length: 0) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear isUserInteractionEnabled = true if longPress == nil { longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(gesture:))) addGestureRecognizer(longPress) } let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(tap:))) addGestureRecognizer(tap) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func tapAction(tap:UITapGestureRecognizer) { originRange = NSRange(location: 0, length: 0) selectedRange = NSRange(location: 0, length: 0) rects.removeAll() hideCursor() setNeedsDisplay() } @objc private func longPressAction(gesture:UILongPressGestureRecognizer) { var originPoint = CGPoint.zero switch gesture.state { case .began: originPoint = gesture.location(in: self) originRange = touchLocation(point: originPoint, str: self.attributeString.string) selectedRange = originRange rects = rangeRects(range: selectedRange, ctframe: ctFrame) showCursor() setNeedsDisplay() break case .changed: let finalRange = touchLocation(point: gesture.location(in: self), str: attributeString.string) if finalRange.location == 0 || finalRange.location == NSNotFound { return } var range = NSRange(location: 0, length: 0) range.location = min(finalRange.location, originRange.location) if finalRange.location > originRange.location { range.length = finalRange.location - originRange.location + finalRange.length } else { range.length = originRange.location - finalRange.location + originRange.length } selectedRange = range rects = rangeRects(range: selectedRange, ctframe: ctFrame) showCursor() setNeedsDisplay() break case .ended: break case .cancelled: break default: break } } func showCursor() { guard rects.count > 0 else { return } let leftRect = rects.first! let rightRect = rects.last! if leftCursor == nil { let rect = CGRect(x: leftRect.minX - 2, y: bounds.height - leftRect.origin.y - rightRect.height - 6, width: 10, height: leftRect.height + 6) leftCursor = ZSTouchAnchorView(frame: rect) addSubview(leftCursor) } else { let rect = CGRect(x: leftRect.minX - 2, y: bounds.height - leftRect.origin.y - rightRect.height - 6, width: 10, height: leftRect.height + 6) leftCursor.frame = rect } if rightCursor == nil { let rect = CGRect(x: rightRect.maxX - 2, y: bounds.height - rightRect.origin.y - rightRect.height - 6, width: 10, height: rightRect.height + 6) rightCursor = ZSTouchAnchorView(frame: rect) addSubview(rightCursor) } else { rightCursor.frame = CGRect(x: rightRect.maxX - 4, y: bounds.height - rightRect.origin.y - rightRect.height - 6, width: 10, height: rightRect.height + 6) } } func hideCursor() { if leftCursor != nil { leftCursor.removeFromSuperview() leftCursor = nil } if rightCursor != nil { rightCursor.removeFromSuperview() rightCursor = nil } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let point = touches.first?.location(in: self) else { return } guard leftCursor != nil && rightCursor != nil else { return } if rightCursor.frame.insetBy(dx: -30, dy: -30).contains(point) { touchRightCursor = true isTouchCursor = true } else if leftCursor.frame.insetBy(dx: -30, dy: -30).contains(point) { touchRightCursor = false isTouchCursor = true } touchOriginRange = selectedRange } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let point = touches.first?.location(in: self) else { return } guard leftCursor != nil && rightCursor != nil else { return } if isTouchCursor { let finalRange = touchLocation(point: point, str: attributeString.string) if (finalRange.location == 0 && finalRange.length == 0) || finalRange.location == NSNotFound { return } var range = NSRange(location: 0, length: 0) if touchRightCursor { // 移动右边光标 if finalRange.location >= touchOriginRange.location { range.location = touchOriginRange.location range.length = finalRange.location - touchOriginRange.location + 1 } else { range.location = finalRange.location range.length = touchOriginRange.location - range.location } } else { // 移动左边光标 if finalRange.location <= touchOriginRange.location { range.location = finalRange.location range.length = touchOriginRange.location - finalRange.location + touchOriginRange.length } else if finalRange.location > touchOriginRange.location { if finalRange.location <= touchOriginRange.location + touchOriginRange.length - 1 { range.location = finalRange.location range.length = touchOriginRange.location + touchOriginRange.length - finalRange.location } else { range.location = touchOriginRange.location + touchOriginRange.length range.length = finalRange.location - range.location } } } selectedRange = range rects = rangeRects(range: selectedRange, ctframe: ctFrame) // 显示光标 showCursor() setNeedsDisplay() } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { isTouchCursor = false touchOriginRange = selectedRange } func rangeRects(range:NSRange, ctframe:CTFrame?) ->[CGRect] { var rects:[CGRect] = [] guard let ctframe = ctframe else { return rects } guard range.location != NSNotFound else { return rects } var lines = CTFrameGetLines(ctframe) as Array var origins = [CGPoint](repeating: CGPoint.zero, count: lines.count) CTFrameGetLineOrigins(ctframe, CFRange(location: 0, length: 0), &origins) for index in 0..<lines.count { let line = lines[index] as! CTLine let origin = origins[index] let lineCFRange = CTLineGetStringRange(line) if lineCFRange.location != NSNotFound { let lineRange = NSRange(location: lineCFRange.location, length: lineCFRange.length) if lineRange.location + lineRange.length > range.location && lineRange.location < (range.location + range.length) { var ascent: CGFloat = 0 var descent: CGFloat = 0 var startX: CGFloat = 0 var contentRange = NSRange(location: range.location, length: 0) let end = min(lineRange.location + lineRange.length, range.location + range.length) contentRange.length = end - contentRange.location CTLineGetTypographicBounds(line, &ascent, &descent, nil) let y = origin.y - descent startX = CTLineGetOffsetForStringIndex(line, contentRange.location, nil) let endX = CTLineGetOffsetForStringIndex(line, contentRange.location + contentRange.length, nil) let rect = CGRect(x: origin.x + startX, y: y, width: endX - startX, height: ascent + descent) rects.append(rect) } } } return rects } func touchLocation(point:CGPoint, str:String = "") ->NSRange { var touchRange = NSMakeRange(0, 0) guard let ctFrame = self.ctFrame else { return touchRange } var lines = CTFrameGetLines(ctFrame) as Array var origins = [CGPoint](repeating: CGPoint.zero, count: lines.count) CTFrameGetLineOrigins(ctFrame, CFRange(location: 0, length: 0), &origins) for index in 0..<lines.count { let line = lines[index] as! CTLine let origin = origins[index] var ascent: CGFloat = 0 var descent: CGFloat = 0 CTLineGetTypographicBounds(line, &ascent, &descent, nil) let lineRect = CGRect(x: origin.x, y: bounds.height - origin.y - (ascent + descent), width: CTLineGetOffsetForStringIndex(line, 100000, nil), height: ascent + descent) if lineRect.contains(point) { let lineRange = CTLineGetStringRange(line) for rangeIndex in 0..<lineRange.length { let location = lineRange.location + rangeIndex var offsetX = CTLineGetOffsetForStringIndex(line, location, nil) var offsetX2 = CTLineGetOffsetForStringIndex(line, location + 1, nil) offsetX += origin.x offsetX2 += origin.x let runs = CTLineGetGlyphRuns(line) as Array for runIndex in 0..<runs.count { let run = runs[runIndex] as! CTRun let runRange = CTRunGetStringRange(run) if runRange.location <= location && location <= (runRange.location + runRange.length - 1) { // 说明在当前的run中 var ascent: CGFloat = 0 var descent: CGFloat = 0 CTRunGetTypographicBounds(run, CFRange(location: 0, length: 0), &ascent, &descent, nil) let frame = CGRect(x: offsetX, y: bounds.height - origin.y - (ascent + descent), width: (offsetX2 - offsetX)*2, height: ascent + descent) if frame.contains(point) { touchRange = NSRange(location: location, length: min(2, lineRange.length + lineRange.location - location)) } } } } } } return touchRange } func buildContent(attr:NSAttributedString, andImages:[ZSImageData] , settings:CTSettings) { attributeString = NSMutableAttributedString(attributedString: attr) imageIndex = 0 let framesetter = CTFramesetterCreateWithAttributedString(attr as CFAttributedString) let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, CGSize(width: settings.pageRect.size.width, height: CGFloat.greatestFiniteMagnitude), nil) let path = CGMutablePath() path.addRect(CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: settings.pageRect.width, height: textSize.height))) let ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) self.ctFrame = ctframe self.imageModels = andImages attachImages(andImages, ctframe: ctframe, margin: settings.margin) setNeedsDisplay() } func build(withAttrString attrString: NSAttributedString, andImages images: [[String: Any]]) { imageIndex = 0 //4 let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString) let settings = CTSettings.shared let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, CGSize(width: settings.pageRect.size.width, height: CGFloat.greatestFiniteMagnitude), nil) self.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: textSize.height) if let parentView = self.superview as? UIScrollView { parentView.contentSize = CGSize(width: self.bounds.width, height: textSize.height) } let path = CGMutablePath() path.addRect(CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: settings.pageRect.width, height: textSize.height))) let ctframe = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) self.ctFrame = ctframe attachImagesWithFrame(images, ctframe: ctframe, margin: settings.margin) } func attachImages(_ images: [ZSImageData],ctframe: CTFrame,margin: CGFloat) { if images.count == 0 { return } let lines = CTFrameGetLines(ctframe) as NSArray var origins = [CGPoint](repeating: .zero, count: lines.count) CTFrameGetLineOrigins(ctframe, CFRangeMake(0, 0), &origins) var nextImage:ZSImageData? = imageModels[imageIndex] for lineIndex in 0..<lines.count { if nextImage == nil { break } let line = lines[lineIndex] as! CTLine if let glyphRuns = CTLineGetGlyphRuns(line) as? [CTRun] { for run in glyphRuns { let runAttr = CTRunGetAttributes(run) as? [NSAttributedString.Key:Any] let delegate = runAttr?[(kCTRunDelegateAttributeName as NSAttributedString.Key)] if delegate == nil { continue } var imgBounds: CGRect = .zero var ascent: CGFloat = 0 var descent: CGFloat = 0 imgBounds.size.width = CGFloat(CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, nil)) imgBounds.size.height = ascent + descent let xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil) imgBounds.origin.x = origins[lineIndex].x + xOffset imgBounds.origin.y = origins[lineIndex].y imgBounds.origin.y -= descent; let pathRef = CTFrameGetPath(ctframe) let colRect = pathRef.boundingBox let delegateBounds = imgBounds.offsetBy(dx: colRect.origin.x, dy: colRect.origin.y) nextImage!.imagePosition = delegateBounds imageModels[imageIndex].imagePosition = imgBounds imageIndex! += 1 if imageIndex < images.count { nextImage = images[imageIndex] } else { nextImage = nil } } } } } func attachImagesWithFrame(_ images: [[String: Any]], ctframe: CTFrame, margin: CGFloat) { //1 let lines = CTFrameGetLines(ctframe) as NSArray //2 var origins = [CGPoint](repeating: .zero, count: lines.count) CTFrameGetLineOrigins(ctframe, CFRangeMake(0, 0), &origins) //3 var nextImage = images[imageIndex] guard var imgLocation = nextImage["location"] as? Int else { return } //4 for lineIndex in 0..<lines.count { let line = lines[lineIndex] as! CTLine //5 if let glyphRuns = CTLineGetGlyphRuns(line) as? [CTRun], let imageFilename = nextImage["filename"] as? String, let img = UIImage(named: imageFilename) { for run in glyphRuns { // 1 let runRange = CTRunGetStringRange(run) if runRange.location > imgLocation || runRange.location + runRange.length <= imgLocation { continue } //2 var imgBounds: CGRect = .zero var ascent: CGFloat = 0 imgBounds.size.width = CGFloat(CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, nil, nil)) imgBounds.size.height = ascent //3 let xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, nil) imgBounds.origin.x = origins[lineIndex].x + xOffset imgBounds.origin.y = origins[lineIndex].y //4 self.images += [(image: img, frame: imgBounds)] //5 imageIndex! += 1 if imageIndex < images.count { nextImage = images[imageIndex] imgLocation = (nextImage["location"] as AnyObject).intValue } } } } } // MARK: - Life Cycle override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } context.textMatrix = .identity context.translateBy(x: 0, y: bounds.size.height) context.scaleBy(x: 1.0, y: -1.0) if rects.count > 0 { let lineRects = rects.map { rect -> CGRect in return CGRect(x: rect.origin.x + 2, y: rect.origin.y, width: rect.width, height: rect.height) } let fillPath = CGMutablePath() UIColor(red:0.92, green:0.5, blue:0.5, alpha:1.00).withAlphaComponent(0.5).setFill() fillPath.addRects(lineRects) context.addPath(fillPath) context.fillPath() } CTFrameDraw(ctFrame!, context) for imageData in images { if let image = imageData.image.cgImage { let imgBounds = imageData.frame context.draw(image, in: imgBounds) } } for imageModel in imageModels { if let image = imageModel.image { context.draw(image.cgImage!, in: imageModel.imagePosition) continue } if let url = URL(string: imageModel.parse?.url ?? "" ) { ImageDownloader.default.downloadImage(with: url, options: nil, progressBlock: nil) { [weak self] (result) in switch result { case .success(let value): print(value.image) self!.imageModels[self?.indexOfModel(model: imageModel, models: self!.imageModels) ?? 0].image = value.image self?.setNeedsDisplay() case .failure(let error): print(error) } } } } } func indexOfModel(model:ZSImageData, models:[ZSImageData]) ->Int { var index = 0 for data in models { if data.parse?.url == model.parse?.url { break } index += 1 } return index } }
fc39ab6e04414dade81b1faa6dc97b61
42.285115
195
0.558047
false
false
false
false
WestlakeAPC/game-off-2016
refs/heads/master
external/Fiber2D/Fiber2D/Scheduling.swift
apache-2.0
1
// // Scheduling.swift // Fiber2D // // Created by Andrey Volodin on 28.08.16. // Copyright © 2016 s1ddok. All rights reserved. // public typealias Time = Float extension Timer { func forEach(block: (Timer) -> Void) { var timer: Timer? = self while timer != nil { block(timer!) timer = timer!.next } } func removeRecursive(skip: Timer) -> Timer? { if self === skip { return self.next } else { self.next = self.next?.removeRecursive(skip: skip) return self } } } // Targets are things that can have update: and fixedUpdate: methods called by the scheduler. // Scheduled blocks (Timers) can be associated with a target to inherit their priority and paused state. internal final class ScheduledTarget { weak var target: Node? var timers: Timer? var actions = [ActionContainer]() var empty: Bool { return timers == nil && !enableUpdates } var hasActions: Bool { return !actions.isEmpty } var paused = false { didSet { if paused != oldValue { let pause = self.paused timers?.forEach { $0.paused = pause } } } } var enableUpdates = false func invalidateTimers() { timers?.forEach { $0.invalidate() } } func add(action: ActionContainer) { actions.append(action) } func removeAction(by tag: Int) { actions = actions.filter { $0.tag != tag } } func remove(timer: Timer) { timers = timers?.removeRecursive(skip: timer) } init(target: Node) { self.target = target } }
68bf531f465ce96f87fd69af53a5de52
22.917808
104
0.553265
false
false
false
false
rossharper/raspberrysauce-ios
refs/heads/master
raspberrysauce-ios/Authentication/TokenAuthManager.swift
apache-2.0
1
// // TokenAuthManager.swift // raspberrysauce-ios // // Created by Ross Harper on 20/12/2016. // Copyright © 2016 rossharper.net. All rights reserved. // import Foundation struct AuthConfig { let tokenRequestEndpoint: URL } class TokenAuthManager : AuthManager { let config : AuthConfig let networking : Networking let tokenStore : TokenStore weak var observer : AuthObserver? init(config: AuthConfig, networking: Networking, tokenStore: TokenStore) { self.config = config self.networking = networking self.tokenStore = tokenStore NotificationCenter.default.addObserver(forName: Notification.Name(rawValue:"SignIn"), object: nil, queue: nil, using:notifySignIn) NotificationCenter.default.addObserver(forName: Notification.Name(rawValue:"SignInFailed"), object: nil, queue: nil, using:notifySignInFailed) NotificationCenter.default.addObserver(forName: Notification.Name(rawValue:"SignedOut"), object: nil, queue: nil, using:notifySignedOut) } deinit { NotificationCenter.default.removeObserver(self) } func isSignedIn() -> Bool { let token = tokenStore.get() return token != nil } func signIn(username: String, password: String) { // TODO: extract to SauceAPIClient?? networking.post(url: config.tokenRequestEndpoint, body: "username=\(username)&password=\(password)", onSuccess: {responseBody in guard let tokenValue = String(data: responseBody, encoding: .utf8) else { return } self.tokenStore.put(token: Token(value: tokenValue)) self.broadcastSignIn() }, onError: { _ in self.broadcastSignInFailed() }) } func signOut() { deleteAccessToken() broadcastSignedOut() } func setAuthObserver(observer: AuthObserver?) { self.observer = observer } func getAccessToken() -> Token? { return tokenStore.get() } func deleteAccessToken() { tokenStore.remove() } private func broadcastSignIn() { NotificationCenter.default.post(name: Notification.Name(rawValue:"SignIn"), object: nil,userInfo: nil) } private func broadcastSignInFailed() { NotificationCenter.default.post(name: Notification.Name(rawValue:"SignInFailed"), object: nil,userInfo: nil) } private func broadcastSignedOut() { NotificationCenter.default.post(name: Notification.Name(rawValue:"SignedOut"), object: nil,userInfo: nil) } @objc func notifySignIn(notification: Notification) { observer?.onSignedIn() } @objc private func notifySignInFailed(notification: Notification) { observer?.onSignInFailed() } @objc private func notifySignedOut(notification: Notification) { observer?.onSignedOut() } }
e36de84beef3cd7df4ec3b247efbcd81
30.712766
150
0.645421
false
true
false
false
apple/swift-nio
refs/heads/main
Sources/NIOCore/IO.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if os(Windows) import ucrt import func WinSDK.FormatMessageW import func WinSDK.LocalFree import let WinSDK.FORMAT_MESSAGE_ALLOCATE_BUFFER import let WinSDK.FORMAT_MESSAGE_FROM_SYSTEM import let WinSDK.FORMAT_MESSAGE_IGNORE_INSERTS import let WinSDK.LANG_NEUTRAL import let WinSDK.SUBLANG_DEFAULT import typealias WinSDK.DWORD import typealias WinSDK.WCHAR import typealias WinSDK.WORD internal func MAKELANGID(_ p: WORD, _ s: WORD) -> DWORD { return DWORD((s << 10) | p) } #elseif os(Linux) || os(Android) import Glibc #elseif os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #endif /// An `Error` for an IO operation. public struct IOError: Swift.Error { @available(*, deprecated, message: "NIO no longer uses FailureDescription.") public enum FailureDescription { case function(StaticString) case reason(String) } /// The actual reason (in an human-readable form) for this `IOError`. private var failureDescription: String @available(*, deprecated, message: "NIO no longer uses FailureDescription, use IOError.description for a human-readable error description") public var reason: FailureDescription { return .reason(self.failureDescription) } private enum Error { #if os(Windows) case windows(DWORD) case winsock(CInt) #endif case errno(CInt) } private let error: Error /// The `errno` that was set for the operation. public var errnoCode: CInt { switch self.error { case .errno(let code): return code #if os(Windows) default: fatalError("IOError domain is not `errno`") #endif } } #if os(Windows) public init(windows code: DWORD, reason: String) { self.error = .windows(code) self.failureDescription = reason } public init(winsock code: CInt, reason: String) { self.error = .winsock(code) self.failureDescription = reason } #endif /// Creates a new `IOError`` /// /// - parameters: /// - errorCode: the `errno` that was set for the operation. /// - reason: the actual reason (in an human-readable form). public init(errnoCode code: CInt, reason: String) { self.error = .errno(code) self.failureDescription = reason } /// Creates a new `IOError`` /// /// - parameters: /// - errorCode: the `errno` that was set for the operation. /// - function: The function the error happened in, the human readable description will be generated automatically when needed. @available(*, deprecated, renamed: "init(errnoCode:reason:)") public init(errnoCode code: CInt, function: StaticString) { self.error = .errno(code) self.failureDescription = "\(function)" } } /// Returns a reason to use when constructing a `IOError`. /// /// - parameters: /// - errorCode: the `errno` that was set for the operation. /// - reason: what failed /// - returns: the constructed reason. private func reasonForError(errnoCode: CInt, reason: String) -> String { if let errorDescC = strerror(errnoCode) { return "\(reason): \(String(cString: errorDescC)) (errno: \(errnoCode))" } else { return "\(reason): Broken strerror, unknown error: \(errnoCode)" } } #if os(Windows) private func reasonForWinError(_ code: DWORD) -> String { let dwFlags: DWORD = DWORD(FORMAT_MESSAGE_ALLOCATE_BUFFER) | DWORD(FORMAT_MESSAGE_FROM_SYSTEM) | DWORD(FORMAT_MESSAGE_IGNORE_INSERTS) var buffer: UnsafeMutablePointer<WCHAR>? // We use `FORMAT_MESSAGE_ALLOCATE_BUFFER` in flags which means that the // buffer will be allocated by the call to `FormatMessageW`. The function // expects a `LPWSTR` and expects the user to type-pun in this case. let dwResult: DWORD = withUnsafeMutablePointer(to: &buffer) { $0.withMemoryRebound(to: WCHAR.self, capacity: 2) { FormatMessageW(dwFlags, nil, code, MAKELANGID(WORD(LANG_NEUTRAL), WORD(SUBLANG_DEFAULT)), $0, 0, nil) } } guard dwResult > 0, let message = buffer else { return "unknown error \(code)" } defer { LocalFree(buffer) } return String(decodingCString: message, as: UTF16.self) } #endif extension IOError: CustomStringConvertible { public var description: String { return self.localizedDescription } public var localizedDescription: String { #if os(Windows) switch self.error { case .errno(let errno): return reasonForError(errnoCode: errno, reason: self.failureDescription) case .windows(let code): return reasonForWinError(code) case .winsock(let code): return reasonForWinError(DWORD(code)) } #else return reasonForError(errnoCode: self.errnoCode, reason: self.failureDescription) #endif } } // FIXME: Duplicated with NIO. /// An result for an IO operation that was done on a non-blocking resource. enum CoreIOResult<T: Equatable>: Equatable { /// Signals that the IO operation could not be completed as otherwise we would need to block. case wouldBlock(T) /// Signals that the IO operation was completed. case processed(T) } internal extension CoreIOResult where T: FixedWidthInteger { var result: T { switch self { case .processed(let value): return value case .wouldBlock(_): fatalError("cannot unwrap CoreIOResult") } } }
295bb9a828a606810a64786f7b6f209e
31.278947
143
0.633295
false
false
false
false